//Place your snippets for cpp here. Each snippet is defined under a snippet name and has a prefix, body and 
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
// same ids are connected.
// prefix 的格式要求是 acm-[一级标题编号].[二级标题编号][该代码片段的英文简称]
// description 的格式要求是 "插入 [该代码片段的中文名]"

{
    "最近公共祖先LCA": {
        "prefix": "acm-4.3RMQ",
        "body": [
            "#include<algorithm>",
            "#include<cstring>",
            "#include<cstdio>",
            "#define LL long long",
            "#define Re register int",
            "using namespace std;",
            "const int N=5e5+3,logN=20;",
            "int n,m,o,x,y,T,rt,head[N];",
            "struct QAQ{int to,next;}a[N<<1];",
            "inline void add(Re x,Re y){a[++o].to=y,a[o].next=head[x],head[x]=o;}",
            "inline void in(Re &x){",
            "    int f=0;x=0;char c=getchar();",
            "    while(c<'0'||c>'9')f|=c=='-',c=getchar();",
            "    while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+(c^48),c=getchar();",
            "    x=f?-x:x;",
            "}",
            "struct LCA{",
            "\tint O,lg[N<<1],Qx[N<<1],Qd[N<<1],fir[N],deep[N],f[N<<1][23],ans[N<<1][23];",
            "\tinline void dfs(Re x,Re fa){",
            "\t\tQx[fir[x]=++O]=x,Qd[O]=deep[x]=deep[fa]+1;",
            "\t\tfor(Re i=head[x],to;i;i=a[i].next)",
            "\t\t\tif((to=a[i].to)!=fa)dfs(to,x),Qx[++O]=x,Qd[O]=deep[x];",
            "\t}",
            "\tinline void build(Re rt){",
            "\t\tdfs(rt,0),lg[0]=-1;",
            "\t\tfor(Re i=1;i<=O;++i)f[i][0]=Qd[i],ans[i][0]=Qx[i],lg[i]=lg[i>>1]+1;",
            "\t\tfor(Re j=1;j<=logN;++j)",
            "\t\t\tfor(Re i=1;i+(1<<j)-1<=O;++i)",
            "\t\t\t\tif(f[i][j-1]<f[i+(1<<j-1)][j-1])f[i][j]=f[i][j-1],ans[i][j]=ans[i][j-1];",
            "\t\t\t\telse f[i][j]=f[i+(1<<j-1)][j-1],ans[i][j]=ans[i+(1<<j-1)][j-1];",
            "\t}",
            "\tinline int lca(Re x,Re y){",
            "\t\tRe L=fir[x],R=fir[y];",
            "\t\tif(L>R)swap(L,R);",
            "\t\tRe m=lg[R-L+1];",
            "\t\treturn f[L][m]<f[R-(1<<m)+1][m]?ans[L][m]:ans[R-(1<<m)+1][m];",
            "\t}",
            "}T1;",
            "int main(){",
            "//\tfreopen(\"123.txt\",\"r\",stdin);",
            "\tin(n),in(T),in(rt),m=n-1;",
            "\twhile(m--)in(x),in(y),add(x,y),add(y,x);",
            "\tT1.build(rt);",
            "\twhile(T--)in(x),in(y),printf(\"%d\\n\",T1.lca(x,y));",
            "}",
            ""
        ],
        "description": "插入 最近公共祖先LCA"
    }
}