Learn the Ben of this god: http://blog.csdn.net/jiangyuze831/article/details/41476865
Attention:
① sort when the first keyword is the block number of the left endpoint (block tree), the second keyword is the right endpoint DFS sequence.
The current chain maintained by ② cannot include LCA (L,R), but the final calculation of the answer to LCA (L,R).
③ l->l '/r->r ' can not take anti-LCA (l,l ')/lca (R,r ').
#include <cstdio> #include <cmath> #include <algorithm>using namespace std; #define N 50001#define M 100001int n,m;int First[n],en,next[n<<1],dfsn[n],v[n<<1],fa[n],bel[n],dep[n],siz[n],cnt,top[n];int x, Y,root,sz,col[n],time[n],ans,anss[m];bool vis[n];struct ask{int l,r,a,b,id;void Read () {scanf ("%d%d%d%d", &l, &r,&a,&b);}} Q[m];bool operator < (const ask &a,const ask &b) {return BEL[A.L]!=BEL[B.L]? BEL[A.L]<BEL[B.L]: DFSN[A.R]&L T;DFSN[B.R];} void Addedge (const int &u,const int &v) {v[++en]=v;next[en]=first[u];first[u]=en;} void dfs (int cur) {dfsn[cur]=++cnt;for (int i=first[cur];i;i=next[i]) if (V[i]!=fa[cur]) {dep[v[i]]=dep[cur]+1; Fa[v[i]]=cur; DFS (V[i]); }}void makeblock (int cur) {for (int i=first[cur];i;i=next[i]) if (V[i]!=fa[cur]) {if (siz[bel[cur]]& LT;SZ) {++siz[bel[cur]]; Bel[v[i]]=bel[cur]; Top[v[i]]=top[cur]; } Makeblock (V[i]); }}int Qlca (int u,int V) {while (u!=v) {if (Top[u]==top[v]) {if (Dep[u]<dep[v]) swap ( U,V); U=fa[u]; } else {if (Dep[top[u]]<dep[top[v]]) swap (U,V); U=fa[top[u]]; }} return U;} void update (const int &COL,CONST int &op) {time[col]+=op;if (! Time[col])--ans;else if (time[col]==1&&op==1) ++ans;} void work (Int. U,int V,int LCA) {while (U!=LCA) {vis[u]^=1; Update (COL[U],VIS[U]?1:-1); U=fa[u]; }while (V!=LCA) {vis[v]^=1; Update (COL[V],VIS[V]?1:-1); V=FA[V]; }} void Solve (const int &p) {int Lca=qlca (Q[P].L,Q[P].R); if (p==1) work (Q[P].L,Q[P].R,LCA); else {work (Q[P-1].L,Q[P].L,QLCA (Q[P-1].L,Q[P].L)); Work (Q[p-1].r,q[p].r,qlca (Q[P-1].R,Q[P].R)); } update (col[lca],1); Anss[q[p].id]=ans; if (q[p].a!=q[p].b) anss[q[p].id]-= (time[q[p].a]&&time[q[p].b]); Update (COL[LCA],-1);} int main () {scanf ("%d%d", &n,&m), for (int i=1;i<=n;++i) scanf ("%d", &col[i]), and for (int i=1;i<=n;++i) { scanf ("%d%d", &x,&y); if (!x) root=y; else if (!y) root=x; else {Addedge (x, y); Addedge (Y,X); }}dfs (root); for (int i=1;i<=n;i++) {siz[bel[i]=dfsn[i]]=1; Top[i]=i; }sz= ((int) sqrt (n)) <<1) Makeblock (root); for (int i=1;i<=m;++i) q[i]. Read (), Q[i].id=i;sort (q+1,q+m+1), for (Int. i=1;i<=m;++i) Solve (i); for (int i=1;i<=m;++i) printf ("%d\n", Anss[i]) ; return 0;}
"Mo Team" bzoj3757 apple tree in the tree