【最小生成树】还是畅通工程 最小生成树板子题

Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
 

Output
对每个测试用例,在1行里输出最小的公路总长度。
 

Sample Input
 
  
1 2 1 
1 3 2 
2 3 4 
1 2 1 
1 3 4 
1 4 1 
2 3 3 
2 4 2 
3 4 5 
0
Sample Output
 
  
5

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int pre[105];

struct mmp
{
    int a,b,l;
    bool operator < (const mmp& x)const
    {
        return l<x.l;
    }
}q[10005];

//bool cmp(mmp a,mmp b)可以用加个函数的方法用sort进行排序
//{
//    return a.l<b.l;
//}

int found(int r)//寻找祖先
{
    if(pre[r]==r)
        return pre[r];
    else
    {
        pre[r]=found(pre[r]);
        return pre[r];
    }
}

void un(int a,int b)//合并祖先
{
    int a1=found(a);
    int b1=found(b);
    if(a1!=b1)
        pre[b1]=a1;
}

int main()
{
    int m,n;
    while(~scanf("%d",&n))
    {
        if(n==0)
            break;
        m=n*(n-1)/2;
        int i,j,k=0,s=0;
        for(i=0;i<=n;i++)
            pre[i]=i;
        for(i=0;i<m;i++)
            scanf("%d %d %d",&q[i].a,&q[i].b,&q[i].l);
        sort(q,q+m);
        for(i=0;i<m;i++)
        {
            if(found(q[i].a)!=found(q[i].b))
            {
                un(q[i].a,q[i].b);
                k++;
                s+=q[i].l;
            }
            if(k==n-1)
                break;
        }
        printf("%d\n",s);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41984014/article/details/80411230
今日推荐