1016 Uniqueness of MST (35 分)(C++)

PAT顶级题解目录​​​​​​​

Given any weighted undirected graph, there exists at least one minimum spanning tree (MST) if the graph is connected. Sometimes the MST may not be unique though. Here you are supposed to calculate the minimum total weight of the MST, and also tell if it is unique or not. Input Specification: Each input file contains one test case. Each case starts with a line containing 2 numbers N (≤ 500), and M, which are the total number of vertices, and the number of edges, respectively. Then M lines follow, each describes an edge by 3 integers:

V1 V2 Weight 

where V1 and V2 are the two ends of the edge (the vertices are numbered from 1 to N), and Weight is the positive weight on that edge. It is guaranteed that the total weight of the graph will not exceed 2​30​​ .

Output Specification: For each test case, first print in a line the total weight of the minimum spanning tree if there exists one, or else print No MST instead. Then if the MST exists, print in the next line Yes if the tree is unique, or No otherwise. There there is no MST, print the number of connected components instead.

Sample Input 1:

5 7 
1 2 6 
5 1 1 
2 3 4 
3 4 3 
4 1 7
2 4 2 
4 5 5

Sample Output 1:

11 
Yes 

Sample Input 2:

4 5 
1 2 1 
2 3 1 
3 4 2
4 1 2
3 1 3 

Sample Output 2:

4 
No 

Sample Input 3:

5 5 
1 2 1 
2 3 1 
3 4 2 
4 1 2 
3 1 3 

Sample Output 3:

No MST 
2

题目大意:给出一个无向图,判断是否能生成最小生成树,如果可以生成最小生成树,那么判断生成的最小生成树是否唯一,如果不能生成最小生成树,求有几个连通分量。

解题思路:Kruskal最小生成树算法。首先关于最小生成树是否唯一,存在不唯一的情况即为有两个(及以上)权值相同的边,且最终的最小生成树只需要使用其中任意一个边,此时最小生成树不唯一。所以可以想到对于权值相同的一串边,先判断当前是否能作为最小生成树的边(用isTreeEdge标记),然后将能够作为最小生成树的边依次加入已经生成的最小树中,若出现某个边由于前面相同权值边的影响而不能加入最小树,此时说明最小生成树不唯一。而对于连通分量的求解,在求最小生成树的时候,每次加入一个新边的时候记一下数,最后用顶点数-该数即为连通分量的值。

C++

#include <bits/stdc++.h>
using namespace std;
typedef struct{
	int u, v, w;
	bool isTreeEdge = false;
}Edge;
vector<Edge>edges;
int n, m, father[505];
int findfather(int x){
	if(x == father[x])
		return x;
	int a = findfather(father[x]);
	father[x] = a;
	return a;
}
int main(){
	scanf("%d %d", &n, &m);
	edges.resize(m);
	for(int i = 0; i < m; ++ i)
		scanf("%d %d %d", &edges[i].u, &edges[i].v, &edges[i].w);
	sort(edges.begin(), edges.end(), [](Edge a, Edge b){return a.w < b.w;});
	iota(father, father+n+1, 0);
	int sum = 0, num = 0, j = 0;
	bool flag = true;
	for(int i = 0; i < edges.size(); i = j){
		for(j = i; j < edges.size() && edges[j].w == edges[i].w; ++ j)
			if(findfather(edges[j].u) != findfather(edges[j].v))
				edges[j].isTreeEdge = true;
		for(int k = i; k < j; ++ k){
			int ua = findfather(edges[k].u), ub = findfather(edges[k].v);
			if(ua != ub){
				sum += edges[k].w;
				father[ua] = ub;
				++ num;
			} 
			else if(edges[k].isTreeEdge)
				flag = false;
		}
	}
	if(num == n-1)
		printf("%d\n%s", sum, flag ? "Yes" : "No");
	else
		printf("No MST\n%d", n-num);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章