HDU5416
题解:我们先预处理每个节点i到根节点1的路径上异或值d[i],然后我们发现两个节点i,j的路径上边权的异或值为d[i]^d[j],因为他们俩距离根节点重复的部分可以异或成0
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
const LL maxn=1e6+10;
LL n,q;
struct node{
LL to;
LL w;
};
vector<node> G[maxn];
LL mp[maxn];
LL d[maxn];
void init()
{
for(LL i=0;i<=n;i++){
G[i].clear();
}
for(LL i=0;i<maxn-5;i++){
mp[i]=0;
}
}
void dfs(LL u,LL fa,LL pre)
{
d[u]=pre;
mp[pre]++;
LL len=G[u].size();
for(LL i=0;i<len;i++){
LL to=G[u][i].to;
if(to==fa)continue;
LL cap=G[u][i].w;
dfs(to,u,pre^cap);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
scanf("%lld",&n);
init();
for(LL i=1;i<=n-1;i++){
LL s,e;
LL w;
scanf("%lld%lld%lld",&s,&e,&w);
node pre;
pre.to=e;
pre.w=w;
G[s].push_back(pre);
pre.to=s;
pre.w=w;
G[e].push_back(pre);
}
dfs(1,0,0);
scanf("%lld",&q);
while(q--){
LL s;
scanf("%lld",&s);
LL res=0;
for(LL i=1;i<=n;i++){
LL pre=(d[i]^s);
LL num=mp[pre];
if(pre==d[i]){
num--;
}
res+=num;
}
res/=2;
if(s==0){
res+=n;
}
printf("%lld\n",res);
}
}
return 0;
}