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;
}

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/84065387