寒假刷題32:洛谷P1111 修復公路(並查集)

題目鏈接:

P1111 修復公路

題目解析:

先按時間排序,每次合併兩個節點,如果原先不連通那麼合併之後聯通塊數量減一

AC代碼:

#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct hh
{
    int x,y,t;
}a[200000];
int f[200000],n,m;
int cmp(const hh &a,const hh &b){return a.t<b.t;}
int getfa(int x){return f[x]==x?x:(f[x]=getfa(f[x]));}
int main()
{
    cin>>n>>m;
    
    for(int i=1;i<=m;i++) cin>>a[i].x>>a[i].y>>a[i].t;
    sort(a+1,a+m+1,cmp);
    for(int i=1;i<=n;i++)f[i]=i;
    for(int i=1;i<=m;i++)
    {
        int fx=getfa(a[i].x),fy=getfa(a[i].y);
        if(fx!=fy)f[fx]=fy,n--;
        if(n==1){cout<<a[i].t;return 0;}
    }
    cout<<-1<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章