The Tag Game

来源:互联网 发布:怎么在mac上新建文件夹 编辑:程序博客网 时间:2024/06/15 11:14

a要追赶b,b尽量不让a追上,可以通过深搜或广搜获得a,b分别到每一个节点的的时间,只要b到达某点的时间小于a到该点的时间就表明b能优先于a到达该点,此后只要找一个最大值即可

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·1052 ≤ 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.

Example
Input
4 31 22 32 4
Output
4
Input
5 21 22 33 42 5
Output
6
Note

In the first example the tree looks like this:

The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3during all the game. So here are the moves:

B: stay at vertex 3

A: go to vertex 2

B: stay at vertex 3

A: go to vertex 3

In the second example the tree looks like this:

The moves in the optimal strategy are:

B: go to vertex 3

A: go to vertex 2

B: go to vertex 4

A: go to vertex 3

B: stay at vertex 4

A: go to vertex 4


#include<stdio.h>#include<string.h>#include<vector>#include<queue>using namespace std;void dfs(int x,int cur);queue<int> q;vector<int> an[200005];bool book[200005];int _max,timea[200005],timeb[200005]; int main(){int n,x,reco;scanf("%d%d",&n,&x);for(int i=0;i<n-1;i++){int a,b;scanf("%d%d",&a,&b);an[a].push_back(b);an[b].push_back(a);}reco=1;timea[1]=0;book[1]=true;q.push(reco);while(!q.empty()){int Q;Q=q.front();for(int i=0;i<an[Q].size();i++){if(book[an[Q][i]]==false){book[an[Q][i]]=true;reco=an[Q][i];timea[an[Q][i]]=timea[Q]+1;q.push(reco);}}q.pop();}memset(book,false,sizeof(book));reco=x;timeb[1]=0;book[x]=true;q.push(reco);while(!q.empty()){int Q;Q=q.front();for(int i=0;i<an[Q].size();i++){if(book[an[Q][i]]==false){book[an[Q][i]]=true;reco=an[Q][i];timeb[an[Q][i]]=timeb[Q]+1;q.push(reco);}}q.pop();}_max=-1;for(int i=2;i<=n;i++){if(timeb[i]<timea[i]){if(timea[i]>_max)_max=timea[i];}}printf("%d",2*_max);return 0;}


原创粉丝点击