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

倍增LCA模板

时间:2017-11-10 23:14:07      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:ons   swap   static   blog   lca   add   ace   oid   struct   

第二弹

namespace Tree {
#define travel(x, i) for (int i = fir[x]; i; i = e[i].nxt) 
  static const int N = 1e5 + 5;
  
  struct edge {
    int nxt, to;
  } e[N << 1];
  int fir[N], cnt;
  int dep[N], fa[N][18];
  
  inline void add(int x, int y) {
    e[++ cnt] = (edge){fir[x], y};
    fir[x] = cnt;
  }
  inline void Dfs(int x, int p) {
    fa[x][0] = p;
    dep[x] = dep[p] + 1;
    for (int i = 1; i < 18; i ++)
      fa[x][i] = fa[fa[x][i - 1]][i - 1];
    travel(x, i)
      if (e[i].to != p) Dfs(e[i].to, p);
  }
  inline int LCA(int x, int y) {
    if (dep[x] < dep[y]) swap(x, y);
    for (int i = 17; i && dep[x] != dep[y]; i --)
      if (dep[fa[x][i]] >= dep[y]) x = fa[x][i];
    if (x == y) return x;
    for (int i = 17; i && fa[x][0] != fa[y][0]; i --)
      if (fa[x][i] != fa[y][i]) {
        x = fa[x][i];
        y = fa[y][i];
      }
    return fa[x][0];
  }
}

  

倍增LCA模板

标签:ons   swap   static   blog   lca   add   ace   oid   struct   

原文地址:http://www.cnblogs.com/the-unbeatable/p/7816608.html

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