HUD 1233 还是畅通工程

    思想:简单最小生成树,kruskal。



#include
#include
#include
#include
#include
#include
using namespace std;
int per[105];
int m;
void init()
{
    for(int i = 0; i < 105; i ++)
    {
        per[i] = i;
    }
}
struct Edge
{
    int x;
    int y;
    int dis;
}edge[5005];
bool cmp(Edge a, Edge b)
{
    return a.dis < b.dis;
}
int find(int x)
{
    int r = x;
    while(r != per[r])
        r = per[r];
    int i = x;
    int j;
    while(i != r)
    {
        j = per[i];
        per[i] = r;
        i = j;
    }
    return r;
}
void join(int x, int y)
{
    int s = find(x);
    int e = find(y);
    if(s != e)
    {
        per[s] = e;
    }
}
int kruskal(int c)
{
    sort(edge+1,edge+c+1,cmp);
    int sum = 0,cnt = 0;
    for(int i = 1; i <= c; i ++)
    {
        int s = find(edge[i].x);
        int e = find(edge[i].y);
        if(s != e)
        {
            join(s,e);
            sum += edge[i].dis;
            cnt++;
        }
        if(cnt == m-1)
            break;
    }
    if(cnt < m-1)
        return -1;
    return sum;
}
int main()
{
    int n,a,b;
    while(scanf("%d%d",&n,&m)!= EOF && n)
    {
        init();
        int c = 0;
        for(int i = 1; i <= n; i ++)
        {
            scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].dis);
        }

        int d = kruskal(n);
        if(d == -1)
        {
            printf("?\n");
            continue;
        }
        printf("%d\n",d);

    }


    return 0;
}


如有错误,欢迎指出~

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