题意:你的朋友写下一串包含1和0的串让你猜,你可以从中选择一个连续的子串(例如其中的第3到第5个数字)问他,该子串中包含了奇数个还是偶数个1,他会回答你的问题,然后你可以继续提问......你怀疑朋友的答案可能有错,或说同他之前的答案相互矛盾,例如:1 - 2 奇数,3 - 4 奇数,那么可以确定1 - 4 一定是偶数,如果你的朋友回答是奇数,就产生了矛盾。给出所有你朋友的答案,请你找出第一个出现矛盾的答案。
思路:如果[l,r]是even,那么[1,l-1]和[1,r]中1的个数都是偶数 or 奇数(奇偶性相同).
如果[l,r]是odd,那么 [1,l-1] 和 [1,r]的奇偶性不同.
就转换成了判断前缀和的问题
所以用[1,n]表示‘相同‘关系,[n+1,2*n]虚拟表示‘不同‘关系.建立两个集合
判断 (l-1+n,r) && (l-1,b+n) 就能确定 l-1和r是否为‘相同‘关系. 其它同理
与 关押罪犯(点击打开链接) 那个题的做法非常类似
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
int n, q, pre[maxn];
char str[5];
int Find(int x)
{
int r = x;
while(pre[r] != r) r = pre[r];
int i = x, j;
while(i != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
void join(int x, int y)
{
int a = Find(x);
int b = Find(y);
if(a != b)
pre[b] = a;
}
int main(void)
{
while(cin >> n >> q)
{
for(int i = 0; i < maxn; i++)
pre[i] = i;
int ans = -1, id = 0, ok = 0;
while(++id <= q)
{
int l, r;
scanf("%d%d %s", &l, &r, str);
if(ok) continue;
if(str[0] == 'e')
{
if(Find(l-1) == Find(r+n) && Find(l-1+n) == Find(r))
{
ok = 1;
ans = id;
}
else
{
join(l-1, r);
join(l-1+n, r+n);
}
}
else
{
if(Find(l-1) == Find(r) && Find(l-1+n) == Find(r+n))
{
ok = 1;
ans = id;
}
else
{
join(l-1, r+n);
join(l-1+n, r);
}
}
}
printf("%d\n", ans);
}
return 0;
}