The Unique MST
Description Given a connected undirected graph, tell if its minimum spanning tree is unique. 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 Sample Output Source POJ Monthly--2004.06.27 srbga@POJ
扫描二维码关注公众号,回复:
4520198 查看本文章
|
[Submit] [Go Back] [Status] [Discuss]
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstring>
#include<algorithm>
#include<vector>
#define maxn 1005
#define maxm 1000*1000+5
using namespace std;
struct edge{
int u,v,dis;
int id;
edge(){}
edge(int u,int v,int dis,int id):u(u),v(v),dis(dis),id(id){}
bool operator<(const edge&rhs)const
{
return dis<rhs.dis;
}
};
int t;
struct krus
{int n,m;
vector<int>e;
int father[maxn];
edge edges[maxm];
int find(int x)
{
if(father[x]!=x)
father[x]=find(father[x]);
return father[x];
}
void init(int n)
{
this->n=n;
m=0;
}
void addedge(int u,int v,int dis,int id)
{
edges[m++]=edge(u,v,dis,id);
}
int kr(int Id)
{for(int i=0;i<=n;i++)
father[i]=i;
e.clear();
int sum=0;
int ans=0;
sort(edges,edges+m);
for(int i=0;i<m;i++)
{
if(edges[i].id==Id)
continue;
int u=edges[i].u,v=edges[i].v;
if(find(u)!=find(v))
{e.push_back(edges[i].id);
father[find(u)]=find(v);
sum+=edges[i].dis;
if(++ans>=n-1)
break;
}
}
if(ans<n-1)
return -1;
return sum;
}
}kru;
int main()
{int n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
kru.init(n);
int u,v,w;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&u,&v,&w);
kru.addedge(u,v,w,i);
}
int ans1=kru.kr(-1);
int ans2=1e9;
vector<int>e(kru.e);
for(int i=0;i<e.size();i++)
{
int tmp=kru.kr(e[i]);
if(tmp==-1)
continue;
ans2=min(ans2,tmp);
if(ans2==ans1)
break;
}
if(ans1==ans2)
printf("Not Unique!\n");
else
printf("%d\n",ans1);
}
return 0;
}