http://acm.hdu.edu.cn/showproblem.php?pid=1863
复习考研练练写Prim,第一次写,乱搞的,有点难看
邻接表+堆
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue> using namespace std; int n, m, cnt, ct, head[], vis[]; struct Edge {
int s, t, v, next;
friend bool operator < (Edge a, Edge b) {
return a.v > b.v;
}
}e[]; void add(int s, int t, int v) {
e[cnt].t = t; e[cnt].v = v; e[cnt].next = head[s]; head[s] = cnt++;
} int Prim() {
int res = ;
priority_queue <Edge> q;
vis[] = ;
ct++;
for(int i = head[]; i != -; i = e[i].next) {
q.push(e[i]);
}
while(!q.empty()) {
Edge e1 = q.top();
q.pop();
vis[e1.t] = ;
res += e1.v;
ct++;
if(ct == m) return res;
for(int i = head[e1.t]; i != -; i = e[i].next) {
if(!vis[e[i].t]) q.push(e[i]);
}
}
return -;
} int main() {
while(~scanf("%d%d", &n, &m), n) {
cnt = ct = ;
memset(head, -, sizeof(head));
memset(vis, , sizeof(vis));
for(int i = ; i < n; i++) {
int s, t, v;
scanf("%d%d%d", &s, &t, &v);
add(s, t, v);
}
int ans = Prim();
if(ans == -) puts("?");
else printf("%d\n", ans);
}
return ;
}