Topic link: https: //nanti.jisuanke.com/t/39277
Meaning of the questions: have given an edge weight of the tree, find all paths that contain simple XOR and simple path for the total number of 0's and.
Ideas:
First, the exclusive OR and val [I] XOR to zero on this limitation, we get all points to the root node through a path dfs, if the value val is equal to two nodes, with the path between them meet different or is zero. SZ [i] i in a subtree rooted size.
Secondly, to meet the XOR of 0 and two points u, v, two cases to consider:
1. u, v on a different chain, the contribution of this path is a sz [u] * sz [v], by the size of each record and map weights can be obtained. First of all we point this process again.
2. u, v on one strand, this contribution is a path (n-sz [u1]) * sz [v], u1 is the first child of v u u on this strand. Because the previous step we added all cases, it must first subtract sz [u] * sz [v], to record on the same or different chain of size and value val by mp1, because the record is the same chain, when the process all child nodes of a node to back the update, i.e. preceded by subtracting the size. After adding the Save (n-sz [u1]) * sz [v], the information is recorded by mp2, updated every processed back a child node, because the longer strand.
AC Code:
#include<cstdio> #include<algorithm> #include<unordered_map> using namespace std; const int maxn=1e5+5; const int MOD=1e9+7; typedef long long LL; typedef unordered_map<LL,LL> ump; struct node{ int v,nex; LL w; }edge[maxn]; int n,head[maxn],cnt,sz[maxn]; LL val[maxn],ans; ump sum,mp1,mp2; void adde(int u,int v,LL w){ edge[++cnt].v=v; edge[cnt].w=w; edge[cnt].nex=head[u]; head[u]=cnt; } void dfs1(int u,LL va){ val[u]=va,sz[u]=1; for(int i=head[u];i;i=edge[i].nex){ int v=edge[i].v; LL w=edge[i].w; dfs1(v,va^w); sz[u]+=sz[v]; } } void dfs2(int u){ ans=(ans+sum[val[u]]*sz[u])%MOD; sum[val[u]]=(sum[val[u]]+sz[u])%MOD; for(int i=head[u];i;i=edge[i].nex) dfs2(edge[i].v); } void dfs3(int u){ ans=(ans-mp1[val[u]]*sz[u]+mp2[val[u]]*sz[u]+MOD)%MOD; mp1[val[u]]=(mp1[val[u]]+sz[u])%MOD; for(int i=head[u];i;i=edge[i].nex){ int v=edge[i].v; LL w=edge[i].w; mp2[val[u]]=(mp2[val[u]]+n-sz[v]+MOD)%MOD; dfs3(v); mp2[val[u]]=(mp2[val[u]]-n+sz[v]+MOD)%MOD; } mp1[val[u]]=(mp1[val[u]]-sz[u]+MOD)%MOD; } int main(){ scanf("%d",&n); for(int i=2;i<=n;++i){ int u;LL w; scanf("%d%lld",&u,&w); adde(u,i,w); } dfs1(1,0); dfs2(1); dfs3(1); printf("%lld\n",ans); return 0; }