您的位置:首页 > 其它

Codeforces - 813C The Tag Game

2017-06-06 12:07 232 查看
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.

Output

Print the total number of moves Alice and Bob will make.

Examples

input
4 3
1 2
2 3
2 4


output
4


input
5 2
1 2
2 3
3 42 5


output
6


解题思路:首先先建树,然后节点保存两个值,aval为Alice走到每一个节点所需的时间,bval为bob走到每一个节点所需的时间,通过宽搜可以确定这些值,然后只要判断aval是否大于bval,大于的话证明alic走到该节点比bob要慢,所以可以算是一种情况,这个时候只要取最大值即可。

#include<iostream>
#include<deque>
#include<memory.h>
#include<stdio.h>
#include<map>
#include<string>
#include<algorithm>
#include<vector>
#include<math.h>
#include<stack>
#include<queue>
using namespace std;
typedef long long int ll;

struct node{
vector<int> childs;
int aval=0;
int bval=0;
}nl[300005];

void abfs(){
queue<int> que;
que.push(1);
while(!que.empty()){
int tp=que.front();
que.pop();
for(int i=0;i<nl[tp].childs.size();i++){
if(nl[nl[tp].childs[i]].aval==0&&nl[tp].childs[i]!=1){
nl[nl[tp].childs[i]].aval=nl[tp].aval+1;
que.push(nl[tp].childs[i]);
}
}

}
}

void bbfs(int x){
queue<int> que;
que.push(x);
while(!que.empty()){
int tp=que.front();
que.pop();
for(int i=0;i<nl[tp].childs.size();i++){
if(nl[nl[tp].childs[i]].bval==0&&nl[tp].childs[i]!=x){
nl[nl[tp].childs[i]].bval=nl[tp].bval+1;
que.push(nl[tp].childs[i]);
}
}

}

}

int main(){
int n,x;
cin>>n>>x;

int a,b;
for(int i=0;i<n-1;i++){
cin>>a>>b;
nl[a].childs.push_back(b);
nl[b].childs.push_back(a);
}

abfs();
bbfs(x);

int ans=0;
for(int i=1;i<=n;i++)
if(nl[i].aval>nl[i].bval)
ans=max(ans,nl[i].aval*2);//实际上是((aval-bval)+ava+bval)

cout<<ans<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: