题目描述
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
输入
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。
当N为0时输入结束。
输出
每个测试用例的输出占一行,输出全省畅通需要的最低成本。
样例输入 复制
4
1 2 1 1
1 3 6 0
1 4 2 1
2 3 3 0
2 4 5 0
3 4 4 0
3
1 2 1 1
2 3 2 1
1 3 1 0
0
样例输出 复制
3
0
分析:
此题要求得出最小生成树,因此考虑Prim算法或者Kruskal算法,但是,本题给的一些边是已经建成的,不算入代价中,因此使用以边进行操作的Kruskal算法更加便捷。
只要提前判断边是否建成,若建成则将其两个顶点进行并操作,若未建成把边加入边集当中,再对未建成边进行Kruskal + 并查集操作。
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXV = 101;
const int MAXE = 101 * 100 / 2;
int n, m, ne, ns;
struct edge{
int u, v;
int cost;
edge(int u_, int v_, int c_): u(u_), v(v_), cost(c_){}
edge(){}
}E[MAXE];
int father[MAXV];
bool cmp(edge a, edge b){
return a.cost < b.cost;
}
void InitialUnion(void){
for(int i = 1; i <= n; i++){
father[i] = i;
}
}
int findfather(int x){
int a = x;
while(x != father[x]){
x = father[x];
}
while(a != father[a]){
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
int Kruskal(void){
int ans = 0, num_edge = 0;
sort(E, E + ne, cmp);
for(int i = 0; i < ne; i++){
int fu = findfather(E[i].u);
int fv = findfather(E[i].v);
if(fu != fv){
father[fv] = fu;
ans += E[i].cost;
num_edge++;
if(num_edge == ns - 1) break;
}
}
if(num_edge != ns - 1) return -1;
return ans;
}
int main()
{
while(cin >> n && n != 0){
m = n * (n - 1) / 2;
ne = 0;
ns = n;
InitialUnion();
for(int i = 0; i < m; i++){
int a, b, c, s;
cin >> a >> b >> c >> s;
if(s == 1){
int fa = findfather(a);
int fb = findfather(b);
if(fa != fb){
father[fb] = fa;
ns--;
}
}else{
E[ne++] = edge(a, b, c);
}
}
int ans = Kruskal();
cout << ans << '\n';
}
return 0;
}