【模板】 倍增lca

虽然很基础,但是还是复习了一下,毕竟比树剖好写。。。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<ctime>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
#define duke(i,a,n) for(int i = a;i <= n;i++)
#define lv(i,a,n) for(int i = a;i >= n;i--)
#define clean(a) memset(a,0,sizeof(a))
const int INF = 1 << 30;
const int N = 300005;
typedef long long ll;
typedef double db;
template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-') op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op) x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0) putchar('-'), x = -x;
    if(x >= 10) write(x / 10);
    putchar('0' + x % 10);
}
struct node
{
    int l,r,nxt;
}a[1001000];
int n,m,s;
int lst[500100],len = 0;
void add(int x,int y)
{
    a[++len].l = x;
    a[len].r = y;
    a[len].nxt = lst[x];
    lst[x] = len;
}
int st[500010][32];
int dep[500010];
void dfs(int u,int fa,int depth)
{
    dep[u] = depth;
    st[u][0] = fa;
    for(int i = 1;(1 << i) <= dep[u];i++)
    {
        st[u][i] = st[st[u][i - 1]][i - 1];
    }
    for(int k = lst[u];k;k = a[k].nxt)
    {
        int y = a[k].r;
        if(y == fa) continue;
        dfs(y,u,depth + 1);
    }
}
int lca(int x,int y)
{
    if(dep[x] > dep[y])
    swap(x,y);
    int ch = dep[y] - dep[x];
    duke(i,0,29)
    {
        if(ch & (1 << i))
        y = st[y][i];
    }
    if(x == y)
    return x;
    lv(i,29,0)
    {
        if(st[x][i] != st[y][i])
        {
            x = st[x][i];
            y = st[y][i];
        }
    }
    x = st[x][0];
    return x;
}
int main()
{
    read(n);read(m);read(s);
    duke(i,1,n - 1)
    {
        int x,y;
        read(x);read(y);
        add(x,y);
        add(y,x);
    }
    dfs(s,0,0);
    int g,h;
    duke(i,1,m)
    {
        read(g);read(h);
        printf("%d\n",lca(g,h));
    }
    return 0;
}

 

posted @ 2018-10-05 21:51  DukeLv  阅读(136)  评论(0编辑  收藏  举报