Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define FASTER() ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
- #define ff first
- #define ss second
- #define pb push_back
- #define all(a) a.begin(), a.end()
- #define dbg(x) cerr<<" "<<#x<<" "<<x<<endl
- typedef long long ll;
- using namespace std;
- struct edge {
- int to, cost;
- };
- int l = 1, t = 0;
- const int maxn = 5e4 + 228, inf = (int)1e7 + 1;
- vector <edge> gr[maxn];
- vector <int> tin, tout, h;
- vector <vector <int>> up, costUp;
- void dfs(int v, int par, int c, int dep) {
- tin[v] = t++;
- h[v] = dep;
- up[v][0] = par;
- costUp[v][0] = c;
- if(v == 0) {
- costUp[v][0] = inf;
- }
- for(int i = 1; i <= l; i++) {
- up[v][i] = up[up[v][i - 1]][i - 1];
- costUp[v][i] = min(costUp[v][i], costUp[up[v][i - 1]][i - 1]); //??
- }
- for(auto to : gr[v]) {
- if(to.to != par) {
- dfs(to.to, v, to.cost, dep + 1);
- }
- }
- tout[v] = t++;
- }
- bool is_upper(int a, int b) {
- return tin[a] <= tin[b] && tout[a] >= tout[b];
- }
- int lca(int a, int b) {
- if(h[a] < h[b]) {
- swap(a, b);
- }
- int ans = min(costUp[a][0], costUp[b][0]); //нужно ли?
- for(int i = l; i >= 0; i--) {
- if(h[a] > h[b] && h[up[a][i]] >= h[b]) { //поднимаем на одну высоту
- a = up[a][i];
- ans = min(ans, costUp[a][0]);
- }
- }
- for(int i = l; i >= 0; i--) {
- if(up[a][0] != up[b][0]) {
- ans = min(ans, min(costUp[up[a][i]][0], costUp[up[b][i]][0]));
- a = up[a][i];
- b = up[b][i];
- }
- }
- return ans;
- }
- int main() {
- FASTER();
- int n;
- cin >> n;
- tin.resize(n);
- tout.resize(n);
- h.resize(n);
- for(int i = 1; i < n; i++) {
- int u, w;
- cin >> u >> w;
- u--;
- gr[u].pb({i, w});
- gr[i].pb({u, w});
- }
- while((1 << l) <= n) {
- l++;
- }
- up.resize(n, vector <int>(l + 1));
- costUp.resize(n, vector <int>(l + 1, inf));
- dfs(0, 0, 0, 0);
- int m;
- cin >> m;
- for(auto a : costUp[3]) cout << a << " ";
- cout << endl;
- for(int i = 0; i < m; i++) {
- int a, b;
- cin >> a >> b;
- a--; b--;
- cout << lca(a, b) << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment