#include<bits/stdc++.h>
using namespace std;
int n, st[21][1000001], mylog[1000001], m, l, r, tmp, root, now, head[500001], t1, t2, pos[21][1000001], preorder[1000001], n2, first[500001], key;
//st[j][i] is the max value of from a[i] to a[i+(1<<j)-1] (2^j elements in total)
//st[0][i] is depth of preorder[i]
struct edge {
int x, nxt;
} e[1000001], t;
inline int readint(){
int x=0,f=1;
char ch=getchar();
while (ch<'0'||ch>'9'){
if (ch=='-') f=-1;
ch=getchar();
}
while (ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
return x*f;
}
void adde(int a, int b) {
++now;
e[now].x = b;
e[now].nxt = head[a];
head[a] = now;
}
void dfs(int p, int d) {
++now;
first[p] = now;
preorder[now] = p;
st[0][now] = d;
pos[0][now] = now;
t1= e[head[p]].x;
t2= e[head[p]].nxt;
for (int i = head[p]; e[i].x > 0; i = e[i].nxt) {
t1= e[i].x;
t2= e[i].nxt;
if (first[t1] == 0) {
dfs(t1, d + 1);
++now;
preorder[now] = p;
st[0][now] = d;
pos[0][now] = now;
}
}
}
int main() {
n=readint();
m=readint();
root=readint();
for (int i = 1; i < n; ++i) {
t1=readint();
t2=readint();
adde(t1, t2);
adde(t2, t1);
}
now = 0;dfs(root, 1);
for (int i = 2; i <= now; ++i) mylog[i] = mylog[i / 2] + 1;
n2 = mylog[now];
for (int i = 1; i <= n2; ++i)
for (int j = 1; j <= now; ++j)
if (j + (1 << i) - 1 <= now) {
st[i][j] = min(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
pos[i][j] = (st[i - 1][j] < st[i - 1][j + (1 << (i - 1))] ? pos[i - 1][j] : pos[i - 1][j + (1 << (i - 1))]);
}
//两重循环和二维数组下标位置还是顺着位置对应起来比较好,逆着来运行时间大概会翻倍
for (int i = 1; i <= m; ++i) {
t1=readint();
t2=readint();
r = max(first[t1], first[t2]);
l = min(first[t1], first[t2]);
tmp = mylog[r - l + 1];
key = (st[tmp][l] < st[tmp][r - (1 << tmp) + 1] ? pos[tmp][l] : pos[tmp][r - (1 << tmp) + 1]);
printf("%d\n", preorder[key]);
}
return 0;
}
没有合适的资源?快使用搜索试试~ 我知道了~
St表欧拉序倍增搞LCA.zip_LCA_lca st表_st表
共1个文件
cpp:1个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 10 浏览量
2022-09-25
00:14:13
上传
评论
收藏 1KB ZIP 举报
温馨提示
用St表实现对最近公共祖先LCA的运算与查询
资源推荐
资源详情
资源评论
收起资源包目录
St表欧拉序倍增搞LCA.zip (1个子文件)
St表欧拉序倍增搞LCA.cpp 2KB
共 1 条
- 1
资源评论
小波思基
- 粉丝: 70
- 资源: 1万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功