Skip to content

Commit c7ef49c

Browse files
committed
最小生成树Prim算法
1 parent e5e35b2 commit c7ef49c

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Prim.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#include <cstdio>
2+
#include <queue>
3+
4+
typedef long long ll;
5+
6+
using namespace std;
7+
8+
struct vertex
9+
{
10+
int first;
11+
}V[5010];
12+
13+
struct edge
14+
{
15+
int endp, next, w;
16+
}E[400010];
17+
18+
struct queue_node
19+
{
20+
int u;
21+
ll dis;
22+
queue_node(int _u = 0, ll _dis = 0) : u(_u), dis(_dis) { }
23+
};
24+
25+
int n, m, ec = 2;
26+
bool vis[5010];
27+
28+
inline void add_edge(int u, int v, int w)
29+
{
30+
E[ec].next = V[u].first;
31+
V[u].first = ec;
32+
E[ec].endp = v;
33+
E[ec].w = w;
34+
ec++;
35+
}
36+
37+
inline bool operator < (const queue_node &x, const queue_node &y)
38+
{
39+
return x.dis > y.dis;
40+
}
41+
42+
ll prim()
43+
{
44+
ll res = 0;
45+
int vc = 0;
46+
priority_queue<queue_node> Q;
47+
Q.push(queue_node(1, 0));
48+
while (vc < n)
49+
{
50+
queue_node u = Q.top();
51+
Q.pop();
52+
if (vis[u.u] == false)
53+
{
54+
res += u.dis;
55+
vis[u.u] = true;
56+
vc++;
57+
for (int cur = V[u.u].first; cur != 0; cur = E[cur].next)
58+
{
59+
Q.push(queue_node(E[cur].endp, E[cur].w));
60+
}
61+
}
62+
}
63+
return res;
64+
}
65+
66+
int main()
67+
{
68+
scanf("%d%d", &n, &m);
69+
int u, v, w;
70+
for (int i = 0; i < m; i++)
71+
{
72+
scanf("%d%d%d", &u, &v, &w);
73+
add_edge(u, v, w);
74+
add_edge(v, u, w);
75+
}
76+
printf("%lld\n", prim());
77+
return 0;
78+
}

0 commit comments

Comments
 (0)