您的位置:首页 > 其它

Educational Codeforces Round 22 C. The Tag Game(思维 搜索)

2017-06-06 00:58 381 查看
题意:给你一个无向有根树,根节点为1,有两个人,A在节点1,B在节点X,AB轮流走,B先走,每次可以原地不动或是向相邻节点移动一次。A想最快抓到B,B想最慢被抓到,

问什么时候A抓到B。

思路:每个人都走最优,是不会走回头路的(B来回走可以看作在一点不动),那么我们可以先求下A,B分别到所有节点的最短时间,对于每个节点如果B走的时间小于A走的时间那B就可以走到这个,所以找到disB[i] < disA[i] 且 disA[i]最大的那个点,就是最晚被抓到的那个点,disA[i]*2就是答案。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
typedef long long ll;
vector<int> g[maxn];
int n, x, d1[maxn], d2[maxn];
bool vis[maxn];
struct node
{
int x, f, s;
node() {}
node(int xx, int ff, int ss):x(xx), f(ff), s(ss) {}
};

void bfs1()
{
memset(vis, 0, sizeof(vis));
queue<node> q;
q.push(node(1, 0, 0));
vis[1] = 1;
node u;
while(!q.empty())
{
u = q.front(); q.pop();
d1[u.x] = u.s;
int f = u.f;
for(int i = 0; i < g[u.x].size(); i++)
{
int to = g[u.x][i];
if(to != f && !vis[to])
{
vis[to] = 1;
q.push(node(to, u.x, u.s+1));
}
}
}
}

void bfs2()
{
memset(vis, 0, sizeof(vis));
queue<node> q;
q.push(node(x, 0, 0));
vis[x] = 1;
node u;
while(!q.empty())
{
u = q.front(); q.pop();
d2[u.x] = u.s;
int f = u.f;
for(int i = 0; i < g[u.x].size(); i++)
{
int to = g[u.x][i];
if(to != f && !vis[to])
{
vis[to] = 1;
q.push(node(to, u.x, u.s+1));
}
}
}
}

int main(void)
{
while(cin >> n >> x)
{
for(int i = 0; i < maxn; i++)
g[i].clear();
for(int i = 1; i < n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
bfs1();
bfs2();
int ans = 0;
for(int i = 1; i <= n; i++)
if(d2[i] < d1[i])
ans = max(ans, d1[i]*2);
printf("%d\n", ans);
}
return 0;
}

/*
6 6
1 2
2 3
3 6
3 4
4 5

--8
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codeforces 搜索