介绍一种解决最近公共祖先的在线算法,倍增,它是建立在任意整数的二进制拆分之上。

 

代码:

 

 //LCA:Doubly

 #include<cstdio>
#define swap(a,b) a^=b^=a^=b
#define maxn 500010
using namespace std; int n,m,s,tot,head[maxn],deep[maxn],p[maxn][];
struct node
{
int nxt,to;
}edge[maxn<<]; int read()
{
int x=,f=;
char c=getchar();
while (c<||c>)
f=c=='-'?-:,c=getchar();
while (c>=&&c<=)
x=(x<<)+(x<<)+(c^),c=getchar();
return x*f;
} void write(int x)
{
if (x<)
x=-x,putchar('-');
if (x>=)
write(x/);
putchar(x%+);
} void add(int a,int b)
{
edge[++tot]=(node){head[a],b};
head[a]=tot;
edge[++tot]=(node){head[b],a};
head[b]=tot;
} void init()
{
for (int j=;(<<j)<=n;j++)
for (int i=;i<=n;i++)
if (p[i][j-])
p[i][j]=p[p[i][j-]][j-];
} int dfs(int u)
{
for (int i=head[u];i;i=edge[i].nxt)
if (!deep[edge[i].to])
{
deep[edge[i].to]=deep[u]+;
p[edge[i].to][]=u;
dfs(edge[i].to);
}
} int LCA(int a,int b)
{
if (deep[a]<deep[b])
swap(a,b);
int i,j;
for (i=;(<<i)<=deep[a];i++);
i--;
for (j=i;j>=;j--)
if (deep[b]<=deep[a]-(<<j))
a=p[a][j];
if (a==b)
return a;
for (j=i;j>=;j--)
if (p[a][j]!=p[b][j]&&deep[p[a][j]]>=)
{
a=p[a][j];
b=p[b][j];
}
return p[a][];
} int main()
{
int i,j,k;
n=read(),m=read(),s=read();
for (i=;i<=n-;i++)
add(read(),read());
deep[s]=;
dfs(s);
init();
while (m--)
write(LCA(read(),read())),putchar();
return ;
}

最新文章

  1. Tensorflow 变量的共享
  2. Underscore-分析
  3. liunx 的 grep命令(转载)
  4. 再谈Bellman-Ford
  5. fail2ban 原理 安装 使用
  6. UVa247 Calling Circles
  7. RHEL6.2下挂载光驱安装软件
  8. LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation
  9. group by order by having
  10. hadoop2.2编程: Interation
  11. CI 笔记 datagrid的调用,不支持多页面多次调用js
  12. android应用的不同版本间兼容性处理
  13. 深入理解JVM(七)&mdash;&mdash;性能监控工具
  14. Java笔试题:给定一个ReadOnlyClass的对象roc,能否把这个对象的age值改成30?
  15. jQuery获取name相同被选中的多选框的值
  16. [Unit Test] Unit Test Brief Introduction
  17. [linux]如何更新Ubuntu的数据源
  18. .Net Standard 类库的创建和使用
  19. HTTP协议中TCP的三次握手 and HTTPS
  20. 配置pycharm 一键安装 requirements.txt,一键生成requirements.txt

热门文章

  1. android listview addheaderview viewpager
  2. PAT甲题题解-1036. Boys vs Girls (25)-找最大最小,大水题
  3. Navicat连接Mysql8.0失败:Client does not support authentication protocol requested by server...
  4. ns3的输入输出奥秘(一) LOGGING系统
  5. 80C51存储器与C51内存优化
  6. Parameter not found的出现的原因
  7. Cisco Packet Tracer 交换机 2950-24 配置
  8. 怎样实现在DBGrid中双击选择整行,并且可以多选?谢谢!!
  9. 【CF888E】Maximum Subsequence(meet in the middle)
  10. 洛谷 P2146 [NOI2015]软件包管理器 解题报告