Luogu P1396 rescue

Luogu P1396 rescue

Originally just wanted to start with Dijkstra, but tune a long time there are problems, so determined to give up.
Consider for a moment the subject was later found could be considered minimum spanning tree, then open Kruskal.
Sure enough, the minimum spanning tree or a good thought.

#include<bits/stdc++.h>
#define N 10010
#define M 20010

using namespace std;

int n,m,s,t,cnt,tot,ans;
int fa[N];

struct node {
    int frm,to,val;
}edge[M];

void addEdge(int u,int v,int w) {
    edge[++cnt]=(node){u,v,w};
    return;
}

bool cmp(node a,node b) {
    return a.val<b.val;
}

int Find(int x) {
    return fa[x]==x?x:fa[x]=Find(fa[x]);
}

bool Merge(int x,int y) {
    return Find(x)==Find(y)?false:true;
}

void Union(int x,int y) {
    fa[Find(y)]=Find(x);
    return;
}

void Read() {
    scanf("%d%d%d%d",&n,&m,&s,&t);
    for(int i=1;i<=m;i++) {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        addEdge(u,v,w);
    }
    return;
}

void Init() {
    for(int i=1;i<=n;i++) {
        fa[i]=i;
    }
    return;
}

void Kruskal() {
    sort(edge+1,edge+cnt+1,cmp);
    for(int i=1;i<=cnt;i++) {
        if(Merge(edge[i].frm,edge[i].to)) {
            Union(edge[i].frm,edge[i].to);
            if(Merge(s,t)) {
                ans=max(ans,edge[i].val);
            }
            else {
                ans=max(ans,edge[i].val);
                break;
            }
        }
    }
    return;
}

void Print() {
    printf("%d",ans);
    return;
}

int main()
{
    Read();
    Init();
    Kruskal();
    Print();
    return 0;
}

Guess you like

Origin www.cnblogs.com/luoshui-tianyi/p/11695721.html