【传送门】http://codeforces.com/problemset/problem/813/C

【题目大意】两个人玩游戏,一个人跑一个人追,轮流决策,可以走也可以不走。给你一棵树,想要从某个结点到达另一个结点当且仅当两个结点有边相连,A从根节点1号点出发,B从X号点出发,B要尽可能躲A,A要尽可能抓住A,最后两个人共决策了多少次。

【题解】可以知道这样一个事实,B一定会躲到离他最远的那个结点,然后A不管怎样决策B都躲在那里不动了。但是有一点需要注意,B需要比A先到达那个叶子结点。

所以问题转化成了分别求A,B到各个叶子结点的距离。选取一个A到达某一叶子结点的最远值,注意还必须满足这个最远值要大于B到达这个叶子结点的距离。

使用DFS对树进行搜索,直到叶子结点,每每遇见一个叶子结点就记下距离。起点分别设置为1和X,距离保存在两个数组中。

【AC代码】

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<vector>
#include<cstring>
#include<iomanip>
using namespace std;
typedef long long ll;
const int maxn = 2e5+;
vector<int> G[maxn];
ll d1[maxn];
ll d2[maxn]; void dfs(int st, int fr, ll step, ll d[]){
if(G[st].size() == && st != ){
d[st] = step;
//return ;//这里return会错误
} for(int i=; i<G[st].size(); i++){
if(G[st][i] != fr){
dfs(G[st][i] , st, step+, d);
}
}
} int main(){
int n,x;
int s,t;
while(scanf("%d%d",&n,&x) != EOF){
ll ans = ;
for(int i=; i<maxn; i++) G[i].clear();
memset(d1 , ,sizeof d1);
memset(d2 , ,sizeof d2);
while(scanf("%d%d",&s,&t) != EOF){
G[s].push_back(t);
G[t].push_back(s);
}
dfs(, -, , d1);
dfs(x, -, , d2); for(int i=; i<=n; i++){
if(d1[i] > d2[i] && G[i].size() == ){
ans = max(ans , *d1[i]);
}
}
printf("%lld\n",ans);
}
return ;
}

最新文章

  1. 为Guid数据类型的属性(property)赋值
  2. sql with as union all
  3. express实现前后端通信上传图片,存储数据库(mysql)傻瓜教程(三)完结篇
  4. Android项目实战(二十八):Zxing二维码实现及优化
  5. ORACLE实验一-三
  6. Win下常用命令大全
  7. spark IDEA开发环境搭建及运行问题
  8. [WinForm] TableLayoutPanel和FlowLayoutPanel的使用
  9. 《Spring3.0就这么简单》
  10. css 垂直同步的几种方式
  11. Struts2 自定义拦截器实例—登陆权限验证
  12. HDU 5758 Explorer Bo
  13. mybatis(三)
  14. Python的re模块
  15. SSRF漏洞浅析
  16. shell 在终端中打开另一个终端执行命令
  17. Linux C++ TCP Socket传输文件或图片实例
  18. CentOS7的/tmp目录自动清理规则
  19. idataway_前端代码规范
  20. 转 举例说明使用MATLAB Coder从MATLAB生成C/C++代码步骤

热门文章

  1. JavaScript reduce() 方法
  2. [LUOGU] P2716 和谐的雪花
  3. easyUI之datagrid绑定后端返回数据的两种方式
  4. Re:从零开始的Linux之路(杂谈)
  5. PWA天气应用
  6. Mac OS X下安装Vue脚手架(vue-cli)
  7. linux系统,python3.7环境安装talib过程
  8. poj--2139
  9. eclipse中tab键设置
  10. android 之 GridView