继续畅通工程(HDU-1879 )
生活随笔
收集整理的這篇文章主要介紹了
继续畅通工程(HDU-1879 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Problem Description
省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可)。現得到城鎮道路統計表,表中列出了任意兩城鎮間修建道路的費用,以及該道路是否已經修通的狀態。現請你編寫程序,計算出全省暢通需要的最低成本。
Input
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( 1< N < 100 );隨后的 N(N-1)/2 行對應村莊間道路的成本及修建狀態,每行給4個正整數,分別是兩個村莊的編號(從1編號到N),此兩村莊間道路的成本,以及修建狀態:1表示已建,0表示未建。
當N為0時輸入結束。
Output
每個測試用例的輸出占一行,輸出全省暢通需要的最低成本。
Sample Input
3
1 2 1 0
1 3 2 0
2 3 4 0
3
1 2 1 0
1 3 2 0
2 3 4 1
3
1 2 1 0
1 3 2 1
2 3 4 1
0?
Sample Output
3
1
0
思路:最小生成樹kruskal算法實現即可,可把已聯通的村莊邊權設為0再求。
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #define INF 999999999 #define N 101 #define MOD 1000000007 #define E 1e-12 using namespace std; int father[N]; struct node {int x;int y;int w; }a[5000]; int Find(int x) {if(x!=father[x])return father[x]=Find(father[x]);return x; } int cmp(const void *x,const void *y) {return (*(struct node *)x).w-(*(struct node *)y).w; } int main() {int n;while(scanf("%d",&n)!=EOF&&n){int edge=n*(n-1)/2;int num=0;for(int i=1;i<=n;i++)//初始化father[i]=i;int k=0;for(int i=1;i<=edge;i++){int x,y,w,p;scanf("%d%d%d%d",&x,&y,&w,&p);if(p==1){x=Find(x);y=Find(y);if(x!=y){father[x]=y;k++;}}else{a[num].x=x;a[num].y=y;a[num].w=w;num++;}}qsort(a,num,sizeof(a[0]),cmp);int MST=0;for(int i=0;i<num;i++){int x=Find(a[i].x);int y=Find(a[i].y);if(x!=y){father[x]=y;MST+=a[i].w;k++;}if(k==n-1)break;}printf("%d\n",MST);}return 0; }總結
以上是生活随笔為你收集整理的继续畅通工程(HDU-1879 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 暑期训练日志----2018.8.6
- 下一篇: Almost Arithmetic Pr