[kuangbin带你飞]专题六 最小生成树 L - 还是畅通工程 (简单最小生成树)
生活随笔
收集整理的這篇文章主要介紹了
[kuangbin带你飞]专题六 最小生成树 L - 还是畅通工程 (简单最小生成树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
L - 還是暢通工程
題目鏈接:https://vjudge.net/contest/66965#problem/L
題目:
某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),并要求鋪設的公路總長度為最小。請計算最小的公路總長度。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 0Sample Output
3 5Huge input, scanf is recommended.Hint
Hint思路:注意輸入的T*(T-1)/2,然后跑最小生成樹就行
// // Created by hanyu on 2019/8/2. // #include <algorithm> #include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <set> #include<math.h> using namespace std; typedef long long ll; const int maxn=2e6+7; int father[maxn]; struct Node{int u,v,w;bool operator<(const Node &other)const{return this->w<other.w;} }node[maxn]; int find(int x) {if(x==father[x])return x;return father[x]=find(father[x]); } int main() {int T;while(~scanf("%d",&T)&&T){for(int i=0;i<=T;i++)father[i]=i;int ans=0,cnt=0;int kk=T*(T-1)/2;for(int i=0;i<kk;i++){scanf("%d%d%d",&node[i].u,&node[i].v,&node[i].w);}sort(node,node+kk);for(int i=0;i<kk;i++){int uu=find(node[i].u);int vv=find(node[i].v);if(uu==vv)continue;else{father[uu]=vv;ans+=node[i].w;cnt++;if(cnt==T-1)break;}}printf("%d\n",ans);}return 0; }
?
?
轉載于:https://www.cnblogs.com/Vampire6/p/11288756.html
總結
以上是生活随笔為你收集整理的[kuangbin带你飞]专题六 最小生成树 L - 还是畅通工程 (简单最小生成树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电王雷暴宝珠咋打
- 下一篇: 几种Normalization算法.md