D. The Number of Imposters(带权并查集)
Posted thusloop
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D. 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
*/
以上是关于D. The Number of Imposters(带权并查集)的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces Round #747 (Div. 2) D. The Number of Imposters(并查集,二分图)
扩展域并查集Codeforces Round #747 (Div. 2) D. The Number of Imposters
扩展域并查集Codeforces Round #747 (Div. 2) D. The Number of Imposters
Educational Codeforces Round 106 (Rated for Div. 2)D. The Number of Pairs(推式子)
Codeforces Round #411 (Div. 2)D. Minimum number of steps(贪心)
ValueError: The number of elements in ‘fill‘ does not match the number of bands of the image (3 != 4