题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1863
新学习了prim算法,把之前的dijkstra改了改,d数组用来存上一个距离当前节点最近的长度,而不是源点到当前最近的长度就可以了。初始化d为inf,如果条件不够那和算出来必定>inf(没考虑溢出,因为我定义的inf并不是很大)(题目小坑,把n和m输入顺序反了一下。)
1 #pragma warning(disable:4996) 2 3 4 #include <algorithm> 5 #include <iostream> 6 #include <iomanip> 7 #include <cstring> 8 #include <climits> 9 #include <complex> 10 #include <fstream> 11 #include <cassert> 12 #include <cstdio> 13 #include <bitset> 14 #include <vector> 15 #include <deque> 16 #include <queue> 17 #include <stack> 18 #include <ctime> 19 #include <set> 20 #include <map> 21 #include <cmath> 22 23 using namespace std; 24 25 const int maxn = 105; 26 const int inf = 0xffffff; 27 int d[maxn]; 28 int G[maxn][maxn]; 29 int vis[maxn]; 30 int n, m; 31 32 void init() { 33 memset(vis, 0, sizeof(vis)); 34 for(int i = 0; i <= n; i++) { 35 d[i] = inf; 36 for(int j = 0; j <= n; j++) { 37 G[i][j] = G[j][i] = inf; 38 } 39 G[i][i] = 0; 40 } 41 } 42 43 int prim(int start) { 44 d[start] = 0; 45 for(int i = 1; i <= n; i++) { 46 int u = -1; 47 for(int j = 1; j <= n; j++) { 48 if(!vis[j]) { 49 if(u == -1 || d[j] < d[u]) { 50 u = j; 51 } 52 } 53 } 54 vis[u] = 1; 55 for(int j = 1; j <= n; j++) { 56 if(!vis[j]) { 57 d[j] = min(G[u][j], d[j]); 58 } 59 } 60 } 61 int sp = 0; 62 for(int i = 1; i <= n; i++) { 63 sp += d[i]; 64 } 65 return sp; 66 } 67 68 int main() { 69 // freopen("in", "r", stdin); 70 int u, v, w; 71 while(~scanf("%d %d", &m, &n) && m) { 72 init(); 73 while(m--) { 74 scanf("%d %d %d", &u, &v, &w); 75 if(w < G[u][v]) { 76 G[u][v] = G[v][u] = w; 77 } 78 } 79 int len = prim(1); 80 if(len > inf) puts("?"); 81 else printf("%d ", len); 82 } 83 }