1. 程式人生 > >POJ-The Unique MST(次小生成樹)

POJ-The Unique MST(次小生成樹)

The Unique MST

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!

題目連結:

http://poj.org/problem?id=1679

題意描述:

給你n個點和m條邊,然後求最小生成樹,問如果在最小生成樹裡去掉一條邊,最小生成樹的值是否有變化,即求最小生成樹的值是否唯一,只需求出次小生成即可。

解題思路:

用克魯斯卡爾演算法求出最小生成樹,並把各邊標記,然後再逐個去掉一條邊,再求最小生成樹,與之前的最小生成樹的值相比較,如果有一個相等,那麼該樹的最小生成樹就是不唯一

程式程式碼:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

struct data{
	int u;
	int v;
	int w;
};
data e[10010];
int n,m;
int f[110];
bool book[10010];

int cmp(data x,data y);
int getf(int u);
int merge(int u,int v);
int kruscal(int x);

int main()
{
	int T,i,sum,count;
	scanf("%d",&T);
	while(T--)
	{
		sum=0;
		count=0;
		scanf("%d%d",&n,&m);
		for(i=1;i<=m;i++)
			scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
		for(i=1;i<=n;i++)
			f[i]=i;
		memset(book,0,sizeof(book));
		sort(e+1,e+1+m,cmp);
		for(i=1;i<=m;i++)
		{
			if(merge(e[i].u,e[i].v)==1)
			{
				book[i]=1;
				sum+=e[i].w;
				count++;
			}
			if(count==n-1)
				break;
		}
		for(i=1;i<=m;i++)
			if(book[i]==1&&sum==kruscal(i))
				break;
		if(i>m)
			printf("%d\n",sum);
		else
			printf("Not Unique!\n");
		
	}
	return 0;
}

int cmp(data x,data y)
{
	return x.w<y.w;
}

int getf(int u)
{
	if(u==f[u])
		return u;
	f[u]=getf(f[u]);
	return f[u];
}

int merge(int u,int v)
{
	u=getf(u);
	v=getf(v);
	if(u!=v)
	{
		f[v]=u;
		return 1;
	}
	return 0;
}

int kruscal(int x)
{
	int sum=0,count=0,i;
	for(i=1;i<=n;i++)
		f[i]=i;
	for(i=1;i<=m;i++)
	{
		if(i==x)
			continue;
		if(merge(e[i].u,e[i].v)==1)
		{
			sum+=e[i].w;
			count++;
		}
		if(count==n-1)
			return sum;
	}
	return -1;
}