Description
A long time ago in a galaxy far, far away, there were N planets. There were also N − 1 interplanetary paths that connected all the planets (directly or indirectly). In other words, the network of planets and paths formed a tree. Additionally, each path was enumerated with an integer that denoted the
curiosity of the path.
A pair of planets A, B is boring if the following holds:
• A and B are different planets
• travelling between planet A and B is possible using one or more interplanetary paths
• binary XOR of the curiosity of all the paths in that travel is equal to 0
Alas, the times have changed and an evil emperor is ruling the galaxy. He decided to use the Force to destroy all the interplanetary paths in a certain order.
Determine the number of boring pairs of planets before the emperor started the destruction and after each destruction.
Solution
乍一看无从下手。
本来想瞎逼搞个什么树形dp之类的发现不好搞,搞得不好会被卡常数。
比赛的时候就没去敲了==
然而Solution大概就是树形dp之类的。
我们维护每个节点到它的最上面的father的路劲异或值
把删边当作加边写。
每次加边都暴力合并(当然是启发式合并)
合并过程中query并且维护dis
query的过程就是在合并的另外一棵树中找dis
这样就没了
还是卡常数。。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
const int M=1e5+5;
#define pb push_back
#define vec vector<int>
int n,Edge[M][3],fa[M],sz[M],dis[M],id[M];
inline void rd(int &a){
a=0;char c;
while(c=getchar(),!isdigit(c));
do a=a*10+(c^48);
while(c=getchar(),isdigit(c));
}
inline int find(int x){
return fa[x]==x?x:fa[x]=find(fa[x]);
}
inline void work(ll x){
if(!x)return;
work(x/10);
printf("%d",x%10);
}
inline void print(ll x){
if(x==0)putchar('0');
else work(x);
putchar('\n');
}
vec G[M];
map<int,int>mp[M];
ll ans[M];
int main(){
cin>>n;
for(int i=1;i^n;++i)
for(int j=0;j^3;++j)rd(Edge[i][j]);
for(int i=1;i<=n;++i)fa[i]=i,sz[i]=1,G[i].pb(i),mp[i][dis[i]=0]=1;
ll res=ans[n]=0;
for(int i=1;i^n;++i)rd(id[i]);
for(int i=n-1,a,b,c;i;--i){
a=Edge[id[i]][0],b=Edge[id[i]][1],c=Edge[id[i]][2];
int f1=find(a),f2=find(b);
if(sz[f1]<sz[f2])swap(a,b),swap(f1,f2);//sz[f2]<sz[f1]
int k=dis[b];
for(int j=0;j<G[f2].size();++j){
int to=G[f2][j];
((dis[to]^=k)^=c)^=dis[a];
if(mp[f1].find(dis[to])!=mp[f1].end())
res+=mp[f1][dis[to]];
G[f1].pb(to);
}
for(int j=0;j<G[f2].size();++j)
mp[f1][dis[G[f2][j]]]++;
G[f2].clear(),mp[f2].clear();
sz[f1]+=sz[f2],sz[f2]=0;
fa[f2]=f1;
ans[i]=res;
}
for(int i=1;i<=n;++i)
print(ans[i]);
return 0;
}
/**************************************************************
Problem: 1790
User: bblss123
Language: C++
Result: 正确
Time:672 ms
Memory:22324 kb
****************************************************************/