码迷,mamicode.com
首页 > 其他好文 > 详细

【模板】 倍增lca

时间:2018-10-05 22:34:28      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:||   define   class   void   ons   queue   code   put   name   

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

代码:

#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;
}

 

【模板】 倍增lca

标签:||   define   class   void   ons   queue   code   put   name   

原文地址:https://www.cnblogs.com/DukeLv/p/9746030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!