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

题意:给你一个无向有根树,根节点为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
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值