-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01197_MST_Prim-Algorithm.cpp
More file actions
59 lines (48 loc) · 1002 Bytes
/
01197_MST_Prim-Algorithm.cpp
File metadata and controls
59 lines (48 loc) · 1002 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
#include <queue>
#define P pair<int, int>
using namespace std;
int v, e;
long long ans = 0;
bool visited[10001];
vector<P> graph[10001];
void prim()
{
priority_queue<P> pq;
pq.push(P(0, 1));
while (!pq.empty())
{
int cur = pq.top().second;
int cost = -pq.top().first;
pq.pop();
if (visited[cur])
continue;
visited[cur] = 1;
ans += cost;
for (int i = 0; i < graph[cur].size(); i++)
{
int next = graph[cur][i].second;
int ncost = graph[cur][i].first;
if (!visited[next])
pq.push(P(-ncost, next));
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin >> v >> e;
while (e--)
{
int a, b, c;
cin >> a >> b >> c;
graph[a].push_back(P(c, b));
graph[b].push_back(P(c, a));
}
prim();
cout << ans;
return 0;
}