還是暢通工程(MST,不存在得不到MST的情況)

來源:互聯網
上載者:User
還是暢通工程 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 53511    Accepted Submission(s): 24304 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 

注意:該例不存在得不到最小產生樹的情況,所以最後我們並沒有對所有節點是否屬於同一個集合進行判斷。若可能出現此情況,則該步不能省略。

#include<stdio.h>#include<math.h>#include<algorithm>using namespace std;#define INF 0x3f3f3f3f#define N 1000int Tree[N];struct edge{int a,b;    int cost ;    bool operator< (const edge &A)const{        return cost<A.cost;    }}edge[6000];int findroot(int x)//尋找根節點{    if(Tree[x]==-1)        return x;    else{        int tmp=findroot(Tree[x]);        Tree[x]=tmp;        return tmp;    }}int main(){    int n,m,i,j;    while(~scanf("%d",&n)&&n!=0)    { m=n*(n-1)/2;        for( i=1;i<=m;i++)        {            scanf("%d%d%d",&edge[i].a,&edge[i].b,&edge[i].cost);        }        sort(edge+1,edge+1+m);        for(i=1;i<=n;i++)Tree[i]=-1;//初始時所有節點都屬於孤立的集合        int ans=0; int a,b;        for( i=1;i<=m;i++){            a=findroot(edge[i].a);            b=findroot(edge[i].b);            if(a!=b){                Tree[a]=b;                ans+=edge[i].cost;//累計該邊權值            }        } printf("%d\n",ans );      }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.