Title Address: POJ 1470
LCA Template questions: The input is a bit of a pit, and the first node of the input is not necessarily the root.
The code is as follows:
#include <iostream>#include <string.h>#include <math.h>#include <queue>#include <algorithm>#include <stdlib.h>#include <map>#include <set>#include <stdio.h>using namespace Std;#define LL __int64#define PI ACOs ( -1.0)ConstintMod=1e9+7; constintinf=0x3f3f3f3f; Const DOUBLE Eqs=1E-9; constintmaxn= ++Ten;intf[maxn<<1], FIR[MAXN], RMQ[maxn<<1], ANS[MAXN], DEG[MAXN];intHEAD[MAXN], CNT, tot;struct node {intU, V,Next;} edge[maxn<<1];void Add (intUintV) {edge[cnt].v=v; EDGE[CNT].Next=head[u]; head[u]=cnt++;} void Dfs (intUintFaintDEP) {f[++tot]=u; Fir[u]=tot; RmQ[tot]=DEP; for(intI=head[u]; i!=-1; I=edge[i].Next) {intV=EDGE[I].V;if(V==FA)Continue; DFS (v,u,dep+1); F[++tot]=u; RmQ[tot]=DEP; }}struct ST {intdp[maxn<<1][ -], I, J; void Init () { for(i=1; i<=tot; i++) {dp[i][0]=i; } for(j=1; (1<<J) <=tot; J + +) { for(i=1; I<=tot-(1<<j-1)+1; i++) {DP[I][J]=RMQ[dp[i][J-1]]<rmq[dp[i+ (1<<j-1)][J-1]]?dp[i][j-1]:d p[i+ (1<<j-1)][j-1]; } } }intQuery (intLintR) {if(r<l) swap (L,R);intk=0; while((1<<k+1) <=r-l+1) k++;returnRmQ[dp[l][K]] <rmq[dp[r+1-(1<<k)][K]]? Dp[l][k]:d p[r+1-(1<<k)][k]; }} st;void init () {memset (head,-1, sizeof (head)); memset (ans,0, sizeof (ans)); memset (deg,0, sizeof (deg)); cnt=tot=0;}intMain () {intNm, I, J, u, V, TMP; while(SCANF ("%d", &n)!=eof) {init (); for(i=0; i<n; i++) {scanf ("%d", &u); scanf":(%d)",&m); while(m--) {scanf ("%d", &v); Add (U,V); Add (V,u); deg[v]++; } } for(i=1; i<=n; i++) {if(!deg[i]) {DFS (i,-1,0); Break; }} st.init (); scanf"%d",&m); while(m--) {char c=getchar (); while(c!=' (') {C=getchar (); } scanf ("%d %d)", &u,&v); Ans[f[st. Query (Fir[u],fir[v])]]++; } for(i=1; i<=n; i++) {if(Ans[i]) {printf("%d:%d\ n", I,ans[i]); } } }return 0;}
POJ 1470 Closest Common ancestors (online LCA transfer RMQ)