洛穀 P1546 最短網路 Agri-Net Label:Water最小產生樹

來源:互聯網
上載者:User

標籤:break   span   距離   方案   輸出   label   翻譯   names   cow   

題目背景

農民約翰被選為他們鎮的鎮長!他其中一個競選承諾就是在鎮上建立起互連網,並串連到所有的農場。當然,他需要你的協助。

題目描述

約翰已經給他的農場安排了一條高速的網路線路,他想把這條線路共用給其他農場。為了用最小的消費,他想鋪設最短的光纖去串連所有的農場。

你將得到一份各農場之間串連費用的列表,你必須找出能串連所有農場並所用光纖最短的方案。每兩個農場間的距離不會超過100000

輸入輸出格式

輸入格式:

 

第一行: 農場的個數,N(3<=N<=100)。

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

 

輸出格式:

 

只有一個輸出,其中包含串連到每個農場的光纖的最小長度。

 

輸入輸出範例輸入範例#1:
40 4 9 214 0 8 179 8 0 1621 17 16 0
輸出範例#1:
28
說明

題目翻譯來自NOCOW。

USACO Training Section 3.1

代碼
 1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<algorithm> 5 #include<vector> 6 #include<queue> 7 #define MAXN 20000 8 using namespace std; 9 10 struct cc{11     int from,to,cost;12 }e[50000];13 14 bool cmp(cc a,cc b){15     return a.cost<b.cost;16 }17 18 int fa[999],N,map[999][999],p,ans,cnt;19 20 int Find(int x){21     if(fa[x]==x)return x;22     else return fa[x]=Find(fa[x]);23 }24 void unite(int a,int b){25     int ta=Find(a),tb=Find(b);26     if(ta==tb) return;27     fa[ta]=tb;28 }29 30 31 int main(){32 //    freopen("01.in","r",stdin);33     scanf("%d",&N);34     for(int i=1;i<=N;i++){35         for(int j=1;j<=N;j++){36             scanf("%d",&map[i][j]);37         }38     }39     for(int i=1;i<=N;i++){40         for(int j=i+1;j<=N;j++){41             e[++p].cost=map[i][j];42             e[p].from=i;43             e[p].to=j;44         }45     }46     for(int i=1;i<=N;i++) fa[i]=i;47     sort(e+1,e+p+1,cmp);48     for(int i=1;i<=p;i++){49         cc x=e[i];50         if(Find(x.from)==Find(x.to)) continue;51         unite(x.from,x.to);52         if(cnt>=N-1) break;53         ++cnt;54         ans+=x.cost;55     }56     printf("%d\n",ans);57     return 0;58 }

 

洛穀 P1546 最短網路 Agri-Net Label:Water最小產生樹

聯繫我們

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