[P1396]营救 (并查集)

大佬都是用最短路做的

我用最小生成树

#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
struct edge{
    int u,v,w;
    bool operator <(const edge &now)
    const {
        return w<now.w;
    }
}e[20005];
int f[20005]; 
int tot;
void add(int x,int y,int z)
{
    tot++;e[tot].u=x;e[tot].v=y;e[tot].w=z;
}
int gf(int u)
{
    while(u!=f[u]) u=f[u]=f[f[u]];
    return u;
}
int main()
{
    int n,m,s,t;
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1;i<=n;i++) f[i]=i;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;scanf("%d%d%d",&x,&y,&z);
        add(x,y,z);
    }
    sort(e+1,e+1+tot);
    int ans=-1;
    for(int i=1;i<=tot;i++)
    {
        int fx=gf(e[i].u),fy=gf(e[i].v);
        if(fx!=fy){
            ans=max(ans,e[i].w);
            f[fx]=fy;
        }
        if(gf(s)==gf(t))
        {
            printf("%d",e[i].w);
            return 0;
        }
    }
    //printf("%d",ans);
    return 0;
}

可能被hack的吧?

猜你喜欢

转载自www.cnblogs.com/fsy2017/p/9927170.html