您的位置:首页 > 其它

codeforces 813C The Tag Game

2017-07-29 10:53 267 查看
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices.
Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in
turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.

Input

The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n)
— edges of the tree. It is guaranteed that the edges form a valid tree.

[b]Output
[/b]
[b]Print
the total number of moves Alice and Bob will make.
[/b]

[b]Example
[/b]


Input
4 3
1 2
2 3
2 4


Output
4




Input
5 2
1 2
2 3
3 4
2 5


Output
6



第一次做这种对一棵树进行深搜的题,看了博客之后才知道用vector这个容器存储树十分方便

这个题的题意是有两个人,一个在根节点,另一个在除了根节点的其他位置,两人要在同一个点相遇,在跟节点的
那个人想始路径最小,另一个人想让路径最大

解法:用两个数组存储两个人到所有叶子结点的距离,具体方法深搜,然后找一个最大的,并且不再
根节点的那个人要比在根节点的那个人提前到那里,最后结果为根节点到所有叶子结点中最大距离的二倍

#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> mp[200001];
int n,x,a,b,ans,f;
int d1[200001],d2[200001];
void dfs(int p,int from,int step,int *d)
{
if(mp[p].size()==1&&p!=1)
d[p]=step;
for(int i=0;i<mp[p].size();i++)
if(mp[p][i]!=from) //深搜要一直向下扩展,
dfs(mp[p][i],p,step+1,d);
return;
}
int main(void)
{
scanf("%d%d",&n,&x);
for(int i=0;i<n-1;i++)
{
scanf("%d%d",&a,&b);
mp[a].push_back(b);
mp[b].push_back(a);
}
dfs(1,-1,0,d1);
dfs(x,-1,0,d2);
ans=0;

for(int i=2;i<=n;i++)
if(mp[i].size()==1&&d1[i]>d2[i])
ans=max(ans,d1[i]*2);
printf("%d\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codeforces dfs 思维