zoukankan      html  css  js  c++  java
  • 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
    ", 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
  • 相关阅读:
    Windows 和Linux 误删除后的恢复
    AWS 使用总结
    20180814 错误分析
    你必须知道的互联网协议详解
    linux常用命令和关闭防火墙
    Nginx之ngx_http_fastcgi_module模块详解
    nginx 限制ip
    nginx allow 多个ip & ipv4的网段表示方法解析
    从Nginx的Web请求处理机制中剖析多进程、多线程、异步IO
    剑指offer:二叉树的深度
  • 原文地址:https://www.cnblogs.com/MingSD/p/11147424.html
Copyright © 2011-2022 走看看