結果

問題 No.2337 Equidistant
ユーザー lgswdn
提出日時 2023-06-02 21:36:14
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 2,206 bytes
コンパイル時間 2,063 ms
コンパイル使用メモリ 196,344 KB
最終ジャッジ日時 2025-02-13 17:49:33
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 6 WA * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
#define fi first
#define se second
#define eb emplace_back
#define mp make_pair
using namespace std;
typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef __int128 i128;
template<typename T,typename U>
T ceil(T x, U y) {return (x>0?(x+y-1)/y:x/y);}
template<typename T,typename U>
T floor(T x, U y) {return (x>0?x/y:(x-y+1)/y);}
template<class T,class S>
bool chmax(T &a,const S b) {return (a<b?a=b,1:0);}
template<class T,class S>
bool chmin(T &a,const S b) {return (a>b?a=b,1:0);}
int popcnt(int x) {return __builtin_popcount(x);}
int popcnt(ll x) {return __builtin_popcountll(x);}
int topbit(int x) {return (x==0?-1:31-__builtin_clz(x));}
int topbit(ll x) {return (x==0?-1:63-__builtin_clzll(x));}
int lowbit(int x) {return (x==0?-1:__builtin_ctz(x));}
int lowbit(ll x) {return (x==0?-1:__builtin_ctzll(x));}

#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<pii> vp;
int read() {
  int x=0,w=1; char c=getchar(); 
  while(!isdigit(c)) {if(c=='-') w=-1; c=getchar();}
  while(isdigit(c)) {x=x*10+(c-'0'); c=getchar();}
  return x*w;
}

const int N=2e5+9;
int n,q,dfn[N],f[N][25],d[N],tick,sz[N];
vi e[N];

void dfs(int u,int fa) {
  dfn[u]=++tick, sz[u]=1;
  d[u]=d[fa]+1, f[u][0]=fa;
  rep(h,1,20) f[u][h]=f[f[u][h-1]][h-1];
  for(int v:e[u]) if(v!=fa) {
    dfs(v,u), sz[u]+=sz[v];
  }
}
int lca(int u,int v) {
  assert(d[u]>=d[v]);
  per(h,20,0) if(d[f[u][h]]>=d[v]) u=f[u][h];
  per(h,20,0) if(f[u][h]!=f[v][h]) u=f[u][h], v=f[v][h];
  return u==v?u:f[u][0];
}
int find(int u,int x) {
  per(h,20,0) if(x&(1<<h)) u=f[u][h];
  return u;
}
int calc(int u,int v) {
  if(d[u]<d[v]) swap(u,v);
  int l=lca(u,v), dis=d[u]+d[v]-2*d[l];
  if(dis&1) return 0;
  int hd=dis/2;
  int p=find(u,hd), fu=find(u,hd-1);
  if(d[u]>d[v]) {
    return sz[p]-sz[fu];
  } else {
    int fv=find(v,hd-1);
    return sz[p]-sz[fu]-sz[fv];
  }
}

signed main() {
  n=read(), q=read();
  rep(i,2,n) {
    int u=read(), v=read();
    e[u].eb(v), e[v].eb(u);
  }
  dfs(1,0);
  rep(i,1,q) {
    int x=read(), y=read();
    printf("%d\n",calc(x,y));
  }
  return 0;
}
0