Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #define f first
- #define s second
- #define pb push_back
- using namespace std;
- const int MAXN = 2e5 + 10;
- const int INF = 1e9 + 7;
- bool was[MAXN];
- vector <pair <int, int> > g[MAXN];
- int up[MAXN][23];
- int minn[MAXN][23];
- int maxx[MAXN][23];
- int tin[MAXN], tout[MAXN], l;
- bool upper(int a, int b){
- return (tin[a] <= tin[b] && tout[a] >= tout[b]);
- }
- int timer = 0;
- void dfs(int x, int len, int p = 0){
- was[x] = 1;
- tin[x] = ++timer;
- up[x][0] = p;
- for (int i = 1; i <= l; i++){
- up[x][i] = up[up[x][i - 1]][i - 1];
- }
- minn[x][0] = len;
- for (int i = 1; i <= l; i++){
- minn[x][i] = min(minn[x][i - 1],
- minn[up[x][i - 1]][i - 1]);
- }
- if (x == 1)
- maxx[x][0] = -INF;
- else
- maxx[x][0] = len;
- for (int i = 1; i <= l; i++){
- maxx[x][i] = max(maxx[x][i - 1],
- maxx[up[x][i - 1]][i - 1]);
- }
- for (int i = 0; i < g[x].size(); i++){
- int to = g[x][i].f;
- int len = g[x][i].s;
- if (!was[to]){
- dfs(to, len, x);
- }
- }
- tout[x] = ++timer;
- }
- pair <int, pair <int, int> > lca(int a, int b){
- int mn = INF;
- int mx = -INF;
- int my_lca = 0;
- if (upper(a, b))
- my_lca = a;
- if (upper(b, a))
- my_lca = b;
- for (int i = l; i >= 0; i--){
- if (!upper(up[a][i], b)){
- mn = min(mn, minn[a][i]);
- mx = max(mx, maxx[a][i]);
- a = up[a][i];
- }
- if (!upper(up[b][i], a)){
- mn = min(mn, minn[b][i]);
- mx = max(mx, maxx[b][i]);
- b = up[b][i];
- }
- //cout << "! " << a << ' ' << (1 << i) << ' ' << mn << '\n';
- }
- if (!upper(a, b)){
- mn = min(mn, minn[a][0]);
- mx = max(mx, maxx[a][0]);
- my_lca = up[a][0];
- }
- if (!upper(b, a)){
- mn = min(mn, minn[b][0]);
- mx = max(mx, maxx[b][0]);
- my_lca = up[b][0];
- }
- return {my_lca, {mn, mx}};
- }
- void solve(){
- tout[0] = INF;
- int n;
- cin >> n;
- l = 0;
- while ((1 << l) <= n){
- l++;
- }
- for (int i = 0; i < n - 1; i++){
- int x, y, cost;
- cin >> x >> y >> cost;
- g[x].pb({y, cost});
- g[y].pb({x, cost});
- }
- dfs(1, INF, 0);
- int q;
- cin >> q;
- while(q--){
- int x, y;
- cin >> x >> y;
- pair <int, pair <int, int> > z = lca(x, y);
- cout << z.s.f << ' ' << z.s.s << "\n";
- }
- }
- int main() {
- ios::sync_with_stdio(0);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int ttt = 1;
- //cin >> ttt;
- while (ttt--){
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment