The Unique MST
http://poj.org/problem?id=1679
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 36744 | Accepted: 13395 |
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
模板题
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
#include<vector>
#include<queue>
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define N 250500
#define MOD 1e9+7
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;
struct sair{
int x,y,v;
}a[];
int fa[];
int n,m;
bool cmp(sair a,sair b){
return a.v<b.v;
} int Find(int x){
int r=x,y;
while(x!=fa[x]){
x=fa[x];
}
while(x!=r){
y=fa[r];
fa[r]=x;
r=y;
}
return x;
} int join(int x,int y){
int xx=Find(x);
int yy=Find(y);
if(xx==yy){
return ;
}
fa[xx]=yy;
return ;
} vector<int>v; int check(int xxx){
int ans=;
int xxxx=;
for(int i=;i<=n;i++){
fa[i]=i;
}
for(int i=;i<=m;i++){
if(i!=xxx){
if(join(a[i].x,a[i].y)){
ans+=a[i].v;
xxxx++;
}
}
}
if(xxxx==n)
return ans;
return -;
} int main(){
std::ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
cin>>n>>m;
for(int i=;i<=n;i++){
fa[i]=i;
}
for(int i=;i<=m;i++){
cin>>a[i].x>>a[i].y>>a[i].v; }
int ans1=;
v.clear();
sort(a+,a+m+,cmp);
for(int i=;i<=m;i++){
if(join(a[i].x,a[i].y)){
ans1+=a[i].v;
v.push_back(i);
}
}
int flag=;
for(int i=;i<v.size();i++){
if(check(v[i])==ans1){
flag=;
break;
}
}
if(flag){
cout<<ans1<<endl;
}
else{
cout<<"Not Unique!"<<endl;
}
}
}