結果

問題 No.2337 Equidistant
ユーザー no wayno way
提出日時 2023-06-02 22:32:39
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 599 ms / 4,000 ms
コード長 1,133 bytes
コンパイル時間 1,613 ms
コンパイル使用メモリ 167,072 KB
実行使用メモリ 46,740 KB
最終ジャッジ日時 2023-08-28 04:33:25
合計ジャッジ時間 10,489 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
11,748 KB
testcase_01 AC 4 ms
11,960 KB
testcase_02 AC 4 ms
11,768 KB
testcase_03 AC 4 ms
11,700 KB
testcase_04 AC 5 ms
11,700 KB
testcase_05 AC 4 ms
11,964 KB
testcase_06 AC 6 ms
11,740 KB
testcase_07 AC 7 ms
11,704 KB
testcase_08 AC 6 ms
11,784 KB
testcase_09 AC 6 ms
11,780 KB
testcase_10 AC 6 ms
11,780 KB
testcase_11 AC 297 ms
31,128 KB
testcase_12 AC 295 ms
31,088 KB
testcase_13 AC 324 ms
31,060 KB
testcase_14 AC 305 ms
31,044 KB
testcase_15 AC 313 ms
31,044 KB
testcase_16 AC 315 ms
31,036 KB
testcase_17 AC 310 ms
31,076 KB
testcase_18 AC 320 ms
31,008 KB
testcase_19 AC 311 ms
31,080 KB
testcase_20 AC 311 ms
31,004 KB
testcase_21 AC 464 ms
46,740 KB
testcase_22 AC 250 ms
31,116 KB
testcase_23 AC 266 ms
31,704 KB
testcase_24 AC 548 ms
41,468 KB
testcase_25 AC 287 ms
31,728 KB
testcase_26 AC 599 ms
41,148 KB
testcase_27 AC 290 ms
31,900 KB
testcase_28 AC 286 ms
31,800 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
const int D=18;
int f[N][D+1];
int dep[N],sz[N];
vector<int>e[N];
int n,q,x,y;
void dfs(int x,int y,int d){
	dep[x]=d;f[x][0]=y;sz[x]=1;
	for (int i=1;i<=D;i++) f[x][i]=f[f[x][i-1]][i-1];
	for (int i=0;i<e[x].size();i++){
		int u=e[x][i];
		if (u==y) continue;
		dfs(u,x,d+1);
		sz[x]+=sz[u];
	}
}
int get_lca(int x,int y){
	for (int i=D;i>=0;i--) if (dep[f[x][i]]>=dep[y]) x=f[x][i];
	for (int i=D;i>=0;i--) if (f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i];
	if (x!=y) x=f[x][0];
	return x;
}
int up(int x,int y){
	for (int i=D;i>=0;i--) if ((y>>i)&1) x=f[x][i];
	return x;
}
void solve(int x,int y){
	if (dep[x]<dep[y]) swap(x,y);
	int lca=get_lca(x,y);
	int t=dep[x]+dep[y]-2*dep[lca];
	if (t&1) puts("0");
	else{
		if (dep[x]==dep[y]){
			printf("%d\n",n-sz[up(x,(t>>1)-1)]-sz[up(y,(t>>1)-1)]);
		}else{
			printf("%d\n",sz[up(x,t>>1)]-sz[up(x,(t>>1)-1)]);
		}
	}
}
int main(){
	scanf("%d%d",&n,&q);
	for (int i=1;i<n;i++){
		scanf("%d%d",&x,&y);
		e[x].push_back(y);
		e[y].push_back(x);
	}
	dfs(1,0,1);
	for (int i=1;i<=q;i++){
		scanf("%d%d",&x,&y);
		solve(x,y);
	}
}
0