POJ1679(次小生成树)


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!

其实吧 就是先用krasual算法求出最小生成树 然后标记一下每一个进入的边  枚举每一条边不在里面的时候


代码:

#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int const MAX = 1e4 + 5;
struct node
{
	int x,y;
	int val;
	int used;
}s[10000];
int n,m,x;
int pre[12500];
bool cmp(node a,node b)
{
	return a.val< b.val;
}
int find(int x)
{
	if(x == pre[x]) return x;
	else return pre[x]= find(pre[x]);
}
bool merge(int x,int y)
{
	int fx = find(x);
	int fy = find(y);
	if(fx!=fy){
		pre[fx] = fy;
		return true;
	}
	return false;
} 
int krusal(int k)
{
	int ans = 0;
	for(int i =1;i<=m;i++)
	{
		if(i==k)continue;
		if(merge(s[i].x,s[i].y)==true) 
		{
			ans += s[i].val;
		}
	}
	int cnt =0;
	for(int i=1;i<=n;i++)
	{
		if(pre[i]==i) cnt++;
	}
	if(cnt>1)return -1;
	return ans;
}
int main()
{
	int t;scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		for(int i=1;i<=m;i++)
			scanf("%d%d%d",&s[i].x,&s[i].y,&s[i].val);
		sort(s+1,s+1+m,cmp);
		for(int i = 1;i <= n;i ++) pre[i] = i;
		int  ans = 0;
		for(int i =1;i<=m;i++)
		{
			if(merge(s[i].x,s[i].y)==true) 
			{
				ans += s[i].val;
				s[i].used = 1;//这些边都是被加入的 
			}else s[i].used = 0;
		}
		int flag = 0;
		for(int i=1;i<=m;i++)
		{
			if(s[i].used == 0) continue;
			for(int j = 1;j<=n;j++) pre[j] = j;//先初始化下 
			int sum = krusal(i); 
	
			if(sum==ans)
			{
				flag = 1;
				break;
			}
		}
		if(!flag)printf("%d\n",ans);
		else printf("Not Unique!\n");  
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/galesaur_wcy/article/details/80145598