(图论:并查集)关押罪犯

(图论:并查集)关押罪犯

https://www.luogu.org/problemnew/show/P1525

const int maxn = 2e4 + 10;
const int maxm = 1e5 + 10;
struct node
{
    int u, v, w;
    bool operator<(const node &x) const
    {
        return w > x.w;
    }
} a[maxm];
int pre[maxn << 1]; //双倍大小用于储存另一个监狱
int find(int x) { return x == pre[x] ? x : pre[x] = find(pre[x]); }
int main()
{
    int n, m;
    scanf("%d%d", &n, &m);
    for (register int i = 0; i < m; i++)
        scanf("%d%d%d", &a[i].u, &a[i].v, &a[i].w);
    sort(a, a + m);
    for (register int i = 1; i <= (n << 1); i++)
        pre[i] = i;
    bool flag = false;
    for (register int i = 0; i < m; i++)
    {
        int u = a[i].u, v = a[i].v, w = a[i].w;
        if (find(u) == find(v) || find(u + n) == find(v + n))
        {
            printf("%d\n", w);
            flag = true;
            break;
        }
        pre[find(u + n)] = find(v);
        pre[find(v + n)] = find(u);
    }
    if (!flag)
        printf("0\n");
}

种类并查集

你可能感兴趣的:(总结)