首页 > 其他 > 详细

POJ 1679 The Unique MST(判断最小生成树_Kruskal)

时间:2015-08-17 17:23:45      阅读:153      评论:0      收藏:0      [点我收藏+]

Description

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‘. 

Input

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.

Output

For each input, if the MST is unique, print the total cost of it, or otherwise print the string ‘Not Unique!‘.

Sample Input

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

Sample Output

3
Not Unique!


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int father[111],n,m,first;

struct node
{
	int u,v,w;
	int used;
	int equal;
	int del;
} a[11111];

bool cmp(node x,node y)
{
	if(x.w<y.w) return true;
	return false;
}

int find(int x)
{
	int r=x;
	while(father[r]!=r) r=father[r];
	int i=x,j;
	while(i!=r) {
		j=father[i];
		father[i]=r;
		i=j;
	}
	return r;
}

int prime()
{
	int i,j,k,sum,num;
	sum=0;num=0;
	for(i=1;i<=n;i++) father[i]=i;
	for(i=1;i<=m;i++) {
		if(a[i].del) continue;
		int fx=find(a[i].u);
		int fy=find(a[i].v);
		if(fx!=fy) {
			num++;
			father[fx]=fy;
			sum+=a[i].w;
			if(first) a[i].used=1;
		}
		if(num==n-1) break;
	}
	return sum;
}

int main()
{
	int i,j,k,u,v,w,sum1,sum2;
	int t;
	scanf("%d",&t);
	while(t--) {
		sum1=sum2=0;
		memset(a,0,sizeof(a));
		scanf("%d%d",&n,&m);
		for(i=1;i<=m;i++) {
			scanf("%d%d%d",&a[i].u,&a[i].v,&a[i].w);
		}
		for(i=1;i<=m;i++) {
			for(j=i+1;j<=m;j++) {
				if(a[i].w==a[j].w) a[i].equal=1;
			}
		}
		sort(a+1,a+1+m,cmp);
		first=1;
		sum1=prime();
		first=0;
		for(i=1;i<=m;i++) {
			if(a[i].used && a[i].equal) {
				a[i].del=1;
				sum2=prime();
				if(sum1==sum2) {
					printf("Not Unique!\n");
					break;
				}
			}
		}
		if(i==m+1) printf("%d\n",sum1);
	}
}











版权声明:本文为博主原创文章,未经博主允许不得转载。

POJ 1679 The Unique MST(判断最小生成树_Kruskal)

原文:http://blog.csdn.net/h1021456873/article/details/47726707

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!