修路问题(最小生成树)

省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。

输入描述:

    测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。

    当N为0时输入结束。

输出描述:

    每个测试用例的输出占一行,输出全省畅通需要的最低成本。

示例1

输入

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

#include<stdio.h>
#include<string.h>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//最小生成树:注意已经通达的要输入时联通
struct edge{
	int a,b,cost,has;
	bool operator < (edge A){
		return cost<A.cost;
	}
};
int father[105];
int getroot(int x){
	if(x==father[x])	return x;
	int root=getroot(father[x]);
	father[x]=root;
	return root;//这一一定有,否则最后返回的是错误的
}
//或者简写成return x==father[i] ? x : father[x]=getroot(father[x]);
void Merge(int a,int b){
	int roota=getroot(a);
	int rootb=getroot(b);
	if(roota!=rootb)
		father[roota]=rootb;
}
int main(){
	int n;
	while(scanf("%d",&n) && n!=0){
		int sum=0;
		vector<edge> edges;
		for(int i=0;i<105;i++)
			father[i]=i;
		for(int i=0;i<(n-1)*n/2;i++){
			edge temp;
			scanf("%d%d%d%d",&temp.a,&temp.b,&temp.cost,&temp.has);
			if(temp.has==1)	Merge(temp.a,temp.b);
			edges.push_back(temp);
		}
		sort(edges.begin(),edges.end());
		for(int i=0;i<edges.size();i++){
			if(edges[i].has==1)	break;
			int ra=getroot(edges[i].a);
			int rb=getroot(edges[i].b);

			if(ra!=rb){
				father[ra]=rb;
				sum+=edges[i].cost;
			}
		}
		printf("%d\n",sum);
	}
	return 0;
}

    原文作者:道路修建问题
    原文地址: https://blog.csdn.net/futangxiang4793/article/details/79582668
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞