题目描述
分析
首先考虑如何形成一个环(封闭的圈), 即当两点已经连通时,再从两点间连一条线,便可以形成环
如何判断两点是否连通? 使用并查集.
此题是二维坐标,不过我们可以使用x*(n-1)+y
将二维坐标系上的每个点唯一映射到一维坐标系上来.
从而使用并查集判断连通性, 进而判环得到答案
实现
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int N = 5e4 + 9;
int n, m, x1, x2, y1, y2, pos1, pos2;
char dir;
int fa[N];
int transfer(int x, int y) // 将二维坐标映射到一维坐标中,方便用并查集
{
return x * (n-1) + y;
}
// 朴素并查集
void init()
{
for(int i=0; i<N; i++) fa[i] = i;
}
int find(int a)
{
return a == fa[a] ? a : fa[a] = find(fa[a]);
}
void merge(int a, int b)
{
int fx = find(a), fy = find(b);
if(fx != fy) fa[fx] = fa[fy];
}
int main()
{
init();
cin >> n >> m;
int ans = -1;
for(int i=1; i<=m; i++)
{
cin >> x1 >> y1 >> dir;
if(ans != -1) continue;
x2 = x1, y2 = y1;
pos1 = transfer(x1, y1);
if(dir == 'D') x2 += 1;
else if(dir == 'R') y2 += 1;
pos2 = transfer(x2, y2);
int fx = find(pos1), fy = find(pos2);
if(fx == fy) ans = i; // 如果两点已经连通,再连一条线,一定会形成封闭的环
else merge(pos1, pos2); // 否则就把两点相连
}
if(ans == -1) cout << "draw" << endl;
else cout << ans << endl;
return 0;
}