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[105], vis[105]; struct Edge { int s, t, v, next; friend bool operator < (Edge a, Edge b) { return a.v > b.v; } }e[10005]; 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 = 0; priority_queue <Edge> q; vis[1] = 1; ct++; for(int i = head[1]; i != -1; i = e[i].next) { q.push(e[i]); } while(!q.empty()) { Edge e1 = q.top(); q.pop(); vis[e1.t] = 1; res += e1.v; ct++; if(ct == m) return res; for(int i = head[e1.t]; i != -1; i = e[i].next) { if(!vis[e[i].t]) q.push(e[i]); } } return -1; } int main() { while(~scanf("%d%d", &n, &m), n) { cnt = ct = 0; memset(head, -1, sizeof(head)); memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; i++) { int s, t, v; scanf("%d%d%d", &s, &t, &v); add(s, t, v); } int ans = Prim(); if(ans == -1) puts("?"); else printf("%d ", ans); } return 0; }