poj-1679 The Unique MST 判断最小生成树是否唯一

题目链接

题目大意:判断最小生成树是否唯一。

思路:先标记最小生成树中的边 枚举删除边 判断是否还能构成最小生成树。



#include "stdio.h"
#include "string.h"
#include "queue"
#include "iostream"
#include "functional"
#include "math.h"
#include "algorithm"
using namespace std;
const int maxn = 105;
const int mod = 1000000007 ;
const int inf = 1<<30;
typedef __int64 LL;
int n,m,ans,mst;
struct node
{
	int u,v,w;
}edge[maxn*maxn];
int p[maxn],path[maxn];
bool cmp( node a,node b )
{
	return a.w < b.w;
}
void MakeSet()
{
	ans = 0;
	for( int i = 1; i <= n; i ++ )
		p[i] = i;
}
int find( int x )
{
	return p[x] == x?x:p[x] = find( p[x] );
}
int main()
{
	#ifndef ONLINE_JUDGE     
	freopen("data.txt","r",stdin);     
	#endif  
	int a,b,c,cas;
	scanf("%d",&cas);
	while( cas -- )
	{
		mst = 0;
		scanf("%d%d",&n,&m);
		for( int i = 0; i < m; i ++ )
		{
			scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
		}
		sort( edge,edge+m,cmp );
		int top = 0;
		MakeSet();
		for( int i = 0; i < m; i ++ )
		{
			int x = find( edge[i].u );
			int y = find( edge[i].v );
			if( x != y )
			{
				p[x] = y;
				mst += edge[i].w;
				path[top++] = i;
			}
		}
		int flag = 0,k;
		for( int i = 0; i < top; i ++ )
		{
			k = 0;
			MakeSet();
			for( int j = 0; j < m; j ++ )
			{
				if( j != path[i] )
				{
					int x = find( edge[j].u );
					int y = find( edge[j].v );
					if( x != y )
					{
						p[x] = y;
						ans += edge[j].w;
						k ++;
					}	
				}
			}
			if( k == n-1 && ans == mst  )
				flag = 1;
		}
		if( flag )
			puts("Not Unique!");
		else
			printf("%d\n",mst);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值