题目链接:http://poj.org/problem?id=1733
题意:给定n长的字符串,m个假设,输出第几个假设是错误的,若都是正确的,输出m。
带全并查集裸模板,然后因为这题只有奇数还是偶数这两个情况,所以直接取两个数值就好了。
下图是带全并查集的理解,向量做法。
其实只要固定一个方向就可以了,不需要分情况。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int n, m;
map<int, int> father;
map<int, int> rank;
int find(int x)
{
if(!father[x])
return x;
int f = father[x];
father[x] = find(father[x]);
rank[x] = (rank[x]+rank[f]) % 2; // 0表示偶数 1表示奇数
return father[x];
}
int main()
{
while(~scanf("%d", &n))
{
scanf("%d", &m);
int flag = 0;
int ans = 0;
father.clear();
rank.clear();
for(int i = 0; i < m; i++)
{
int x, y, d;
char op[5];
scanf("%d%d%s", &x, &y, op);
x--;
if(op[0] == 'e')
d = 0;
else
d = 1;
int fx = find(x);
int fy = find(y);
if(fx != fy)
{
father[fx] = fy;
rank[fx] = (rank[y]-rank[x]+d+2) % 2;
}
else
{
if(flag==0 && (rank[x]-rank[y]+2)%2 != d)
ans = i, flag = 1;
}
}
if(!flag)
ans = m;
printf("%d\n", ans);
}
return 0;
}