最小生成树MST

最小生成树Kruskal算法

1.初始时所以点属于孤立的结点

2.按照边权递增的顺序遍历所有的边,若该边的两个点不属于一个集合,则确定该边为最小生成树上的一条边,且要将这两个点合并到一个集合之中。

3.遍历完所有边,若原图上所有结点均属于同一集合,则被选取的边和结点构成了最小生成树;否则不连通,MST不存在

方法:并查集

例一:九度1017 还是畅通工程

题目描述:
    某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
输入:

    测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
    当N为0时,输入结束,该用例不被处理。

输出:

    对每个测试用例,在1行里输出最小的公路总长度。

样例输入:
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
样例输出:
3
5

//畅通工程
#include<stdio.h>
#include<algorithm>
using namespace std;
//定义每条边的结构体
struct Edge {
	int a;
	int b;
	int count;
}edge[101];
int Tree[101];
//查找根节点
int findRoot(int a) {
	if (Tree[a] == -1) return a;
	else {
		int t = findRoot(Tree[a]);
		Tree[a] = t;
		return t;
	}
}
bool cmp(Edge a, Edge b) {
	return a.count < b.count;
}
int main() {
	int n;
	int i, j;
	while (scanf("%d", &n) != EOF&&n!=0) {
		int ans=0;
		for (i = 1; i <=100; i++) {
			Tree[i] = -1;
		}
		for (i = 0; i < n*(n-1)/2; i++) {
			scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].count);
		}
		sort(edge, edge + n*(n - 1) / 2, cmp);
		for (i = 0; i < n*(n - 1) / 2; i++) {
			int a = findRoot(edge[i].a);
			int b = findRoot(edge[i].b);
			if (a != b) {
				Tree[a] = b;
				ans += edge[i].count;
			}
		}
		printf("%d\n", ans);
	}
}

例二 九度1024 畅通工程(MST可能不存在)

题目描述:

    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
输入:
    测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M (N, M < =100 );随后的 N 行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
输出:
    对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
样例输入:
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
样例输出:
3
?
   
//畅通工程(MST可能不存在)
#include<stdio.h>
#include<algorithm>
using namespace std;
//定义每条边的结构体
struct Edge {
	int a;
	int b;
	int count;
}edge[101];
int Tree[101];
//查找根节点
int findRoot(int a) {
	if (Tree[a] == -1) return a;
	else {
		int t = findRoot(Tree[a]);
		Tree[a] = t;
		return t;
	}
}
bool cmp(Edge a, Edge b) {
	return a.count < b.count;
}
int main() {
	int n,m; //n代表道路条数,m代表村庄数目
	int i, j;
	while (scanf("%d%d", &n,&m) != EOF&&n != 0) {
		int ans = 0;
		for (i = 1; i <= 100; i++) {
			Tree[i] = -1;
		}
		for (i = 0; i < n; i++) {
			scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].count);
		}
		sort(edge, edge + n, cmp);
		int sum=1;
		for (i = 0; i < n; i++) {
			int a = findRoot(edge[i].a);
			int b = findRoot(edge[i].b);
			if (a != b) {
				Tree[a] = b;
				ans += edge[i].count;
				sum++;
			}
			if (sum == m) break; //如果所有点都包含在了集合中,则退出
		}
		if (sum < m) {
			printf("?\n");
		}
		else {
			printf("%d\n", ans);
		}
		
	}
}

例三 继续畅通工程 九度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
//继续畅通工程
#include<stdio.h>
#include<algorithm>
using namespace std;
//定义每条边的结构体
struct Edge {
	int a;
	int b;
	int cost;
	int status;
}edge[101];
int Tree[101];
//查找根节点
int findRoot(int a) {
	if (Tree[a] == -1) return a;
	else {
		int t = findRoot(Tree[a]);
		Tree[a] = t;
		return t;
	}
}
bool cmp(Edge a, Edge b) {
	return a.cost < b.cost;
}
int main() {
	int n;
	int i, j;
	while (scanf("%d", &n) != EOF&&n != 0) {
		int ans = 0;
		for (i = 1; i <= 100; i++) {
			Tree[i] = -1;
		}
		for (i = 0; i < n*(n - 1) / 2; i++) {
			scanf("%d%d%d%d", &edge[i].a, &edge[i].b, &edge[i].cost,&edge[i].status);
			if (edge[i].status == 1) { //注意要先判断状态在排序,不然顺序又会乱
				edge[i].cost = 0;
			}
		}
		sort(edge, edge + n*(n - 1) / 2, cmp);
		for (i = 0; i < n*(n - 1) / 2; i++) {
			int a = findRoot(edge[i].a);
			int b = findRoot(edge[i].b);
			
			if (a != b) {
				Tree[a] = b;
				ans += edge[i].cost;
			}
		}
		printf("%d\n", ans);
	}
}

例四 九度1144 Freckles (给出点的坐标)

题目描述:

    In an episode of the Dick Van Dyke show, little Richie connects the freckles on his Dad's back to form a picture of the Liberty Bell. Alas, one of the freckles turns out to be a scar, so his Ripley's engagement falls through. 
    Consider Dick's back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle. 

输入:

    The first line contains 0 < n <= 100, the number of freckles on Dick's back. For each freckle, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the freckle.

输出:

    Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.

样例输入:
3
1.0 1.0
2.0 2.0
2.0 4.0
样例输出:
3.41
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
//定义边结构体
struct Edge {
	int a, b;
	double cost;
}edge[101];
//定义点结构体
struct Point {
	double x, y;
}point[101];
double distance(Point a, Point b) {
	double t = (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y);
	return sqrt(t);
}
bool cmp(Edge a, Edge b) {
	return a.cost < b.cost;
}
int Tree[101];
int findRoot(int x) {
	if (Tree[x] == -1) return x;
	else {
		int t = findRoot(Tree[x]);
		Tree[x] = t;
		return t;
	}
}
int main() {
	int n;
	int i, j;
	while (scanf("%d", &n) != EOF) {
		for (i = 1; i <= n; i++) {
			scanf("%lf%lf", &point[i].x, &point[i].y);
		}
		int size = 0;
		for (i = 1; i <= n; i++) {
			for (j = i+1; j <= n; j++) {
				edge[size].a = i;
				edge[size].b = j;
				edge[size].cost = distance(point[i], point[j]);
				size++;
			}
		}
		sort(edge, edge + size, cmp);
		for (i = 1; i <= 100; i++) {
			Tree[i] = -1;
		}
		double ans = 0;
		for (i = 0; i < size; i++) {
			int a = findRoot(edge[i].a);
			int b = findRoot(edge[i].b);
			if (a != b) {
				Tree[a] = b;
				ans += edge[i].cost;
			}
		}
		printf("%.2lf\n", ans);
	}
}

练习 九度1154 Jungle Roads

题目描述:

   

    The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.

输入:

    The input consists of one to 100 data sets, followed by a final line containing only 0. Each data set starts with a line containing only a number n, which is the number of villages, 1 < n < 27, and the villages are labeled with the first n letters of the alphabet, capitalized. Each data set is completed with n-1 lines that start with village labels in alphabetical order. There is no line for the last village. Each line for a village starts with the village label followed by a number, k, of roads from this village to villages with labels later in the alphabet. If k is greater than 0, the line continues with data for each of the k roads. The data for each road is the village label for the other end of the road followed by the monthly maintenance cost in aacms for the road. Maintenance costs will be positive integers less than 100. All data fields in the row are separated by single blanks. The road network will always allow travel between all the villages. The network will never have more than 75 roads. No village will have more than 15 roads going to other villages (before or after in the alphabet). In the sample input below, the first data set goes with the map above.

输出:

    The output is one integer per line for each data set: the minimum cost in aacms per month to maintain a road system that connect all the villages. Caution: A brute force solution that examines every possible set of roads will not finish within the one minute time limit.

样例输入:
9
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
3
A 2 B 10 C 40
B 1 C 20
0

 
#include<stdio.h> #include<algorithm> using namespace std; //定义边的结构体 struct Edge { int a; int b; int cost; }edge[101]; int Tree[101]; int findRoot(int x) { if (Tree[x] == -1) return x; else { int t = findRoot(Tree[x]); Tree[x] = t; return t; } } bool cmp(Edge a, Edge b) { return a.cost < b.cost; } int main() { int n; int i, j; char c,d; int k; while (scanf("%d", &n) != EOF&&n!=0) { int edgeno=0; int a, b; for (i = 0; i < n-1; i++) { //不能用getchar();会超时,用空格来代替回车
scanf(" %c %d",&c,&k); for (j = 0; j < k; j++) { scanf(" %c %d", &d, &edge[edgeno].cost); edge[edgeno].a = c - 'A' + 1; //此处定义节点从1开始,边从0开始 edge[edgeno].b = d - 'A' + 1; edgeno++; } } for (i = 1; i <= n; i++) { Tree[i] = -1; } sort(edge, edge + edgeno, cmp); int ans = 0; for (i = 0; i < edgeno; i++) { a = findRoot(edge[i].a); b = findRoot(edge[i].b); if (a != b) { Tree[a] = b; ans += edge[i].cost; } } printf("%d\n", ans); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值