HDU 5416 CRB and Tree (dfs+ prefix and)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.