PAT顶级 1016 Uniqueness of MST (35分)(判断最小生成树是否唯一)

添加链接描述
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

思路:由于点和边少,暴力删边判断是否能生成别的最小生成我即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct cxk{
	int u,v,cost;
}s[500005];
int n,m,father[505],cns=0;
vector<int>v;
void init()
{
	for(int i=0;i<=n;++i) father[i]=i;
}
int findfather(int x)
{
	if(x==father[x]) return x;
	return father[x]=findfather(father[x]);
}
bool cmp(const cxk &a,const cxk &b)
{
	return a.cost<b.cost;
}
ll kr(int flag)
{
	ll cnt=0,num=0,res=0;
	for(int i=1;i<=m;++i)
	{
		if(i==flag) continue;
		int fa=findfather(s[i].u),fb=findfather(s[i].v);
		if(fa!=fb)
		{
			res+=s[i].cost;
			father[fa]=fb;
			cnt++;
			if(flag==-1) v.push_back(i);
			if(cnt==n-1) break;
		}
	}
	for(int i=1;i<=n;++i) if(father[i]==i)num++;
	cns=cnt;
	return num>1?-1:res;
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;++i) scanf("%d%d%d",&s[i].u,&s[i].v,&s[i].cost);
	for(int i=0;i<=n;++i) father[i]=i;
	sort(s+1,s+1+m,cmp);
	ll ans=kr(-1);
	if(ans==-1){
		puts("No MST");printf("%d\n",n-cns);return 0;
	}
	for(auto it:v)
	{
		init();
		ll temp=kr(it);
		if(temp==ans){
			printf("%lld\nNo",ans);return 0;
		}
	}
	printf("%lld\nYes",ans);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值