最小產生樹——最短網路Agri-Net

來源:互聯網
上載者:User

標籤:ble   name   組成   void   main   共用   ace   nbsp   idt   

最短網路Agri-Net 【問題描述】  農民約翰被選為他們鎮的鎮長!他其中一個競選承諾就是在鎮上建立起互連網,並串連到所有的農場。當然,他需要你的協助。約翰已經給他的農場安排了一條高速的網路線路,他想把這條線路共用給其他農場。為了用最小的消費,他想鋪設最短的光纖去串連所有的農場。你將得到一份各農場之間串連費用的列表,你必須找出能串連所有農場並所用光纖最短的方案。每兩個農場間的距離不會超過100000。【輸入格式】 
第一行: 農場的個數,N(3<=N<=100)。
第二行..結尾 

 

 

後來的行包含了一個N*N的矩陣,表示每個農場之間的距離。理論上,他們是N行,每行由N個用空格分隔的數組成,實際上,他們限制在80個字元,因此,某些行會緊接著另一些行。當然,對角線將會是0,因為不會有線路從第i個農場到它本身。

 

 

 

【輸出格式】    只有一個輸出,其中包含串連到每個農場的光纖的最小長度。【輸入範例】agrinet.in    4    0  4  9  21    4  0  8  17    9  8  0  16    21 17 16  0【輸出範例】agrinet.out  28 
 1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5  6 struct point{ 7     int x; 8     int y; 9     int w;10 }a[10000];11 int dad[101];12 int n,m,x,k,tot;13 14 int find(int x)15 {16     if(dad[x]!=x) dad[x]=find(dad[x]);17     return dad[x];18 }19 20 void unionn(int a,int b)21 {22     int r1=find(a);23     int r2=find(b);24     if(r1!=r2)25     dad[r1]=r2;26 }27 28 int cmp(const point &a,const point &b)29 {30     if(a.w<b.w) return 1;31     else return 0;32 }33 34 int main()35 {36     cin>>n;37     for(int i=1;i<=n;i++)38       for(int j=1;j<=n;j++){39           cin>>x;40           if(x!=0){41               m++;42               a[m].x=i,a[m].y=j,a[m].w=x;43           }44       }45     for(int i=1;i<=n;i++)46      dad[i]=i;47     sort(a+1,a+m+1,cmp);48     for(int i=1;i<=m;i++){49         if(find(a[i].x)!=find(a[i].y)){50             unionn(a[i].x,a[i].y);51             tot+=a[i].w;52             k++;53         }54         if(k==n-1) break;55     }56     cout<<tot;57     return 0;58 }

 

最小產生樹——最短網路Agri-Net

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.