Submission #1354961

#TimeUsernameProblemLanguageResultExecution timeMemory
1354961kantaponzValley (BOI19_valley)C++20
100 / 100
101 ms45684 KiB
#include <bits/stdc++.h>
using namespace std;

#define ll long long

const int nx = 1e5 + 5;
const ll maxDist = (1000000000LL) * (1e5);

int n, s, q, e;
vector<pair<int,ll>> adj[nx];
int u[nx], v[nx];
int tin[nx], tout[nx], timer = 0;
int depth[nx], pa[nx];
ll dist[nx], best[nx], opt[nx];
ll dp[nx][18];
ll dp2[nx][18];

void dfs(int u) {
    tin[u] = timer++;
    for (auto [v, w] : adj[u]) {
        if (pa[u] == v) continue;
        dist[v] = dist[u] + w;
        depth[v] = depth[u] + 1;
        pa[v] = u;
        dfs(v);
    }
    tout[u] = timer++;
}

ll solve(int u) {
    ll ans = 1e18;
    for (auto [v, w] : adj[u]) {
        if (pa[u] == v) continue;
        ans = min(ans, solve(v) + w);
    }
    return best[u] = min(best[u], ans);
}

ll query(int u, int k) {
    if (k == 0) return opt[u];
    ll ans = 1e18;
    for (int i = 0; (1 << i) <= k; i++) {
        if ((1 << i) & k) {
            ans = min(ans, dp2[u][i]);
            u = dp[u][i];
        }
    }
    return ans;
}

int main() {
    ios_base::sync_with_stdio(0), cin.tie(0);
    cin >> n >> s >> q >> e;
    pa[e] = e;
    for (int i = 1; i <= n - 1; i++) {
        cin >> u[i] >> v[i];
        int w;
        cin >> w;
        adj[u[i]].emplace_back(v[i], w);
        adj[v[i]].emplace_back(u[i], w);
    }
    for (int i = 1; i <= n; i++) best[i] = dist[i] = 1e18;
    dist[e] = 0;
    while (s--) {
        int c; cin >> c;
        best[c] = 0;
    }
    dfs(e);
    solve(e);
    for (int i = 1; i <= n; i++) opt[i] = best[i] - dist[i];
    for (int u = 1; u <= n; u++) {
        dp[u][0] = pa[u];
        dp2[u][0] = min(opt[u], opt[pa[u]]);
    }
    for (int k = 1; (1 << k) <= n; k++) {
        for (int u = 1; u <= n; u++) {
            dp[u][k] = dp[dp[u][k-1]][k-1];
        }
        for (int u = 1; u <= n; u++) {
            dp2[u][k] = min(dp2[u][k-1], dp2[dp[u][k-1]][k-1]);
        }
    }


    while (q--) {
        int i, k;
        cin >> i >> k;
        int root;
        if (depth[u[i]] < depth[v[i]]) root = v[i];
        else root = u[i];
        //printf("%d %d\n", root, k);
        if (!(tin[root] <= tin[k] && tin[k] <= tout[root])) {
            cout << "escaped\n";
            continue;
        }
        ll ans = dist[k] + query(k, depth[k] - depth[root]);
        //printf("ans = %lld + %lld = %lld\n", dist[k] + query(k, depth[k] - depth[root]), ans);
        if (ans > maxDist) cout << "oo\n";
        else cout << ans << "\n";
    }

}

/*
5 2 3 1
1 2 3
1 3 2
3 4 1
3 5 2
2
4
2 2
2 5
4 5

*/
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...