3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5Huge input, scanf is recommended.HintHint
Kruskal:
#include<cstdio> #include<cstring> #include<cmath> #define mem(a, b) memset(a, (b), sizeof(a)) #define Wi(a) while(a--) #define Si(a) scanf("%d", &a) #define Pi(a) printf("%d\n", (a)) #include<algorithm> using namespace std; int per[200]; int n; struct node{ int from, to, val; }; node p[10010]; bool operator < (node a, node b) { return a.val < b.val; } void init() { for(int i = 0; i <= n ;i++) { per[i] = i; } } int find(int x) { return x==per[x] ? x : (per[x] = find(per[x])); } bool join(int x, int y) { int fx = find(x); int fy = find(y); if(fx!=fy){ per[fx] = fy; return true; } return false; } int main(){ while(Si(n)==1, n) { int m = n*(n-1)/2; init(); int i, j, k; for(i = 0; i < m; i++) scanf("%d%d%d", &p[i].from, &p[i].to, &p[i].val); sort(p, p+m); int ans = 0; for(i = 0; i < m; i++) { if(join(p[i].from, p[i].to)) ans += p[i].val; } Pi(ans); } return 0; }
=================================华丽的分割线====================================
Prim:
#include<cstdio> #include<cstring> #include<cmath> #define mem(a, b) memset(a, (b), sizeof(a)) #define Wi(a) while(a--) #define Si(a) scanf("%d", &a) #define Pi(a) printf("%d\n", (a)) #define INF 0x3f3f3f int map[150][150]; int vis[150]; int pay[150]; int n; void prim() { int i, j, k; int minn, ans = 0; mem(vis, 0); for(i = 1; i <= n; i++) { pay[i] = map[1][i]; } vis[1] = 1; for(i = 1; i < n; i++) { minn = INF; k = 1; for(j = 1; j <= n; j++) { if(!vis[j]&&pay[j]<minn) { minn = pay[j]; k = j; } } vis[k] = 1; ans += minn; for(j = 1; j <= n; j++) { if(!vis[j] && pay[j] > map[j][k]) pay[j] = map[j][k]; } } Pi(ans); } int main(){ while(Si(n)==1, n) { int x, y, v; int m = n*(n-1)/2; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(i==j) map[i][j] = 0; else map[i][j] = INF; } } Wi(m) { scanf("%d%d%d", &x, &y, &v); map[x][y] = map[y][x] = v; } prim(); } return 0; }