POJ 1679 The Unique MST

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’.


【题目分析】
关于最小生成树是否唯一的问题。只需要计算一下删除任意一条原有的生成树的边,然后再跑一边最小生成树,然后比较一下是否相等就可以了。


【代码】

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct edge{
    int a,b,w;
}c[20000];
int f[110],list[110];
inline int gf(int k)
{
    if (f[k]==k) return k;
    else return f[k]=gf(f[k]);
}
inline bool cmp(edge a,edge b)
{return a.w<b.w;}
inline void un(int a,int b)
{
    int fa=gf(a),fb=gf(b);
    if (fa==fb) return;
    else f[fa]=fb;
    return;
}
inline void kru()
{
    int n,m,ans=0,ans2=0,k2,k=0;
    scanf("%d%d",&n,&m);
    memset(c,0,sizeof c);
    memset(list,0,sizeof list);
    for (int i=1;i<=m;++i) scanf("%d%d%d",&c[i].a,&c[i].b,&c[i].w);
    for (int i=1;i<=n;++i) f[i]=i;
    sort(c+1,c+m+1,cmp);
    for (int i=1;i<=m&&k<n-1;++i)
    {
        int f1=gf(c[i].a),f2=gf(c[i].b);
        if (f1!=f2)
        {
            un(f1,f2);
            ++k;
            ans+=c[i].w;
            list[k]=i;
        }
    }
    for (int i=1;i<n;++i)
    {
        ans2=0,k2=0;
        for (int j=1;j<=n;++j) f[j]=j;
        for (int j=1;j<=m;++j)
        {
            if (j==list[i]) continue;
            int f1=gf(c[j].a),f2=gf(c[j].b);
            if (f1!=f2)
            {
                un(f1,f2);
                k2++;
                ans2+=c[j].w;
            }
        }
        if (k2!=n-1) continue;
        if (ans==ans2){
            printf("Not Unique!\n");
            return ;
        }
    }
    printf("%d\n",ans);
}
int main()
{
    int tt;
    scanf("%d",&tt);
    for (int z=1;z<=tt;++z)
    {
        kru();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值