The Unique MST

来源:互联网 发布:网络借贷暂行管理办法 编辑:程序博客网 时间:2024/06/04 00:27

The Unique MST

  • 查看
  • 提交
  • 统计
  • 提问
总时间限制: 
1000ms 
内存限制: 
65536kB
描述
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'.
输入
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.
输出
For each input, if the MST is unique, print the total cost of it, or otherwise print the string 'Not Unique!'.
样例输入
23 31 2 12 3 23 1 34 41 2 22 3 23 4 24 1 2
样例输出
3Not Unique!
来源
POJ Monthly--2004.06.27 srbga@POJ

#include<iostream>#include<cmath>#include<cstring>#include<algorithm>#include<iomanip>#include<queue>#include<stack>#include<vector>#include<set>#include<map>using namespace std;int father[105];struct edge{int s,t,w;}E[5005];bool Vis[5005]={0};bool cmp(const edge&a,const edge&b){return a.w<b.w;}int Getfather(int x){if(father[x]==x)return x;int tmp=Getfather(father[x]);father[x]=tmp;return tmp;}bool Valid(int x){if(Vis[x])return false;int fs=Getfather(E[x].s);int ft=Getfather(E[x].t);return fs!=ft;}int main(){int Test;cin>>Test;while(Test--) {int n,m,s,t,w;memset(Vis,0,sizeof(Vis));cin>>n>>m;for(int i=1;i<=n;++i){father[i]=i;}for(int i=0;i<m;++i){cin>>E[i].s>>E[i].t>>E[i].w;}sort(E,E+m,cmp);int num=n-1,sum=0;bool Unique=true;while(num--){for(int i=0;i<m;++i){if(Valid(i)){for(int j=i+1;j<m;++j){if(E[j].w>E[i].w)break;if(Valid(j)){Unique=false;break;}}if(!Unique)break;Vis[i]=true;int fs=Getfather(E[i].s);int ft=Getfather(E[i].t);father[fs]=ft;sum+=E[i].w;}}if(!Unique)break;}if(Unique)cout<<sum<<endl;else cout<<"Not Unique!"<<endl;}return 0;}


原创粉丝点击