您的位置:首页 > 产品设计 > UI/UE

POJ 1679 The Unique MST(次小生成树)

2018-01-29 08:36 405 查看
The Unique MST

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions:33267 Accepted: 12111
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!

第一次把最小生成树的n-1条边记录下来,若可以不用其中的一条边
依然可以生成同样权值的最小生成树,则最小生成树不唯一
代码:

#include<bits/stdc++.h>
int n,m,par[102],rank1[102],edge[102],len;
using namespace std;
struct node
{
int from,to,cost;
}rode[10003];
bool cmp(node a,node b)
{
return a.cost<b.cost;
}
void init()
{
for(int i=0;i<=100;i++)
par[i]=i,rank1[i]=0;
len=0;
}
int find(int x)
{
if(x==par[x])return x;
return par[x]=find(par[x]);
}
bool same(int x,int y)
{
return find(x)==find(y);
}
void unite(int x,int y)
{
x=find(x);y=find(y);
if(x==y)return;
if(rank1[x]<rank1[y])
par[x]=y;
else
{
par[y]=x;
if(rank1[x]==rank1[y])
rank1[x]++;
}
}
int Kruskal(int dec)
{
init();
int i,j,ans=0;
for(i=1;i<=m;i++)
{
if(dec==i)continue;
node e=rode[i];
if(!same(e.from,e.to))
{
ans+=e.cost;
if(dec==-1)
edge[len++]=i;
unite(e.from,e.to);
}
}
bool bb=1;
for(i=2;i<=n;i++)
{
if(!same(1,i))
{
bb=0;break;
}
}
if(!bb)return -1;
else return ans;
}
int main()
{
int T;scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
int i,j;
for(i=1;i<=m;i++)
scanf("%d%d%d",&rode[i].from,&rode[i].to,&rode[i].cost);
sort(rode+1,rode+1+m,cmp);
int k=Kruskal(-1);
if(k==-1)
{
printf("Not Unique!\n");
continue;
}
bool bb=0;
for(i=0;i<n-1;i++)
{
if(k==Kruskal(edge[i]))
{
bb=1;break;
}
}
if(bb)printf("Not Unique!\n");
else printf("%d\n",k);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: