木牛流馬

追梦之鲸發表於2024-06-02
#include <bits/stdc++.h>
using namespace std;
#define pii pair<int, int>
#define fr first
#define se second
#define pbk push_back
#define mpr make_pair
#define ll long long
#define ull unsigned long long
#define re return
#define con continue
#define brk break
#define il inline
#define pt putchar
#define out printf
#define io scanf
#define big(a, b) (a = max(a, b))
#define sml(a, b) (a = min(a, b))
#define rep(i, j, n) for (int i = (j); i <= (n); i ++)
#define per(i, j, n) for (int i = (j); i >= (n); i --)
#define rp(i, n) rep(i, 1, n)
#define pr(i, n) per(i, n, 1)
#define err() cout<<"\nerr "<<__LINE__<<"\n",exit(0)
#define debug(x, args...) (#x)
#define adebug(x, args...) (#x)
#define odebug(x, args...) (#x)
#define dg(args...) fRnT(#args),cout<<"  Line "<<__LINE__<<"\t: ",bHnD(args),cout<<"\n"
#define adg(x, args...) fRnT(#x),cout<<"  Line "<<__LINE__<<"\t: ",bHnD(args),cout<<"\n"
#define odg(x, l, r) fRnT(#x),cout<<"  Line "<<__LINE__<<"\t: ",PRY(x, l, r),cout<<"\n"
inline void bHnD(){}
template<typename T,typename... Ts> inline void bHnD(const T& x,const Ts&... y){cout<<x<<' ';bHnD(y...);}
inline void fRnT(string nam){cout<<"\n"<<setw(49)<<nam;}
template<typename PRY_Type> void PRY(PRY_Type *a, int l, int r) {cout<<l<<"~"<<r<< ": ";rep(i,l,r)cout<<*(a+i)<<' ';}
const int N = 5e5 + 233;
const int M = 1e6 + 233;
const int K = 21; // * 1e6

vector<int> e[N];
int dfn[N], nfd[N];
int lg[M];
int ast[K][M], an;
int n, q, s;

il void ST() {
	int r;
	rp(k, 20) {
		rp(l, n) {
			if ((l + (1 << k) - 1) > n)
				brk;
			ast[k][l] = max(ast[k - 1][l], ast[k - 1][l + (1 << (k - 1))]);
		}
	}
	re;
}
il void dfs(int nw) {
	ast[0][++ an] = nw;
	re;
}

signed main() {
	// cout << (ll)(1<<23);
	lg[0] = -1;
	cin >> n >> q >> s;
	int u, v, k;
	rep(i, 2, n) {
		io("%d%d", &u, &v);
		e[u].pbk(v);
		e[v].pbk(u);
	}
	dfs(s);
	rp(i, an) {
		lg[i] = lg[i >> 1] + 1;
	}
	// rp(i, n) {
	// 	io("%d", &ast[0][i]);
	// }
	ST();
	rp(i, q) {
		io("%d%d", &u, &v);
		k = lg[v - u + 1];
		out("%d\n", max(ast[k][u], ast[k][v - (1 << k) + 1]));
	}
	return 0;
}

相關文章