Test instructions
There are n points in a tree, n-1, and each edge has a weight.
Make f ( u , V ) equals the prefix and on the path of U to v.
Now I'm going to ask you Q. q <= 10 )
Ask F(u,v)=s Number of paths.
Analytical:
Because q is small, it can be done directly using O (n) complexity algorithm.
What is the XOR of the root node to u, first with Sum[u]?
Save with a hash map, Sum[u] How many times have you seen it?
Every time you query the hash map, s ^ s u m [ u How many times has it occurred.
The sum of the queries divided by 2 is the final result.
Attention:
If s=0 When f ( u , U ) Also satisfies the condition, so we have to add N.
my code
#include <cstdio>#include <cstring>#include <algorithm>#include <vector>#define PB Push_backusing namespace STD;typedef Long LongllConst intMAXN = (int)2e5+Ten;structEdge {intU, V, Val; Edge () {} Edge (intUintVintval): U (U), V (v), Val (val) {}};intMP[MAXN], SUM[MAXN]; vector<Edge>G[MAXN];intN, Q;voidInit () {memset(MP,0,sizeof(MP)); for(inti =1; I <= N; i++) {g[i].clear (); }}voidAddedge (intUintVintval) {G[U].PB (Edge (U, V, Val));}voidDfsintUintPreintval) {Sum[u] = val; for(inti =0; I < g[u].size (); i++) {intv = g[u][i].v;if(pre = = v)Continue; DFS (V, u, val^g[u][i].val); }}ll Cal (ints) {LL ret =0; for(inti =1; I <= N; i++) {ret + = mp[s^sum[i]]; }if(s = =0) ret + = n;returnRET/2;}intMain () {intTscanf("%d", &t);intU, V, Val, S; while(t--) {scanf("%d", &n); Init (); for(inti =1; I < n; i++) {scanf("%d%d%d", &u, &v, &val); Addedge (U, V, Val); Addedge (V, U, Val); } DFS (1, -1,0); for(inti =1; I <= N; i++) {mp[sum[i]]++; }scanf("%d", &q); while(q--) {scanf("%d", &s);printf("%lld\n", Cal (s)); } }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 5416 CRB and Tree (dfs+ prefix and)