結果

問題 No.2337 Equidistant
ユーザー tnakao0123tnakao0123
提出日時 2023-06-28 16:58:41
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,938 bytes
コンパイル時間 578 ms
コンパイル使用メモリ 53,344 KB
実行使用メモリ 31,384 KB
最終ジャッジ日時 2023-09-18 20:44:39
合計ジャッジ時間 10,824 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
9,792 KB
testcase_01 WA -
testcase_02 AC 4 ms
9,760 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 AC 4 ms
9,788 KB
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 -
testcase_19 WA -
testcase_20 WA -
testcase_21 AC 366 ms
30,340 KB
testcase_22 AC 221 ms
30,708 KB
testcase_23 WA -
testcase_24 AC 470 ms
30,324 KB
testcase_25 WA -
testcase_26 AC 652 ms
30,384 KB
testcase_27 WA -
testcase_28 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

/* -*- coding: utf-8 -*-
 *
 * 2337.cc:  No.2337 Equidistant - yukicoder
 */

#include<cstdio>
#include<vector>
#include<algorithm>
 
using namespace std;

/* constant */

const int MAX_N = 200000;
const int BN = 18;

/* typedef */

typedef vector<int> vi;

/* global variables */

vi nbrs[MAX_N];
int ps[MAX_N][BN], ds[MAX_N], ss[MAX_N], cis[MAX_N];

/* subroutines */

int ancestor(int u, int d) {
  for (int i = BN - 1; i >= 0; i--)
    if ((d >> i) & 1) u = ps[u][i];
  return u;
}

int find_lca(int u, int v) {
  if (ds[u] > ds[v]) swap(u, v);

  v = ancestor(v, ds[v] - ds[u]);
  if (u == v) return u;

  for(int i = BN - 1; i >= 0; i--)
    if (ps[u][i] != ps[v][i])
      u = ps[u][i], v = ps[v][i];

  return ps[u][0];
}

/* main */

int main() {
  int n, qn;
  scanf("%d%d", &n, &qn);

  for (int i = 1; i < n; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    u--, v--;
    nbrs[u].push_back(v);
    nbrs[v].push_back(u);
  }

  ps[0][0] = -1, ds[0] = 0;
  for (int u = 0; u >= 0;) {
    vi &nbru = nbrs[u];
    int up = ps[u][0];

    if (cis[u] < nbru.size()) {
      int v = nbru[cis[u]++];
      if (v != up) {
	ps[v][0] = u, ds[v] = ds[u] + 1;
	u = v;
      }
    }
    else {
      ss[u]++;
      if (up >= 0) ss[up] += ss[u];
      u = up;
    }
  }

  for (int i = 0; i < BN - 1; i++)
    for (int u = 0; u < n; u++)
      ps[u][i + 1] = (ps[u][i] >= 0) ? ps[ps[u][i]][i] : -1;

  while (qn--) {
    int s, t;
    scanf("%d%d", &s, &t);
    s--, t--;

    if ((ds[s] - ds[t]) & 1) { puts("0"); continue; }

    if (ds[s] > ds[t]) swap(s, t);
    int w = find_lca(s, t);
    int d = (ds[s] + ds[t] - ds[w] * 2) / 2;

    if (ds[s] != ds[t]) {
      int a0 = ancestor(t, d), a1 = ancestor(t, d - 1);
      printf("%d\n", ss[a0] - ss[a1]);
    }
    else {
      int a0 = ancestor(s, d);
      int a1 = ancestor(s, d - 1), a2 = ancestor(t, d - 1);
      printf("%d\n", ss[a0] - ss[a1] - ss[a2]);
    }
  }
  return 0;
}
0