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
注意:当两点之间已有路时,把这两点的路长设为0,然后套用kruskal就行了
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct edge { int a, b, w; }e[5050]; int p[5050]; int cmp(edge a, edge b) { return a.w < b.w; } int find(int v) { if (p[v] != v) p[v] = find(p[v]); return p[v]; } int join(edge e) { int x = find(e.a), y = find(e.b); if (x != y) { p[x] = y; return e.w; } return 0; } int kruskal(int m, int n) { int ans = 0; for(int i=1; i<=n; i++) p[i] = i; sort(e, e+m, cmp); for(int i = 0; i<m; i++) ans += join(e[i]); return ans; } int main() { int n; while(scanf("%d", &n) == 1 && n) { int m = n * (n-1) / 2, t; for(int i=0; i<m; i++) { scanf("%d %d %d %d", &e[i].a, &e[i].b, &e[i].w, &t); if(t) e[i].w = 0; } printf("%d\n", kruskal(m, n)); } return 0; }