結果

問題 No.2337 Equidistant
ユーザー umezoumezo
提出日時 2023-06-03 04:02:58
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,934 bytes
コンパイル時間 2,322 ms
コンパイル使用メモリ 202,140 KB
実行使用メモリ 45,748 KB
最終ジャッジ日時 2023-08-28 07:36:44
合計ジャッジ時間 12,937 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 7 ms
21,640 KB
testcase_01 AC 7 ms
21,840 KB
testcase_02 WA -
testcase_03 AC 7 ms
21,736 KB
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 -
testcase_19 WA -
testcase_20 WA -
testcase_21 AC 484 ms
45,748 KB
testcase_22 AC 194 ms
30,516 KB
testcase_23 WA -
testcase_24 AC 630 ms
40,452 KB
testcase_25 WA -
testcase_26 AC 831 ms
40,532 KB
testcase_27 WA -
testcase_28 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(v) v.begin(), v.end()
typedef long long ll;

#include <bits/stdc++.h>
using namespace std;

const int MAX=200010;
const int MAX_LOG=18;
vector<int> G[MAX];
int root;

int parent[MAX_LOG][MAX];
int len[MAX];
int siz[MAX];

void dfs(int v,int p,int d){
  parent[0][v]=p;
  len[v]=d;
  int cnt=1;
  for(auto x:G[v]){
    if(x==p) continue;
    dfs(x,v,d+1);
    cnt+=siz[x];
  }
  siz[v]=cnt;
}

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

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

pair<int,int> lca2(int u,int v){
  for(int k=MAX_LOG-1;k>=0;k--){
    if(parent[k][u]!=parent[k][v]){
      u=parent[k][u];
      v=parent[k][v];
    }
  }
  return {u,v};
}

pair<int,int> lca3(int u,int l){
  for(int k=MAX_LOG-1;k>=0;k--){
    if(len[parent[k][u]]>l){
      u=parent[k][u];
    }
  }
  return {u,parent[0][u]};
}

int dist(int a,int b){
  return len[a]+len[b]-2*len[lca(a,b)];
}

int main(){
  ios::sync_with_stdio(false);
  std::cin.tie(nullptr);

  int n,q;
  cin>>n>>q;

  rep(i,n-1){
    int a,b;
    cin>>a>>b;
    a--,b--;
    G[a].push_back(b);
    G[b].push_back(a);
  }
  
  root=0;
  init(n);
  
  rep(i,q){
    int s,t;
    cin>>s>>t;
    s--,t--;
    if(len[s]==len[t]){
      auto p=lca2(s,t);
      cout<<n-siz[p.first]-siz[p.second]<<'\n';
    }
    else if(dist(s,t)%2) cout<<0<<'\n';
    else{
      if(len[s]<len[t]) swap(s,t);
      auto p=lca3(s,dist(s,t)/2);
      cout<<siz[p.second]-siz[p.first]<<'\n';
    }
  }
  
  return 0;
}
0