COGS 1578. 次小生成树初级练习题

http://www.cogs.pro/cogs/problem/problem.php?pid=1578

 

【题目描述】

求严格次小生成树

【输入格式】

第一行包含两个整数N 和M,表示无向图的点数与边数。 接下来 M行,每行 3个数x y z 表示,点 x 和点y之间有一条边,边的权值为z。

【输出格式】

包含一行,仅一个数,表示严格次小生成树的边权和。(数据保证必定存在严格次小生成树)

【样例输入】

5 6

1 2 1

1 3 2

2 4 3

3 5 4

3 4 3

4 5 6

【样例输出】

11

【提示】

数据中无向图无自环; 50% 的数据N≤2 000 M≤3 000; 80% 的数据N≤50 000 M≤100 000; 100% 的数据N≤100 000 M≤300 000 ,边权值非负且不超过 10^9 。

 

#include<bits/stdc++.h>
using namespace std;
#define maxn 10000000
int n,m,k,ans=maxn,cnt,tot,flag,fa[maxn],use[maxn];
struct Edge{
    int l,r,w;
}edge[maxn];

int find(int x) { return fa[x]==x?x:fa[x]=find(fa[x]); }
bool cmp(Edge a,Edge b) { return a.w<b.w; }

int main()
{
    freopen("mst2.in","r",stdin);
    freopen("mst2.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) fa[i]=i;
    for(int i=1;i<=m;i++) scanf("%d%d%d",&edge[i].l,&edge[i].r,&edge[i].w);
    sort(edge+1,edge+m+1,cmp);
    for(int i=1;i<=m;i++)
    {
        int fx=find(edge[i].l),fy=find(edge[i].r);
        if(fx!=fy)
        {
            use[++cnt]=i;
            fa[fx]=fy;
            tot+=edge[i].w;
        }
        if(cnt==n-1) break;
    }
    for(int i=1;i<=cnt;i++)
    {
        for(int j=1;j<=n;j++) fa[j]=j;
        int cnt2=0,tot2=0;
        for(int j=1;j<=m;j++)
        {
            if(j!=use[i])
            {
                int fx=find(edge[j].l),fy=find(edge[j].r);
                if(fx!=fy)
                {
                    cnt2++;
                    tot2+=edge[j].w;
                    fa[fx]=fy;
                }
            }
            if(cnt2==n-1&&tot2!=tot)    ans=min(ans,tot2);
        }
    }
    printf("%d",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/chen74123/p/7418598.html