P1525 关押罪犯 并查集

P1525 关押罪犯

题解:

  一拿到题目想到的是二分 + 奇奇怪怪的操作。

后来学到了并查集裸写就好了。

先将边权按大到小排序一边。

然后访问到一个边的时候。

先看一下这2个边有没有联通, 如果有联通就是说明在同一个块内, 输出这条边的权值作为答案。

否则 互相连到对方的敌人哪里。

代码:

#include<bits/stdc++.h>
using namespace std;
#define Fopen freopen("_in.txt","r",stdin); freopen("_out.txt","w",stdout);
#define LL long long
#define ULL unsigned LL
#define fi first
#define se second
#define pb push_back
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lch(x) tr[x].son[0]
#define rch(x) tr[x].son[1]
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
typedef pair<int,int> pll;
const int inf = 0x3f3f3f3f;
const int _inf = 0xc0c0c0c0;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const LL _INF = 0xc0c0c0c0c0c0c0c0;
const LL mod =  (int)1e9+7;
const int N = 2e5 + 100;
int pre[N];
int enemy[N];
int Find(int x){
    if(x == pre[x]) return x;
    return pre[x] = Find(pre[x]);
}
struct Node{
    int u, v, w;
    bool operator < (const Node & x)const{
        return w > x.w;
    }
}e[N];
int main(){
    int n, m;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; ++i)
        pre[i] = i;
    for(int i = 1; i <= m; ++i)
        scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);
    sort(e+1, e+1+m);
    for(int i = 1; i <= m; ++i){
        int tu = Find(e[i].u), tv = Find(e[i].v);
        if(tu == tv) {
            printf("%d\n", e[i].w);
            return 0;
        }
        if(!enemy[tu]) enemy[tu] = tv;
        pre[tv] = Find(enemy[tu]);
        if(!enemy[tv]) enemy[tv] = tu;
        pre[tu] = Find(enemy[tv]);
    }
    puts("0");
    return 0;
}
View Code

 

posted @ 2019-07-07 19:50  Schenker  阅读(132)  评论(0编辑  收藏  举报