题解:P17267 [ICPC 2017 Urumqi R] A Possible Tree
CuteGielHina · · 题解
约定下文中所有
首先注意到树上
其中
因此,每条结论
设
用带权并查集来维护这个问题,每个节点
- 若
u 和v 在同一集合中,检查d_u \oplus d_v 是否等于val ,若不等于则产生冲突。 - 若不在同一集合,则合并两个集合,并根据异或方程更新
d_{root} 。
维护一个冲突标记
如果处理到最后都没有发生冲突的话,则
输出
注意异或值要用 unsigned long long 来存,不然会爆。
总复杂度为
:::info[代码]
#include<bits/stdc++.h>
#define BUF 1<<20
#define IL inline
#define ll long long
#define ri register int
#define F(i,a,b) for(ri i=a;i<=b;i++)
#define FF(i,a,b) for(ri i=b;i>=a;i--)
#define u64 uint64_t
#define ull unsigned long long
#define i128 __int128
#define vec vector
#define vi vector<int>
#define vll vector<ll>
#define vb vector<bool>
#define prq priority_queue
#define pii pair<int,int>
#define pill pair<int,ll>
#define plli pair<ll,int>
#define um unordered_map
#define mii map<int,int>
#define us unordered_set
#define pb(x) push_back(x)
#define fi first
#define se second
#define fr() front()
#define bk() back()
#define beg() begin()
#define Fill(a,b) memset(a,b,sizeof(a))
using namespace std;
const int N=1e6+5;
const ll inf=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-9;
char buf[BUF],*p1=buf,*p2=buf;
#define getchar_unlocked()((p1==p2)&&(p2=(p1=buf)+fread(buf,1,BUF,stdin),p1==p2)?EOF:*p1++)
int T,n,m,u,v,w;
vi g[N];
struct DSU{
int fa[N];
ull xo[N];
IL void init(){
F(i,1,n){
fa[i]=i;
xo[i]=0;
}
}
IL int find(int x){
if(fa[x]==x) return x;
int p=fa[x],rt=find(p);
xo[x]^=xo[p];
fa[x]=rt;
return rt;
}
} dsu;
IL int read(){
int k=0,f=1;
char c=getchar_unlocked();
while(c<'0'||c>'9'){
if(c=='-') f=-1;
c=getchar_unlocked();
}
while(c>='0'&&c<='9') k=k*10+c-'0',c=getchar_unlocked();
return k*f;
}
IL void write(int x){
if(x<0) putchar('-'),x=-x;
if(x<10) putchar(x+'0');
else write(x/10),putchar(x%10+'0');
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
T=read();
while(T--){
n=read(),m=read();
F(i,1,n) g[i].clear();
F(i,1,n-1){
u=read(),v=read();
g[u].pb(v),g[v].pb(u);
}
dsu.init();
int ans=m;
bool fl=0;
F(i,1,m){
u=read(),v=read(),w=read();
if(fl) continue;
int fu=dsu.find(u),fv=dsu.find(v);
ull xu=dsu.xo[u],xv=dsu.xo[v];
if(fu==fv){
if((xu^xv)!=w){
ans=i-1;
fl=1;
}
}
else{
dsu.fa[fv]=fu;
dsu.xo[fv]=xu^xv^w;
}
}
write(ans);
putchar('\n');
}
return 0;
}
:::