acwing 1250. 格子游戏(并查集维护集合连通性)

题意

  1. 两个人在一个 n*n 的方格上选边,谁先形成在选择一条边之后形成封闭的圈谁就输。
  2. 现在给出两个人的选边 m 次操作,问谁输。
  3. 如果到最后都无法判断谁输,就输出 draw

思路

  1. 并查集维护集合连通性。

代码

#include <bits/stdc++.h>
using namespace std;

int n, m;
const int N = 4e4 + 250;
int fa[N];

int find(int x)
{
    
    
    if (fa[x] == x) return x;
    return fa[x] = find(fa[x]);
}

int main()
{
    
    
    for (int i = 1; i < N; i ++) fa[i] = i;
    scanf("%d %d", &n, &m);
    int x, y, tx, ty; char ch;
    for (int i = 1; i <= m; i ++) {
    
    
        scanf("%d %d %c ", &x, &y, &ch);
        if (ch == 'D')
        {
    
    
            tx = x + 1;
            ty = y;
        }
        else
        {
    
    
            tx = x;
            ty = y + 1;
        }

        int u = x * n + y;
        int v = tx * n + ty;
        u = find(u), v = find(v);
        if (u == v)
        {
    
    
            printf("%d\n", i);
            return 0;
        }
        else fa[u] = v;
    }

    printf("draw\n");

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34261446/article/details/121146211