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

poj1679 The Unique MST

2016-09-21 17:17 337 查看
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!’.

先求最小生成树,然后枚举换掉某一条边,看是否仍和原来的大小相等。

就具体做法就是枚举强制不选每一条边,然后求最小生成树。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge
{
int f,t,l;
bool operator < (const edge & ee) const
{
return l<ee.l;
}
}g[10010];
int n,m,fa[110],use[10010],ban[10010];
bool mark;
int find(int x)
{
return x==fa[x]?x:fa[x]=find(fa[x]);
}
int kru()
{
int i,j,k,x,y,z,ans=0,cnt=0;
for (i=1;i<=n;i++)
fa[i]=i;
for (i=1;cnt<n-1;i++)
if (!ban[i])
{
x=find(g[i].f);
y=find(g[i].t);
if (x==y) continue;
ans+=g[i].l;
cnt++;
fa[x]=y;
if (mark) use[i]=1;
}
return ans;
}
int main()
{
int i,j,k,x,y,z,T,ans;
bool flag;
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&n,&m);
for (i=1;i<=m;i++)
use[i]=ban[i]=0;
for (i=1;i<=m;i++)
scanf("%d%d%d",&g[i].f,&g[i].t,&g[i].l);
sort(g+1,g+m+1);
mark=1;
ans=kru();
mark=0;
flag=0;
for (i=1;i<=m;i++)
if (use[i])
{
ban[i]=1;
if (ans==kru())
{
flag=1;
break;
}
ban[i]=0;
}
if (flag) printf("Not Unique!\n");
else printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  最小生成树