Prim

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
struct edge{
int to, nxt, d;
bool operator<(const edge& b)const {
return d > b.d;
}
}f[20 * maxn];
int head[maxn], tot = 0;
void add(int x, int y, int d){
f[++tot].to = y; f[tot].d = d; f[tot].nxt = head[x]; head[x] = tot;
}

int p, r, vis[maxn];
int prim(){
ms(vis, 0); vis[1] = 1;
priority_queue<edge> q;
int ans = 0;
for (int i = head[1]; i; i = f[i].nxt){
q.push(f[i]);
}
while (!q.empty()){
edge t = q.top(); q.pop();
if (vis[t.to]) continue;
vis[t.to] = 1;
ans += t.d;
for (int i = head[t.to]; i; i = f[i].nxt){
q.push(f[i]);
}
}
return ans;
}
  • 本文作者: XLor
  • 本文链接: https://xlor.cn/2018/8/prim/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!