結果

問題 No.399 動的な領主
ユーザー milanis48663220milanis48663220
提出日時 2020-06-29 22:57:52
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,951 bytes
コンパイル時間 775 ms
コンパイル使用メモリ 85,924 KB
実行使用メモリ 18,032 KB
最終ジャッジ日時 2023-09-26 11:24:46
合計ジャッジ時間 2,825 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <queue>
#include <set>
#include <map>

using namespace std;
typedef long long ll;

const int N_MAX = 160000;
const int N_LOG_MAX = 25;
vector<int> G[N_MAX];
int root;

int parent[N_LOG_MAX][N_MAX];
int depth[N_MAX];

void dfs(int v, int p, int d){
    parent[0][v] = p;
    depth[v] = d;
    for(int i = 0; i < G[v].size(); i++){
        if(G[v][i] != p) dfs(G[v][i], v, d+1); 
    }
}

void init(int V){
    dfs(root, -1, 0);
    for(int i = 0; i < N_LOG_MAX-1; i++){
        for(int v = 0; v < V; v++){
            if(parent[i][v] < 0) parent[i+1][v] = -1;
            else parent[i+1][v] = parent[i][parent[i][v]];
        }
    }
}

int lca(int u, int v){
    if(depth[u] > depth[v]) swap(u, v);
    for(int i = 0; i < N_LOG_MAX; i++){
        if((depth[v] - depth[u]) >> i & 1){
            v = parent[i][v];
        }
    }
    if(u == v) return u;
    for(int i = N_LOG_MAX-1; i >= 0; i--){
        if(parent[i][u] != parent[i][v]) {
            u = parent[i][u];
            v = parent[i][v];
        }
    }
    return parent[0][u];
}

int N;
ll cnt[100000];

bool used[100000];
void dfs_cnt(int v){
    used[v] = true;
    for(int to : G[v]){
        if(!used[to]){
            dfs_cnt(to);
            cnt[v] += cnt[to];
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout << setprecision(10) << fixed;
    cin >> N;
    for(int i = 0; i < N-1; i++){
        int u, v;
        cin >> u >> v; u--; v--;
        G[v].push_back(u);
        G[u].push_back(v);
    }
    init(0);
    int Q; cin >> Q;
    for(int i = 0; i < Q; i++){
        int a, b; cin >> a >> b; a--; b--;
        int l = lca(a, b);
        cnt[a]++; cnt[b]++; cnt[l]--;
        if(l != 0) cnt[parent[0][l]]--;
    }
    dfs_cnt(N);
    ll ans = 0;
    for(int i = 0; i < N; i++){
        ans += (cnt[i]*(cnt[i]+1))/2;
    }
    cout << ans << endl;
}
0