黑书上的题,刚开始看不会,找结题报告,网上一大堆用什么异或思想,完全把问题复杂化,纠结了一下午加一个晚上,最后终于找到一种好理解的思想,
如果i, j 间的1个数为偶数, 那么1 ~ i - 1, 和 1 ~ j的1的个数的奇偶性是相同的,否则相反,此外如果某个判断的两个端点含有以前未出现的端点,那么这两个端点间的奇偶性是无法断定的。问题退化到了分组的问题,简单的并查集就可以解决。此外还有用hash离散化数据,因为10亿数组开不了。详见孙林春-2002-国家集训队论文
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define N 10009
using namespace std;
struct node{
int num, value, next;
};
int head[N], p[2 * N];
node a[N];
int cnt;
//const int PRIME = 100003;//大质数
const int PRIME = 10007;
void init()
{
for (int i = 0; i < N; i++)
head[i] = -1;
for (int i = 0; i < 2 * N; i++)
p[i] = i;
}
int hash(int x)
{
int h = x % PRIME;
for (int i = head[h]; i != -1; i = a[i].next)
{
if (x == a[i].value)
return a[i].num;
}
a[cnt].value = x;
a[cnt].num = cnt;
a[cnt].next = head[h];
head[h] = cnt++;
return cnt - 1;
}
int find(int x)
{
return p[x] == x? x: (p[x] = find(p[x]));
}
int main()
{
memset (head, -1, sizeof(head));
int n, m;
cnt = 0;
FILE* fp = fopen("in.txt", "r");
fscanf(fp, "%d %d", &n, &m);
init();
int ans = m;
for (int k = 1; k <= m; k++)
{
int x, y ;
char op[10];
fscanf(fp, "%d %d %s", &x, &y, op);
x = hash(x - 1), y = hash(y);
int x1 = find(x), x2 = find(x + N);
int y1 = find(y), y2 = find(y + N);
if (op[0] == 'e')
{
if (x2 == y1 || x1 == y2){
ans = k - 1;
goto result;
}
else {
p[x1] = y1, p[x2] = y2;
}
}
else {
if (x1 == y1 || x2 == y2){
ans = k - 1;
goto result;
}
else {
p[x1] = y2, p[x2] = y1;
}
}
}
result:
printf("%d\n", ans);
getchar();
return 0;
}