繼續暢通工程 HDU - 1879(最小生成樹)
#include <stdio.h>
#include <algorithm>using namespace std;
struct Node
{
int a, b;
int w, s;
}list[5000];bool cmp(Node x, Node y)
{
return x.w < y.w;
}int t[110];
int findRoot(int x)
{
if(t[x] == x)
return x;
int tmp = findRoot(t[x]);
t[x] = tmp;
return tmp;
}int main()
{
int n;
while(~scanf("%d", &n) && n != 0)
{
for(int i = 1; i <= n; i++)
t[i] = i;
for(int i = 0; i < n*(n-1)/2; i++)
{
scanf("%d %d %d %d", &list[i].a, &list[i].b, &list[i].w, &list[i].s);
if(list[i].s == 1) //如果已經修建
t[list[i].a] = list[i].b;
}
sort(list, list+n*(n-1)/2, cmp);
int ans = 0;
for(int i = 0; i < n*(n-1)/2; i++)
{
int x1 = findRoot(list[i].a);
int x2 = findRoot(list[i].b);
if(x1 != x2)
{
t[x1] = x2;
//if(list[i].s == 0)
ans += list[i].w;
}
}
printf("%d\n", ans);
}
return 0;
}