二分图 : 染色法

关押罪犯

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 20010, M = 200010;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int color[N];

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

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


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

int main() {
    IO; 
    cin >> n >> m;
    memset(h, -1, sizeof h);
    while (m--) {
        int a, b, c;
        cin >> 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;
    }
    cout << r << '\n';
    return 0;
}

posted @ 2021-02-22 17:03  phr2000  阅读(80)  评论(0编辑  收藏  举报