HDU 5266 pog loves szh III
  bT2kse65LKjH 2023年11月02日 100 0


Problem Description



Pog and Szh are playing games. Firstly Pog draw a tree on the paper. Here we define 1 as the root of the tree. Then Szh choose some nodes from the tree. He wants Pog helps to find the least common ancestor(LCA) of these node. The question is too difficult for Pog. So he decided to simplify the problems. The nodes picked are consecutive numbers from li to ri ([li,ri]).

Hint : You should be careful about stack overflow !


Input



Several groups of data (no more than 3 groups,n≥10000 or Q≥10000).

The following line contains ans integers,n(2≤n≤300000).

AT The following n−1 line, two integers are bi and ci at every line, it shows an edge connecting bi and ci.

The following line contains ans integers,Q(Q≤300000).

AT The following Q line contains two integers li and ri(1≤li≤ri≤n).


Output



For each case,output Q integers means the LCA of [li,ri].


Sample Input



5 1 2 1 3 3 4 4 5 5 1 2 2 3 3 4 3 5 1 5


Sample Output



1 1 3 3 1

Hint


Be careful about stack overflow.


lca+rmq

#include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>
#include<queue>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<string>
using namespace std;
const int maxn = 300005;
int n, m, x, y, lc[maxn][20], dp[maxn][20], deep[maxn];
vector<int> t[maxn];

void bfs()
{
queue<int> p;
p.push(1); deep[1] = 1;
while (!p.empty())
{
int q = p.front(); p.pop();
for (int i = 0; i < t[q].size(); i++)
if (t[q][i] != lc[q][0])
{
lc[t[q][i]][0] = q;
deep[t[q][i]] = deep[q] + 1;
p.push(t[q][i]);
}
}
}

int lca(int a, int b)
{
int i, j;
if (deep[a]<deep[b]) swap(a, b);
for (i = 0; (1 << i) <= deep[a]; i++);
i--;
for (j = i; j >= 0; j--)
if (deep[a] - (1 << j) >= deep[b])
a = lc[a][j];
if (a == b)return a;
for (j = i; j >= 0; j--)
{
if (lc[a][j] != -1 && lc[a][j] != lc[b][j])
{
a = lc[a][j];
b = lc[b][j];
}
}
return lc[a][0];
}

int query(int s, int v)
{
int k = (int)(log((v - s + 1)*1.0) / log(2.0));
return lca(dp[s][k], dp[v - (1 << k) + 1][k]);
}

int main()
{
while (cin >> n)
{
memset(dp, -1, sizeof(dp));
memset(lc, -1, sizeof(lc));
for (int i = 1; i <= n; i++)
{
t[i].clear();
dp[i][0] = i;
deep[i] = 0;
}
for (int i = 1; i < n; i++)
{
scanf("%d%d", &x, &y);
t[x].push_back(y);
t[y].push_back(x);
}
bfs();

for (int j = 1; (1 << j) <= n; j++)
for (int i = 1; i <= n; i++)
if (lc[i][j - 1] != -1) lc[i][j] = lc[lc[i][j - 1]][j - 1];

for (int j = 1; (1 << j) <= n; j++)
for (int i = 1; i <= n; i++)
if (i + (1 << j) - 1 <= n)
{
dp[i][j] = lca(dp[i][j - 1], dp[i + (1 << (j - 1))][j - 1]);
}

cin >> m;
while (m--)
{
scanf("%d%d", &x, &y);
printf("%d\n", query(x, y));
}
}
}



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论