HDU 1879 继续畅通工程

思想:最小生成树,Kruskal。

#include
#include
#include
#include
#include
using namespace std;
int per[105];
int n;
struct Edge
{
    int x;
    int y;
    int dis;
}edge[5005];

bool cmp(Edge a, Edge b)
{
    return a.dis < b.dis;
}
void init()
{
    for(int i = 0; i <= n; i ++)
        per[i] = i;
}
int find(int x)
{
    if(x != per[x])
        per[x] = find(per[x]);
    return per[x];
}
void join(int x, int y)
{
    int s = find(x);
    int t = find(y);
    if(s != t)
    {
        per[s] = t;
    }
}
int kruskal()
{
    sort(edge+1,edge+n*(n-1)/2+1,cmp);
    int sum = 0, count = 0;
    for(int i = 1; i <= n*(n-1)/2; i++)
    {
        int s = find(edge[i].x);
        int e = find(edge[i].y);
        if(s != e)
        {
            join(s,e);
            sum += edge[i].dis;
            count ++;
        }
        if(count == n-1)
            break;
    }
    return sum;
}
int main()
{
    while(scanf("%d",&n)!= EOF && n)
    {
        init();
        int a, b, d, f;
        for(int i = 1; i <= n*(n-1)/2; i ++)
        {
            scanf("%d%d%d%d",&a,&b,&d,&f);
            edge[i].x = a;
            edge[i].y = b;
            if(f == 0)
                edge[i].dis = d;
            else if(f == 1)
                edge[i].dis = 0;
        }
        int h = kruskal();
        printf("%d\n",h);
    }
    return 0;
}

如有错误,欢迎指出~

你可能感兴趣的:(acm,图论)