結果

問題 No.2337 Equidistant
コンテスト
ユーザー zjsdut
提出日時 2026-08-19 02:23:07
言語 C++23
(gcc 15.2.0 + boost 1.90.0)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 247 ms / 4,000 ms
+ 393µs
コード長 2,086 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,057 ms
コンパイル使用メモリ 334,300 KB
実行使用メモリ 45,952 KB
最終ジャッジ日時 2026-08-19 02:23:22
合計ジャッジ時間 9,609 ms
ジャッジサーバーID
(参考情報)
judge3_1 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

/**
 *    author:  zjs
 *    created: 19.08.2026 00:43:04
**/
#include <bits/stdc++.h>
#include <cassert> // <bits/stdc++.h> does not include cassert since GCC 16.
using namespace std;

#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#endif
const int maxn = 2e5 + 5;
const int LOG = 18;
int anc[maxn][LOG];
vector<int> g[maxn];
int depth[maxn];
int sz[maxn];
void dfs(int u, int p) {
    sz[u] = 1;
    depth[u] = depth[p] + 1;
    anc[u][0] = p;
    for (int i = 1; i < LOG; i++)
        anc[u][i] = anc[anc[u][i - 1]][i - 1];
    for (int v : g[u])
        if (v != p) {
            dfs(v, u);
            sz[u] += sz[v];
        }
}

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

int kth_anc(int u, int k) {
    for (int i = 0; i < LOG; i++)
        if (k >> i & 1)
            u = anc[u][i];
    return u;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, q;
    cin >> n >> q;
    for (int i = 0; i < n - 1; i++) {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1, 0);
    while (q--) {
        int s, t;
        cin >> s >> t;
        if ((depth[s] + depth[t]) & 1) {
            cout << 0 << '\n';
            continue;
        }
        int LCA = lca(s, t);
        int d = depth[s] + depth[t] - 2 * depth[LCA];
        if (depth[s] < depth[t])
            swap(s, t);
        int ans;
        if (depth[s] == depth[t]) {
            int A = kth_anc(s, d / 2 - 1);
            int B = kth_anc(t, d / 2 - 1);
            ans = n - sz[A] - sz[B];
        } else {
            int M = kth_anc(s, d / 2);
            int A = kth_anc(s, d / 2 - 1);
            ans = sz[M] - sz[A];
        }
        cout << ans << '\n';
    }
}
0