参见算法竞赛进阶指南190页
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
int n, m, num[10005], qwq=1, fa[10005], dis[10005];
char ss[15];
struct Node{
int l, r, ans;
}nd[5005];
int myfind(int x){
if(x==fa[x]) return x;
int rot=myfind(fa[x]);
dis[x] ^= dis[fa[x]];
return fa[x]=rot;
}
int main(){
cin>>n>>m;
n = 0;
for(int i=1; i<=m; i++){
scanf("%d %d %s", &nd[i].l, &nd[i].r, ss);
nd[i].l--;
nd[i].ans = ss[0]==‘o‘;
num[++n] = nd[i].l;
num[++n] = nd[i].r;
}
sort(num+1, num+1+n);
n = unique(num+1, num+1+n) - num - 1;
for(int i=1; i<=m; i++){
nd[i].l = lower_bound(num+1, num+1+n, nd[i].l) - num;
nd[i].r = lower_bound(num+1, num+1+n, nd[i].r) - num;
}
for(int i=1; i<=n; i++) fa[i] = i;
for(int i=1; i<=m; i++){
int r1=myfind(nd[i].l), r2=myfind(nd[i].r);
if(r1==r2){
if(nd[i].ans!=(dis[nd[i].l]^dis[nd[i].r])) break;
}
else{
fa[r1] = r2;
dis[r1] = dis[nd[i].l] ^ dis[nd[i].r] ^ nd[i].ans;
}
qwq++;
}
printf("%d\n", qwq-1);
return 0;
}