题目
题意: 有三类动物,A吃B、B吃C、C吃A。现在给出k句话,判断有多少句话为假话。如果某句话与前边的话形成的条件存在冲突,默认这句话为假,否则为真。
1 x y: x和y为同类
2 x y: x吃y
**思路:**维护带权并查集,0:与祖宗同类,1:吃祖宗那一类,2:被祖宗吃。
时间复杂度: O(n + k*α(n))
代码:
// Problem: 职业玩家
// Contest: QDUOJ
// URL: https://qduoj.com/problem/22Spring10
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<complex>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<unordered_map>
#include<list>
#include<set>
#include<queue>
#include<stack>
#define OldTomato ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
#define fir(i,a,b) for(int i=a;i<=b;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define p_ priority_queue
// round() 四舍五入 ceil() 向上取整 floor() 向下取整
// lower_bound(a.begin(),a.end(),tmp,greater<ll>()) 第一个小于等于的
// #define int long long //QAQ
using namespace std;
typedef complex<double> CP;
typedef pair<int,int> PII;
typedef long long ll;
// typedef __int128 it;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const ll inf = 1e18;
const int N = 2e5+10;
const int M = 1e6+10;
const int mod = 1e9+7;
const double eps = 1e-6;
inline int lowbit(int x){ return x&(-x);}
template<typename T>void write(T x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9)
{
write(x/10);
}
putchar(x%10+'0');
}
template<typename T> void read(T &x)
{
x = 0;char ch = getchar();ll f = 1;
while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
int n,m,k,T;
int fa[N];
int d[N]; //带权并查集.0:同类,1:吃根节点,2:被根节点吃.
int find(int x)
{
if(x != fa[x])
{
d[x] += d[fa[x]];
fa[x] = find(fa[x]);
}
return fa[x];
}
void solve()
{
read(n); read(m);
fir(i,1,n) fa[i] = i;
int ans = 0;
for(int i=0;i<m;++i)
{
int op,x,y; read(op),read(x),read(y);
if(x>n||y>n) {ans ++ ; continue;}
int u = find(x),v = find(y);
if(op == 1) //A、B是同类
{
if(u == v && ((d[x]-d[y])%3 != 0))
{
ans ++ ;
}
else if(u != v)
{
fa[u] = v;
d[u] = d[y] - d[x];
}
}
else
{
if(u == v && ((d[x]-d[y]-1)%3 != 0))
{
ans ++ ;
}
else if(u != v)
{
fa[u] = v;
d[u] = d[y] - d[x] + 1;
}
}
}
write(ans);
}
signed main(void)
{
T = 1;
// OldTomato; cin>>T;
// read(T);
while(T--)
{
solve();
}
return 0;
}