D. The Number of Imposters(带权并查集)

The Number of Imposters

//#pragma GCC optimize(2)
//#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int inf=2e18+100;
const int maxn=2e5+100;
int a[maxn],pre[maxn],cnt[maxn][2];
int n,m;
int find(int x)
{
	if(x!=pre[x])
	{
		int root=find(pre[x]);
		a[x]^=a[pre[x]];
		pre[x]=root;
	}
	return pre[x];
}
signed main()
{
	IOS
	int tt;
	cin>>tt;
	while(tt--)
	{
		bool fg=1;
		cin>>n>>m;
		for(int i=1; i<=n; i++)
		{
			pre[i]=i;
			a[i]=0;
			cnt[i][0]=1;
			cnt[i][1]=0;
		}
		for(int i=1; i<=m; i++)
		{
			int x,y;
			string str;
			cin>>x>>y>>str;
			int val=0;
			if(str[0]=='i')val=1;
			int fx=find(x),fy=find(y);
			if(fx==fy)
			{
				if((a[x]^a[y])!=val)fg=0;
			}
			else
			{
				pre[fy]=fx;
				if((a[x]^a[y])!=val)
				{
					a[fy]^=1;
					cnt[fx][1]+=cnt[fy][0];
					cnt[fx][0]+=cnt[fy][1];
				}
				else
				{
					cnt[fx][1]+=cnt[fy][1];
					cnt[fx][0]+=cnt[fy][0];
				}
			}
		}
		int ans=0;
		for(int i=1;i<=n;i++)
		{
			if(pre[i]==i)ans+=max(cnt[i][0],cnt[i][1]);
		}
		if(fg==0)cout<<"-1"<<"\n";
		else cout<<ans<<"\n";
	}
}
/*
1
5 4
1 2 i
3 4 i
2 3 e
4 5 i

1
5 4
1 2 i
4 3 i
2 3 e
4 5 i
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

thusloop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值