Problem Description
省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可)。現得到城鎮道路統計表,表中列出了任意兩城鎮間修建道路的費用,以及該道路是否已經修通的狀態。現請你編寫程序,計算出全省暢通需要的最低成本。
Input
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( 1< N < 100 );隨後的 N(N-1)/2 行對應村莊間道路的成本及修建狀態,每行給4個正整數,分別是兩個村莊的編號(從1編號到N),此兩村莊間道路的成本,以及修建狀態:1表示已建,0表示未建。
當N爲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
代碼:
#include <cstdio>
#include <algorithm>
using namespace std;
struct edge{
int a,b;
int w;
int flag;
bool operator<(const edge& A)const{
return w<A.w;
}
}e[6000];
const int maxn=105;
int tree[maxn];
int findRoot(int x){
if(tree[x]==-1) return x;
else{
int tmp=findRoot(tree[x]);
tree[x]=tmp;
return tmp;
}
}
int main(){
int n;
while(scanf("%d",&n)==1&&n){
for(int i=1;i<=n;i++) tree[i]=-1;
for(int i=1;i<=n*(n-1)/2;i++){
scanf("%d%d%d%d",&e[i].a,&e[i].b,&e[i].w,&e[i].flag);
if(e[i].flag) tree[e[i].a]=e[i].b;
}
sort(e+1,e+1+n*(n-1)/2);
int ans=0;
for(int i=1;i<=n*(n-1)/2;i++){
int a=findRoot(e[i].a);
int b=findRoot(e[i].b);
if(a!=b){
tree[a]=b;
ans+=e[i].w;
}
}
printf("%d\n",ans);
}
return 0;
}