Step6.1.5 hdu1879繼續暢通工程
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11442 Accepted Submission(s): 5011
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
Author
ZJU
Source
浙大計算機研究生複試上機考試-2008年
題解:
這道題繼續是求最小生成樹,還是克魯斯卡爾算法。公路建成的城市,放到生成樹中,然後再在將其他的頂點放到生成樹中。
源代碼:
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
struct Road
{
intc1,c2,value;
}rd[10050];
int node[105];
void init()
{
memset(node,-1,sizeof(node));
}
bool mycmp(const Road &x,const Road &y)
{
if(x.value< y.value)
returntrue;
else
returnfalse;
}
int find_set(int x)
{
if(node[x]== -1)
returnx;
returnnode[x] = find_set(node[x]);
}
bool merge(int x,int y)
{
intr1 = find_set(x);
intr2 = find_set(y);
if(r1== r2)
return0;
if(r1< r2)
node[r2] = r1;
else
node[r1] = r2;
return1;
}
int main()
{
intn;
while(scanf("%d",&n) != EOF && n)
{
init();
intm = n*(n-1)/2;
inta,b,c,d;
intnum = 0,count = 0;
for(int i = 0;i < m;i++)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
if(!d)
{
rd[num].c1 = a;
rd[num].c2 = b;
rd[num++].value = c;
}
else
{
if(merge(a,b))
count++;
}
}
sort(rd,rd+num,mycmp);
intsum = 0;
for(int i = 0;i < num;i++)
{
if(count== n-1)
break;
if(merge(rd[i].c1,rd[i].c2))
{
count ++;
sum+=rd[i].value;
}
}
printf("%d\n",sum);
}
}