poj 1679 The Unique MST(唯一的最小生成树)

时间:2020-12-14 20:42:35

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

The Unique MST
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 17726   Accepted: 6150

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!

Source

 
【题解】:
  用kruskal,求出最小生成树,然后枚举删除最小生成树上的一条边,再求最小生成树,比较前后两次求解的大小
  【注意】:如果题目给的数据不能构成一个树需要输出0
 
【code】:
 
 /**
Judge Status:Accepted Memory:748K
Time:32MS Language:G++
Code Lenght:1814B Author:cj
*/
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector> #define N 101
#define M 6000
using namespace std; struct Nod
{
int x,y,w;
}node[M]; int parent[N];
int n,m;
vector<int> vct; bool cmp(Nod a,Nod b)
{
return a.w<b.w;
} int findp(int a)
{
while(a!=parent[a])
{
a=parent[a];
}
return a;
} int merge(Nod nd) //合并
{
int x = findp(nd.x);
int y = findp(nd.y);
if(x>y)
{
parent[y]=x;
return nd.w;
}
else if(x<y)
{
parent[x]=y;
return nd.w;
}
return -;
} int kruskal(int id)
{
int i,sum=,cnt=;
for(i=;i<=n;i++) parent[i]=i;
for(i=;i<m;i++)
{
if(i!=id)
{
int temp = merge(node[i]);
if(temp!=-)
{
sum+=temp;
cnt++; //剪枝
if(id==-) vct.push_back(i); //保存第一次最小生成树的各个节点
}
if(cnt>=n-) //找到n-1条边即可以跳出了
break;
}
}
cnt = ;
for(i=;i<=n;i++) //判断是不是构成一棵树
if(parent[i]==i)
cnt++;
if(cnt==) //是
return sum;
if(id==-) //否
return ;
return -;
} int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
int i;
for(i=;i<m;i++)
{
scanf("%d%d%d",&node[i].x,&node[i].y,&node[i].w);
}
vct.clear();
sort(node,node+m,cmp);
int mins = kruskal(-); //找到第一颗最小生成树
int temp=-;
for(i=;i<vct.size();i++)
{
temp = kruskal(vct[i]); //每次去掉一个节点 再判断是否可以组成最小生成树
if(mins==temp)
break;
}
if(temp==mins) puts("Not Unique!");
else printf("%d\n",mins);
}
return ;
}