B - The Tag Game( 树 的BFS)
作者:互联网
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 4 2 5
output
6
题目大意及思路
题目大意:有n个点,n-1条边,Alice在点1,Bob在点K,Bob跑Alice追,问Alice追上Bob时,Alice和Bob的总步数 思路:以Alice追上Bob为终点,所以总步数就是Alice走的步数的两倍,两遍DFS,记录A和B到各点的步数,
再找到可到达的点中步数最大的,如果有一点x ,Ax<=Bx 说明A和B会提前遇到所以不管这个点
代码实现
#include <iostream> #include <bits/stdc++.h> #define maxn 200005 using namespace std; int vis1[maxn],vis2[maxn]; //标记是否走过 vector<int> p[maxn]; //存储树的数据 int step1[maxn],step2[maxn]; //记录到某个点的步数 void dfs1(int x,int count){ step1[x]=count; vis1[x]=1; for(int i=0;i<p[x].size();i++){ if(vis1[p[x][i]]==0){ count++; dfs1(p[x][i],count); count--; } } return ; } void dfs2(int x,int count){ step2[x]=count; vis2[x]=1; for(int i=0;i<p[x].size();i++){ if(vis2[p[x][i]]==0){ count++; dfs2(p[x][i],count); count--; //步数回溯 } } return ; } int main() { int n,x,a,b; cin>>n>>x; for(int i=0;i<n-1;i++){ //存储树的数据 cin>>a>>b; p[a].push_back(b); p[b].push_back(a); } memset(vis1,0,sizeof(vis1)); memset(vis2,0,sizeof(vis2)); memset(step1,0,sizeof(step1)); memset(step2,0,sizeof(step2)); dfs1(1,0); dfs2(x,0); //从 1,x处开始搜索,步数初始都为0 /* for(int i=1;i<=n;i++){ cout<<step1[i]<<endl; cout<<step2[i]<<endl; } */ int sum=0; for(int i=1;i<=n;i++){ if(step1[i]>step2[i]){ //找step1[i]>step2[i]
sum=max(sum,2*step1[i]);
}
}
cout<<sum<<endl;
return 0;
}
标签:int,Alice,BFS,Game,Tag,maxn,step1,Bob,步数 来源: https://www.cnblogs.com/yhj-coisini/p/15036166.html