经典离线求lca[模板]

来源:互联网 发布:js判断滚动条是否存在 编辑:程序博客网 时间:2024/06/06 05:21
#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>#include <vector>#define maxn 600000#define maxm 1200000#define maxq 600000using namespace std;inline void read(int &x) {    char ch;    bool flag = false;    for (ch = getchar(); !isdigit(ch); ch = getchar())if (ch == '-') flag = true;    for (x = 0; isdigit(ch); x = x * 10 + ch - '0', ch = getchar());    x = flag ? -x : x;}inline void write(int x) {    static const int maxlen = 100;    static char s[maxlen];    if (x < 0) {   putchar('-'); x = -x;}    if (!x) { putchar('0'); return; }    int len = 0; for (; x; x /= 10) s[len++] = x % 10 + '0';    for (int i = len - 1; i >= 0; --i) putchar(s[i]);}int n,q;int root;int pre[maxm],now[maxn],son[maxm],tot;void build(int a,int b){pre[++tot]=now[a];now[a]=tot;son[tot]=b;}bool vis[maxn];int Fa[maxn];struct zy{vector<int> ed,id;}que[maxn];int ans[maxn];int get(int x){if (Fa[x]!=x)    return Fa[x]=get(Fa[x]);return x;}void dfs(int x,int fa){for (int p=now[x];p;p=pre[p])    if (son [p]!=fa)    {        dfs(son[p],x);        Fa[son[p]]=x;    }vis[x]=1;for (int i=0;i<que[x].ed.size();i++)    if (vis[  que[x].ed[i] ] )    {        ans[ que[x].id[i] ]=get(  que[x].ed[i] );        //printf("%d  %d\n",x,que[x].ed[i]);    }}int main(){    read(n); read(q); read(root);    for (int i=1;i<n;i++)    {        int a,b,c;        read(a); read(b);        build(a,b);        build(b,a);    }    for (int i=1;i<=q;i++)    {        int a,b;        read(a); read(b);        que[a].ed.push_back(b);        que[a].id.push_back(i);        que[b].ed.push_back(a);        que[b].id.push_back(i);    }    for (int i=1;i<=n;i++)        Fa[i]=i;    dfs(root,root);    for (int i=1;i<=q;i++)        printf("%d\n",ans[i]);    return 0;}