The Unique MST POJ - 1679

The Unique MST

题目链接:POJ - 1679
题意:判断图的最小生成树是不是唯一的;
先求出最小生成树, 然后枚举去掉最小生成树的一边, 再求一边最小生成树;
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const long long INF = 0x3f3f3f3f;
const int maxn=50010;
int n, m;
struct node{
	int v, w, u, id;
}edge;
bool cmp(node a, node b){
	return a.w<b.w;
}
vector<node> vec;
int pre[110];
void init(){
	for(int i=0; i<=n; i++){
		pre[i]=i;
	}
}
int find(int x){
	return pre[x]==x?pre[x]:pre[x]=find(pre[x]);
}
int Union(int x, int y){
	int fx=find(x), fy=find(y);
	if(fx==fy) return 0;
	pre[fx]=fy;
	return 1;
}
vector<node> st, rt;
int ok(node a, node b){
	if(a.v==b.v&&a.u==b.u||a.v==b.u&&a.u==b.v){
		if(a.w<=b.w) return 1;
	}
	return 0;
}
void Kruskal(){
	int sum=0;
	st.clear();
	int cnt=0;
	while(cnt<vec.size()){
		if(st.size()==n-1) break;
		if(Union(vec[cnt].u, vec[cnt].v)){
			st.push_back(vec[cnt]);
			sum+=vec[cnt].w;
		}
		cnt++;
	}
	int temp;
	for(int i=0; i<st.size(); i++){
		temp=0;
		init();
		cnt=0;
		rt.clear();
		while(cnt<vec.size()){
			if(rt.size()==n-1) break;
			if(vec[cnt].id==st[i].id){
				cnt++;
				continue;
			}
			if(Union(vec[cnt].u, vec[cnt].v)){
				temp+=vec[cnt].w;
				rt.push_back(vec[cnt]);
			}
			cnt++;
		}
		if(rt.size()==n-1&&sum==temp){
			printf("Not Unique!\n");
			return;
		}
	}
	printf("%d\n", sum);
	return;
}
int main(){
	int t;
	scanf("%d", &t);
	while(t--){
		scanf("%d%d", &n, &m);
		init();
		vec.clear();
		for(int i=0; i<m; i++){
			scanf("%d%d%d", &edge.u, &edge.v, &edge.w);
			edge.id=i;
			vec.push_back(edge);
		}
		sort(vec.begin(), vec.end(), cmp);
		Kruskal();
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值