其他分享
首页 > 其他分享> > 洛谷 P1525 关押罪犯

洛谷 P1525 关押罪犯

作者:互联网

洛谷 P1525 关押罪犯

Description

Input

Output

Sample Input

4 6
1 4 2534
2 3 3512
1 2 28351
1 3 6618
2 4 1805
3 4 12884

Sample Output

3512

Data Size

题解:

#include <iostream>
#include <cstdio>
#include <cstring>
#define N 20005
#define M 200005
using namespace std;

struct E {int next, to, dis;} e[M];
int n, m, num;
int h[N], tag[N];

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

void add(int u, int v, int w)
{
    e[++num].next = h[u];
    e[num].to = v;
    e[num].dis = w;
    h[u] = num;
}

bool dfs(int x, int col, int val)
{
    tag[x] = col;
    for(int i = h[x]; i != 0; i = e[i].next)
    {
        int v = e[i].to;
        if(e[i].dis > val && tag[v] == tag[x]) return 0;
        else if(e[i].dis > val && !tag[v] && !dfs(v, -col, val)) return 0;
    }
    return 1;
}

bool check(int val)
{
    memset(tag, 0, sizeof(tag));
    int flag = 0;
    for(int i = 1; i <= n; i++)
        if(!tag[i] && !dfs(i, 1, val))
            {flag = 1; break;}
    return !flag;
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int u = read(), v = read(), w = read();
        add(u, v, w), add(v, u, w);
    }
    int l = 0, r = 0x7fffffff, ans;
    while(l <= r)
    {
        int mid = l + r >> 1;
        if(check(mid)) r = mid - 1, ans = mid;
        else l = mid + 1;
    }
    cout << ans;
    return 0;
}

标签:P1525,二分,洛谷,关押,int,tag,罪犯,冲突,return
来源: https://www.cnblogs.com/BigYellowDog/p/11735807.html