描述
n x n的点阵,m次操作,每次对相邻的点连边,问第一次出现封闭的圈是哪次操作
分析
复习一下并查集,模板题,将点阵的点看成离散的点,并查集判环即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 40010;
int fa[N];
int get(int x)
{
if (fa[x] == x) return x;
return fa[x] = get(fa[x]);
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n * n; i++) fa[i] = i;
int ans = 0;
for (int i = 1; i <= m; i++)
{
int x, y;
char s[3];
scanf("%d%d%s", &x, &y, s);
int a = (x - 1) * n + y, b;
if (s[0] == 'D') b = x * n + y;
else b = (x - 1) * n + y + 1;
int ra = get(a), rb = get(b);
if (ra == rb)
{
ans = i;
break;
}
fa[ra] = rb;
}
if (!ans) puts("draw");
else printf("%d\n", ans);
}