【并查集】ACW1250. 格子游戏

题目

代码

#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <queue>
#include <functional>
#include <unordered_set>
#include <set>
#include <bitset>
#include <cstdio>

using namespace std;

const int N = 1e5 + 1;
int p[N];
int n, m;

inline int get(int x, int y) {
    return x * n + y;
}

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

int main() {
    ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 0; i < n * n; i++) {
        p[i] = i;
    }
    // 将二维压缩成一维, 使用 n * x + y
    // 再判定压缩成一维后是否连接到同一个点
    // 则为形成闭圈
    int res = 0;
    for (int i = 1; i <= m; i++) {
        int x, y;
        char op;
        cin >> x >> y >> op;
        // R x+1 D y-1
        // 判断一条直线的两端是否有同一个源点
        // 有的化就表明连接闭合
        x--, y--; // 减一使得可以使得部分点贴合坐标,使其围城一个圈
        int a = get(x, y), b;
        if (op == 'R') b = get(x, y+1);
        else b = get(x+1, y);
        int fa = find(a), fb = find(b);
        if (fa == fb) {
            res = i;
            break;
        }
        p[fa] = fb;
    }
    if (!res) cout << "draw" << endl;
    else cout << res << endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值