C. The Tag Game

来源:互联网 发布:贪玩传奇盛世翅膀数据 编辑:程序博客网 时间:2024/06/08 13:40

C. The Tag Game
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
input
4 31 22 32 4
output
4
input
5 21 22 33 42 5
output
6
这个题分析一下,其实就是在这两个人的路径上,BOB选择在哪个点走一个最长链的问题。

for(int i = 0, j = cnt-1 ; i < j ; ++i,--j)    {        ans = max(ans,(i+deep[path[i]]-deep[path[j]]+dis[path[i]]-1)*2);    }
这个东西,path是路径,从Bob到Alice,i是A已经走的步数,deep[path[i]]-deep[path[j]]是指A到达B的步数,然后dis[path[i]]-1是B能够到达的最大深度。

用这些更新一个最大值就可以了。

#include <bits/stdc++.h>using namespace std;const int MAXN = 2e5+7;const int inf = 1e9;vector<int>head[MAXN];int dis[MAXN];//最大深度int deep[MAXN];//在当前树中的深度int pre[MAXN];//记录祖先int path[MAXN];//记录路径int n,m;int dfs(int u,int fa,int d){    int MAX = 0;    deep[u] = d;    pre[u] = fa;    for(int i = 0 ,l = head[u].size(); i < l ; ++i)    {        int v =head[u][i];        if(v == pre[u])continue;        MAX = max(MAX,dfs(v,u,d+1));    }    return dis[u] = MAX + 1;}int main(){    scanf("%d%d",&n,&m);    int u,v;    for(int i = 0 ; i < n-1 ; ++i)    {        scanf("%d%d",&u,&v);        head[u].push_back(v);        head[v].push_back(u);    }    dfs(1,-1,0);    int t = m,cnt = 0;    while(t != -1)    {        path[cnt++] = t;        t = pre[t];    }    int ans = 0 ;    for(int i = 0, j = cnt-1 ; i < j ; ++i,--j)    {        ans = max(ans,(i+deep[path[i]]-deep[path[j]]+dis[path[i]]-1)*2);    }    printf("%d\n",ans);    return 0;}/*9 41 22 33 44 54 63 77 88 9109 31 22 33 43 52 66 77 88 96*/






原创粉丝点击