The Unique MST

The Unique MST

总时间限制: 
1000ms 
内存限制: 
65536kB
描述
Given a connected undirected graph, tell if its minimum spanning tree is unique.

Definition 1 (Spanning Tree): Consider a connected, undirected graph G = (V, E). A spanning tree of G is a subgraph of G, say T = (V', E'), with the following properties:
1. V' = V.
2. T is connected and acyclic.

Definition 2 (Minimum Spanning Tree): Consider an edge-weighted, connected, undirected graph G = (V, E). The minimum spanning tree T = (V, E') of G is the spanning tree that has the smallest total cost. The total cost of T means the sum of the weights on all the edges in E'.
输入
The first line contains a single integer t (1 <= t <= 20), the number of test cases. Each case represents a graph. It begins with a line containing two integers n and m (1 <= n <= 100), the number of nodes and edges. Each of the following m lines contains a triple (xi, yi, wi), indicating that xi and yi are connected by an edge with weight = wi. For any two nodes, there is at most one edge connecting them.
输出
For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'.
样例输入
2
3 3
1 2 1
2 3 2
3 1 3
4 4
1 2 2
2 3 2
3 4 2
4 1 2
样例输出
3
Not Unique!
来源
POJ Monthly--2004.06.27 srbga@POJ

#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
using namespace std;
int father[105];
struct edge
{
	int s,t,w;
}E[5005];
bool Vis[5005]={0};
bool cmp(const edge&a,const edge&b)
{
	return a.w<b.w;
}
int Getfather(int x)
{
	if(father[x]==x)return x;
	int tmp=Getfather(father[x]);
	father[x]=tmp;
	return tmp;
}
bool Valid(int x)
{
	if(Vis[x])return false;
	int fs=Getfather(E[x].s);
	int ft=Getfather(E[x].t);
	return fs!=ft;
}
int main()
{
	int Test;
	cin>>Test;
	while(Test--) 
	{
		int n,m,s,t,w;
		memset(Vis,0,sizeof(Vis));
		cin>>n>>m;
		for(int i=1;i<=n;++i)
		{
			father[i]=i;
		}
		for(int i=0;i<m;++i)
		{
			cin>>E[i].s>>E[i].t>>E[i].w;
		}
		sort(E,E+m,cmp);
		int num=n-1,sum=0;
		bool Unique=true;
		while(num--)
		{
			for(int i=0;i<m;++i)
			{
				if(Valid(i))
				{
					for(int j=i+1;j<m;++j)
					{
						if(E[j].w>E[i].w)break;
						if(Valid(j))
						{
							Unique=false;
							break;
						}
					}
					if(!Unique)break;
					Vis[i]=true;
					int fs=Getfather(E[i].s);
					int ft=Getfather(E[i].t);
					father[fs]=ft;
					sum+=E[i].w;
				}
			}
			if(!Unique)break;
		}
		if(Unique)cout<<sum<<endl;
		else cout<<"Not Unique!"<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值