最短網路Agri-Net

來源:互聯網
上載者:User

標籤:cin   else   code   ios   algo   空格   can   矩陣   最小   

問題描述】  農民約翰被選為他們鎮的鎮長!他其中一個競選承諾就是在鎮上建立起互連網,並串連到所有的農場。當然,他需要你的協助。約翰已經給他的農場安排了一條高速的網路線路,他想把這條線路共用給其他農場。為了用最小的消費,他想鋪設最短的光纖去串連所有的農場。你將得到一份各農場之間串連費用的列表,你必須找出能串連所有農場並所用光纖最短的方案。每兩個農場間的距離不會超過100000。【輸入格式
第一行: 農場的個數,N3<=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<cstring> 4 #include<algorithm> 5 using namespace std; 6 int num=1; 7 struct node 8 { 9     int u;10     int v;11     int w;12     int next;13 }edge[10001];14 int head[10001];15 int f[10001];16 int tot=0;17 int cmp(const node &a,const node &b)18 {19     if(a.w<b.w)return 1;20     else return 0;21 }22 int find(int x)23 {24     if(f[x]!=x)25     f[x]=find(f[x]);26     return f[x];27 }28 void unionn(int x,int y)29 {30     int fx=find(x);31     int fy=find(y);32     if(fx!=fy)33     f[fx]=fy;34 }35 int main()36 {37     int n;38     scanf("%d",&n);39     for(int i=0;i<=n;i++)head[i]=-1;40     for(int i=0;i<=n;i++)f[i]=i;41     for(int i=1;i<=n;i++)42     {43         for(int j=1;j<=n;j++)44         {45             int kk;46             scanf("%d",&kk);47             if(kk!=0)48             {49                 edge[num].w=kk;50                 edge[num].u=i;51                 edge[num].v=j;52                 edge[num].next=head[i];53                 num++;54             }55         }56     }57     int k=0;58     sort(edge+1,edge+num,cmp);59     for(int i=1;i<=num-1;i++)60     {61         if(find(edge[i].u)!=find(edge[i].v))62         {63             unionn(edge[i].u,edge[i].v);64             tot=tot+edge[i].w;65             k++;66         }67         if(k==n-1)break;68     }69     printf("%d",tot);70     return 0;71 }

 

 

最短網路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.