【題解】CSES 1136 Counting Paths

【題目敘述】https://cses.fi/problemset/task/1136/

#include <iostream>
#include <vector>
using namespace std;
 
int n, q, a, b, p[200005][20], d[200005], dp[200005];
vector <int> v[200005];
 
void dfs(int x, int pre){
    for (auto i:v[x]){
        if (i == pre) continue;
        p[i][0] = x;
        d[i] = d[x]+1;
        dfs(i, x);
    }
}
int lca(int a, int b){
    int x = d[a], y = d[b];
    if (x > y){
        swap(a, b);
        swap(x, y);
    }
    y -= x;
    for (int i = 0; i < 20; i++){
        if (y & (1<<i)){
            b = p[b][i];
        }
    }
    if (a == b) return a;
    for (int i = 19; i >= 0; i--){
        if (p[a][i] != p[b][i]){
            a = p[a][i];
            b = p[b][i];
        }
    }
    return p[a][0];
}
void dfs2(int x, int pre){
    for (auto i:v[x]){
        if (i == pre) continue;
        dfs2(i, x);
        dp[x] += dp[i];
    }
}
int main() {
    cin >> n >> q;
    for (int i = 2; i <= n; i++){
        cin >> a >> b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    dfs(1, 0);
    for (int i = 1; i < 20; i++){
        for (int j = 1; j <= n; j++){
            p[j][i] = p[p[j][i-1]][i-1];
        }
    }
    while (q--){
        cin >> a >> b;
        dp[a]++;
        dp[b]++;
        dp[p[lca(a, b)][0]]--;
        dp[lca(a, b)]--;
    }
    dfs2(1, 0);
    for (int i = 1; i <= n; i++){
        cout << dp[i] << " ";
    }
}
分享本文 Share with friends