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);
}

 

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