【题解】CF813C:The Tag Game

原题传送门
分别以 A , B A,B 为起点遍历一遍求出树上各点与 A , B A,B 的距离 d i s a i , d i s b i disa_i,disb_i
B B 希望久一点, A A 希望快一点
那么枚举点 i i ,若 d i s b i > = d i s a i disb_i>=disa_i ,说明之前 B B 肯定被 A A 抓到了
所以对于所有的 d i s b i < d i s a i disb_i<disa_i ,答案是 m a x ( 2 d i s a i ) max(2disa_i)

Code:

#include <bits/stdc++.h>
#define maxn 200010
using namespace std;
struct Edge{
	int to, next;
}edge[maxn << 1];
int num, head[maxn], f[maxn][2], n, a, b;

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

void addedge(int x, int y){ edge[++num] = (Edge){y, head[x]}, head[x] = num; }

void dfs(int u, int pre, int s, int opt){
	f[u][opt] = s;
	for (int i = head[u]; i; i = edge[i].next){
		int v = edge[i].to;
		if (v != pre) dfs(v, u, s + 1, opt);
	}
}

int main(){
	n = read(), b = read(), a = 1;
	for (int i = 1; i < n; ++i){
		int x = read(), y = read();
		addedge(x, y), addedge(y, x);
	}
	dfs(1, 0, 0, 1);
	dfs(b, 0, 0, 2);
	int ans = 0;
	for (int i = 2; i <= n; ++i)
		if (f[i][2] < f[i][1]) ans = max(ans, f[i][1]);
	printf("%d\n", ans << 1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ModestCoder_/article/details/108393589
tag