# POJ1679-The Unique MST(次小生成树)

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<algorithm>
using namespace std;
const int maxn = 110;
int n,m;
bool flag;
struct Edge{
int u,v,w;
bool del,use;
}edge[maxn*maxn];
int f[maxn];
void init()
{
for(int i=0;i<n;i++)
f[i]=i;
}
int Find(int x)
{
if(x==f[x]) return x;
return f[x]=Find(f[x]);
}
bool cmp(Edge p,Edge q) {return p.w<q.w;}
int Krusal()
{
int cnt=0,sum=0;
init();
for(int i=0;i<m;i++)
{
int xroot=Find(edge[i].u),yroot=Find(edge[i].v);
if(xroot!=yroot&&edge[i].del==false)
{
if(!flag) edge[i].use=true;
f[xroot]=yroot;
sum+=edge[i].w;
cnt++;
if(cnt==n-1)
{
return sum;
}
}
}
return -1;

}
int main()
{
int t;
cin>>t;
while(t--)
{
scanf("%d%d",&n,&m);
if(m==0){ printf("0\n");continue;}
for (int i=0;i < m;i++)
{
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
edge[i].del = false;
edge[i].use = false;
}
sort(edge,edge+m,cmp);
flag=false;
int t=Krusal();
flag=true;
for(int i=0;i<m;i++)
{
if(edge[i].use==true)
{
edge[i].del=true;
int ans=Krusal();
if(t==ans)
{
t=-1;
break;
}
edge[i].del=false;

}

}
if(t==-1)
{
printf("Not Unique!\n");
}
else{
printf("%d\n",t);
}

}
}