Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <cstring>
- #include <algorithm>
- #include <cmath>
- #include <vector>
- #include <set>
- #include <map>
- #include <stack>
- #include <queue>
- #include <deque>
- #include <unordered_map>
- #include <numeric>
- #include <iomanip>
- using namespace std;
- #define pii pair<long long, long long>
- #define ll long long
- #define FAST ios_base::sync_with_stdio(false); cin.tie(NULL)
- const long long dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
- const long long dl[2] = {1, -1};
- const long long MOD = 1000000007;
- const long long MAXN = 50005;
- int N, M;
- vector<int> adj[MAXN];
- int par[MAXN][22];
- int depth[MAXN];
- void make_tree(int c, int p, int d){
- depth[c] = d;
- par[c][0] = p;
- for(auto x : adj[c]){
- if(x != p){
- make_tree(x, c, d + 1);
- }
- }
- }
- int main() {
- FAST;
- cin >> N;
- for(int x, y, i = 0; i < N - 1; i++){
- cin >> x >> y;
- adj[x].push_back(y);
- adj[y].push_back(x);
- }
- make_tree(1, 0, 0);
- for(int j = 1; j <= 20; j++){
- for(int i = 2; i <= N; i++){
- par[i][j] = par[par[i][j - 1]][j - 1];
- }
- }
- cin >> M;
- for(int x, y, i = 0; i < M; i++){
- cin >> x >> y;
- if(depth[x] < depth[y]){
- swap(x, y);
- }
- if(depth[x] != depth[y]){
- int tmp = depth[x] - depth[y];
- for(int j = 0; j <= 20; j++){
- if((tmp & (1 << j)) != 0){
- x = par[x][j];
- }
- }
- }
- // depth[x] = depth[y]
- if(x == y){
- cout << y << "\n";
- continue;
- }
- for(int j = 20; j >= 0; j--){
- int xx = par[x][j];
- int yy = par[y][j];
- if(xx != yy){
- x = xx;
- y = yy;
- }
- }
- cout << par[x][0] << "\n";
- }
- }
- /*
- 15
- 1 2
- 1 3
- 2 4
- 3 7
- 6 2
- 3 8
- 4 9
- 2 5
- 5 11
- 7 13
- 10 4
- 11 15
- 12 5
- 14 7
- 6
- 6 11
- 10 9
- 2 6
- 7 6
- 8 13
- 8 15
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement