noip 关押罪犯(二分 + 染色)

12 篇文章 0 订阅
9 篇文章 0 订阅

noip 关押罪犯

题目

给一个无向图,让把顶点分成两部分,要求两个集合里最大边的权值最小。
在这里插入图片描述

分析

可以用扩展并查集,下面二分做法:

先二分枚举答案,即最大边,然后看大于答案的边所构成的图是不是二分图。

注意
要找最大边最小的值,即找二分右边最小的值。

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
#define d(x) cout<<(x)<<endl
const int N = 2e4 + 10;
const int M = 2e5 + 10;

int n, m;
int h[N], e[M], w[M], ne[M], idx;
int color[N];

void add(int a, int b, int c){
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

bool dfs(int u, int c, int limit){
    color[u] = c;
    for (int i = h[u]; ~i; i = ne[i])
    {
        if(w[i] <= limit)
            continue;
        int j = e[i];
        if (color[j])
        {
            if (color[j] == c)
                return false;
        }else if (!dfs(j, 3 - c, limit))
            return false;
    }
    return true;
}

bool check(int limit){
    memset(color, 0, sizeof color);
    for(int i = 1; i <= n; i++)
        if(color[i] == 0)
            if(!dfs(i, 1, limit))
                return false;
    return true;
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    while(m--){
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
        add(b, a, c);
    }
    int l = 0, r = 1e9;
    while(l < r){
        int mid = l + r >> 1;
        if(check(mid))
            r = mid;
        else
            l = mid + 1;
    }
    printf("%d\n", l);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值