Hdoj1233還是暢通工程

Hdoj1233:

還是暢通工程

Problem Description
某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),並要求鋪設的公路總長度爲最小。請計算最小的公路總長度。
 

Input
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨後的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。爲簡單起見,村莊從1到N編號。
當N爲0時,輸入結束,該用例不被處理。
 

Output
對每個測試用例,在1行裏輸出最小的公路總長度。
 

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

Sample Output
3 5
Hint
Hint
Huge input, scanf is recommended.
 

Source
 

#include <cstdio>
#include <algorithm>
using namespace std;
struct node{
    int x,y,z;
    bool operator<(const node &q)const{
        return z<q.z;
    }
}a[5000];
int n,p[101],ans;
int fid(int x)
{
    return p[x]==x?x:fid(p[x]);
}
void join(int x,int y,int c)
{
    int f1=fid(x);
    int f2=fid(y);
    if(f1!=f2)
    {
        ans+=a[c].z;
        p[f1]=f2;
    }
}
int main()
{
    while(scanf("%d",&n)!=EOF&&n)
    {
        ans=0;
        for(int i=1;i<=n;i++)
            p[i]=i;
        int m=n*(n-1)/2;
        for(int i=0;i<m;i++)
            scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].z);
        sort(a,a+m);
        for(int i=0;i<m;i++)
            join(a[i].x,a[i].y,i);
        printf("%d\n",ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章