Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17838 Accepted Submission(s): 7680
3 1 2 1 0 1 3 2 0 2 3 4 0 3 1 2 1 0 1 3 2 0 2 3 4 1 3 1 2 1 0 1 3 2 1 2 3 4 1 0
3 1 0
又是一道模板题。。。只要通过最后一个数字将造价改一改就可以了。。完全不用在根据是否建造来排序了。
#include<stdio.h> #include<algorithm> using namespace std; int per[110], n; struct node { int u, v, w; }; node edge[5050]; int cmp(node a, node b){ return a.w < b.w; } void init(int m){ int i; for(i = 0; i <= m; ++i){ per[i] = i; } } int find(int x){ int r = x; while(per[r] != r) r = per[r]; per[x] = r; return r; } void kruskal(){ init(n); sort(edge, edge + n * (n - 1) / 2, cmp); int i, fx, fy, sum = 0; for(i = 0; i < n * (n - 1) / 2; ++i){ fx = find(edge[i].u); fy = find(edge[i].v); if(fx != fy){ sum += edge[i].w; per[fx] = fy; } } printf("%d\n", sum); } int main(){ while(~scanf("%d", &n), n){ int i,temp; for(i = 0; i < n * (n - 1) / 2; ++i){ scanf("%d%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w, &temp); if(temp == 1) edge[i].w = 0; } kruskal(); } return 0; }