并查集模板题,注意二维坐标转化为一维坐标的巧妙用法
AcWing 1250. 格子游戏
#include<bits/stdc++.h>
using namespace std;
const int N = 40010;
int p[N]; //每个节点的祖先节点
int n, m;
int ans;
int find(int x){ //找到x的祖先接地
if(x != p[x]) x = find(p[x]);
return x;
}
int get(int x, int y){ //二维坐标转化为一维
return x * n + y;
}
int main()
{
cin>>n>>m;
for(int i = 1; i <= n * n; i ++ ) p[i] = i;
for(int i = 1; i <= m; i ++ ){
int x, y, a, b;
char crs;
cin>>x>>y>>crs;
x -- , y -- ; //这里--是为了让(0, 0)作为起始坐标
a = get(x, y);
if(crs == 'D') b = get(x + 1, y);
else if(crs == 'R') b = get(x, y + 1);
int fa = find(a), fb = find(b);
if(fa == fb){
ans = i;
break;
}
p[fb] = fa;
}
if(!ans) cout<<"draw"<<endl;
else cout<<ans<<endl;
return 0;
}