CRB and Tree
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1995 Accepted Submission(s): 614
Problem Description
CRB has a tree, whose vertices are labeled by 1, 2, …, N. They are connected by N – 1 edges. Each edge has a weight.
For any two vertices u and v(possibly equal), f(u,v) is xor(exclusive-or) sum of weights of all edges on the path from u to v.
CRB’s task is for given s, to calculate the number of unordered pairs (u,v) such that f(u,v) = s. Can you help him?
Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains an integer N denoting the number of vertices.
Each of the next N - 1 lines contains three space separated integers a, b and c denoting an edge between a and b, whose weight is c.
The next line contains an integer Q denoting the number of queries.
Each of the next Q lines contains a single integer s.
1 ≤ T ≤ 25
1 ≤ N ≤ 105
1 ≤ Q ≤ 10
1 ≤ a, b ≤ N
0 ≤ c, s ≤ 105
It is guaranteed that given edges form a tree.
Output
For each query, output one line containing the answer.
Sample Input
1
3
1 2 1
2 3 2
3
2
3
4
Sample Output
1
1
0
Hint
For the first query, (2, 3) is the only pair that f(u, v) = 2.
For the second query, (1, 3) is the only one.
For the third query, there are no pair (u, v) such that f(u, v) = 4.
Author
KUT(DPRK)
Source
2015 Multi-University Training Contest 10
Recommend
wange2014 | We have carefully selected several similar problems for you: 5831 5830 5829 5828 5827
不会做看了大神的分析:
http://blog.csdn.net/queuelovestack/article/details/47830959
用前向星存好图dfs瞎搞一下就行了。主要是要发现几个xor的性质
#include "cstring"
#include "iostream"
#include "string.h"
#define M 200005
#define N 200005
#define MAX 0x3f3f3f
using namespace std;
struct node
{
int next;
int to;
long long weight;
}edge[M];
int head[N],tot;
int cnt[M];
long long sum[M];
void init ()
{
memset (head, -1, sizeof(head));
memset (cnt,0,sizeof(cnt));
memset (sum,0,sizeof(sum));
tot =0;
}
void addedge (int from, int to,long long weight)
{
edge[tot].to = to;
edge[tot].next = head[from];
edge[tot].weight=weight;
head[from] = tot++;
}
void dfs(int u,int pre)
{
for(int i=head[u];~i;i=edge[i].next)
{
int v=edge[i].to;
if(v==pre)
continue;
sum[v]=sum[u]^edge[i].weight;
cnt[sum[v]]++;
dfs(v,u);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
init();
int n;
scanf("%d",&n);
int a,b;
long long c;
for(int i=1;i<=n-1;i++)
{
scanf("%d%d%lld",&a,&b,&c);
addedge(a,b,c);
addedge(b,a,c);
}
dfs(1,-1);
int q;
scanf("%d",&q);
while(q--)
{
long long s,total,ans,y;
total=ans=0;
scanf("%lld",&s);
if(s==0)
ans+=n;
for(int i=2;i<=n;i++)
{
if(s==sum[i])
ans++;
total+=cnt[y=sum[i]^s];
if(y==sum[i])
total--;
}
printf("%lld\n",total/2+ans);
}
}
return 0;
}