九度[1028]-继续畅通工程
题目描述:
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
输入
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。
当N为0时输入结束。
输出
每个测试用例的输出占一行,输出全省畅通需要的最低成本。
样例输入
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
样例输出
3
1
0
解题思路:
本质上还是最小生成树
AC代码:
#include <cstdio>
const int maxn = 110;
int N;
bool vis[maxn];
int father[maxn];
struct road{
int A;
int B;
int cost;
int connect;
}roads[maxn*maxn];
int findFather(int n){
if(n == father[n]) return n;
else return findFather(father[n]);
}
void quickSort(road roads[], int l, int r){
if(l >= r) return;
int low = l, high = r;
road key = roads[low];
while(low < high){
while(low < high && roads[high].cost >= key.cost) high--;
if(low < high) roads[low] = roads[high];
while(low < high && roads[low].cost < key.cost) low++;
if(low < high) roads[high] = roads[low];
}
roads[low] = key;
quickSort(roads, l, low-1);
quickSort(roads, high+1, r);
}
int kruskal(road roads[], int eNum){
int ans = 0;
//for(int i = 0; i < eNum && cnt <= pNum; i++) is wrong?
for(int i = 0; i < eNum; i++){
int faA = findFather(roads[i].A);
int faB = findFather(roads[i].B);
if(faA != faB) {
father[faA] = faB;
if(!vis[roads[i].A]){
vis[roads[i].A] = true;
}
if(!vis[roads[i].B]){
vis[roads[i].B] = true;
}
ans += roads[i].cost;
}
}
return ans;
}
int main(){
freopen("C:\\Users\\Administrator\\Desktop\\test.txt", "r", stdin);
while(scanf("%d", &N) != EOF){
if(N == 0) break;
for(int i = 0; i < maxn; i++){
father[i] = i;
vis[i] = false;
}
int num = N*(N-1)/2;
for(int i = 0; i < num; i++){
scanf("%d%d%d%d", &roads[i].A, &roads[i].B, &roads[i].cost, &roads[i].connect);
if(roads[i].connect == 1) roads[i].cost = 0;
}
quickSort(roads, 0, num-1);
printf("%d\n", kruskal(roads, num));
}
fclose(stdin);
return 0;
}