其他分享
首页 > 其他分享> > 牛客网The Flee Plan of Groundhog

牛客网The Flee Plan of Groundhog

作者:互联网

题目描述:

Groundhog was especially careful after the outbreak,so he put on his mask in the 1st1^{st}1st bedroom early,and then walked on the way to the nth{n^{th}}nth dormitory to play with Orange. There are n{n}n dormitories in ZLZX, which are connected by n−1{n-1}n−1 corridors. Each dormitory can be reached to each other.The length of each corridor is 1{1}1.The walking speed of Groundhog is 1 m/s{1\ \mathrm{m/s}}1 m/s.
At that moment the bad news came: After Groundhog set out for t{t}t seconds,Orange took his temperature, and it turned out to be 41℃ !!! In addition to grief and indignation, Orange decided to run to Groundhog, to tell him the news at the speed of  2 m/s{2\ \mathrm{m/s}}2 m/s.
Groundhog had to run, of course, but he was running too slow at 1 m/s{1\ \mathrm{m/s}}1 m/s . As he ran, he had an idea: if he ran with the best strategy, how soon would Orange catch up  with him? Define that every second Groundhog moves and then Orange moves again. Groundhog can choose to stay put.
Groundhog would have solved that, of course, but he is running away now, so he give it to you, the smartest one.

翻译:

土拨鼠在第 1 个房间,要走到Orange的第 n 个房间。 这 n 间房间之间有 n-1 条走廊,确保这 n 个房间连通,每个走廊的长度为 1 。

土拨鼠出发 t 秒钟后,Orange发现他发烧了。愚蠢的Orange以 2m/s 的速度跑向土拨鼠。

土拨鼠的速度为 1m/s 。如果他以最佳策略跑步,Orange多久能赶上他?每秒钟土拨鼠移动一次,然后Orange再次移动。土拨鼠可以选择留在原地。

输入描述:

第一行包含两个整数n,t。接下来的n-1行,每行包含两个整数x,y,表示在第x个宿舍和第y个宿舍之间有一条走廊。

输出描述:

一个整数,表示Orange赶上土拨鼠的最晚可能时间。

分析:

见代码。

 

 

代码如下:

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10, M = N << 1;
int h[N], e[M], ne[M], idx = -1;
void add(int a, int b)
{
    e[++idx]=b;
    ne[idx]=h[a];
    h[a]=idx;
}
int n, t;
int dist[N], f[N]; 
void dfs1(int u, int fa, int step)
{ 
    f[u]=fa;
    dist[u]=step;    //记录下每个点到 n 的距离  
    for(int i=h[u]; i!=-1; i=ne[i])
    {
        int v=e[i];
        if(v==fa) continue;
        dfs1(v,u,step+1);
    }
}
int max_dist;
void dfs2(int u, int fa)//从t时间所在点往相反的方向跑最远是多少 
{
    max_dist=max(max_dist,dist[u]);
    for(int i=h[u]; i!=-1; i=ne[i])
    {
        int v=e[i];
        if(v==fa) continue;
        dfs2(v,u);
    }
}

int main()
{
    memset(h,-1,sizeof h);
    scanf("%d%d",&n,&t);
    for(int i=1; i<n; i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b);
        add(b,a);
    }
    dfs1(n,n,0); //预处理每个点到n点的距离  
    int pos=1;
    while(t--) pos=f[pos]; //找到t秒可到达的从1~n路径上的点  
    dfs2(pos,f[pos]); //找到从pos开始,远离n点的方向处找到可以到达的最远点 
    int x=max_dist-dist[pos]; //从pos处开始,和远离n点的方向可以到达的最远点的距离 
    int y=dist[pos]; //从n点到pos点的距离 
    if(pos==n || y==0) printf("0\n"); //已经到n点了,跑不掉了
    else if(x-y>=0) printf("%d\n",y); //在跑到最远点前被抓住了
    else printf("%d\n",max_dist+1>>1); //在最远点被抓住
    return 0;
}
View Code

 

标签:Groundhog,Flee,房间,牛客,Plan,Orange,mathrm,土拨鼠,he
来源: https://www.cnblogs.com/WWWZZZQQQ/p/13468545.html