-
Notifications
You must be signed in to change notification settings - Fork 439
/
Prim.cpp
78 lines (68 loc) · 1.07 KB
/
Prim.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <cstdio>
#include <queue>
typedef long long ll;
using namespace std;
struct vertex
{
int first;
}V[5010];
struct edge
{
int endp, next, w;
}E[400010];
struct queue_node
{
int u;
ll dis;
queue_node(int _u = 0, ll _dis = 0) : u(_u), dis(_dis) { }
};
int n, m, ec = 2;
bool vis[5010];
inline void add_edge(int u, int v, int w)
{
E[ec].next = V[u].first;
V[u].first = ec;
E[ec].endp = v;
E[ec].w = w;
ec++;
}
inline bool operator < (const queue_node &x, const queue_node &y)
{
return x.dis > y.dis;
}
ll prim()
{
ll res = 0;
int vc = 0;
priority_queue<queue_node> Q;
Q.push(queue_node(1, 0));
while (vc < n)
{
queue_node u = Q.top();
Q.pop();
if (vis[u.u] == false)
{
res += u.dis;
vis[u.u] = true;
vc++;
for (int cur = V[u.u].first; cur != 0; cur = E[cur].next)
{
Q.push(queue_node(E[cur].endp, E[cur].w));
}
}
}
return res;
}
int main()
{
scanf("%d%d", &n, &m);
int u, v, w;
for (int i = 0; i < m; i++)
{
scanf("%d%d%d", &u, &v, &w);
add_edge(u, v, w);
add_edge(v, u, w);
}
printf("%lld\n", prim());
return 0;
}