CodeForces-813C The Tag Game

这篇博客讨论了在CodeForces 813C问题中,Alice和Bob在树形结构上进行的标签游戏。游戏目标是Alice要以最少的步数追上Bob,而Bob则希望增加步数。问题转化为求解最短路径的最大值。通过分析,可以确定Alice将直奔Bob的位置,而Bob会尽可能深入。解决方案包括使用最短路径算法和搜索策略。博主提供了两种不同的代码实现来解决这个问题。
摘要由CSDN通过智能技术生成

题目链接:
https://vjudge.net/problem/CodeForces-813C

The Tag Game
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
4 3
1 2
2 3
2 4

4

5 2
1 2
2 3
3 4
2 5

6
Note
In the first example the tree looks like this:

The red vertex is Alice’s starting position, the blue one is Bob’s. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4

题目的大意就是Alice和Bob(后面用A和B代替)在玩一个游戏,A的初始位置在1,B的初始位置在x。然后A和B同时走,直到A和B同时在一个地方游戏结束,在这个过程中A想用尽可能少的步数追上B,但是B又想让A追上他的步数尽可能多(就是A想尽可能快的追上B,但是B又不想让A那么快的追上),大致就是这个意思。B是可以选择移动或者待在原地不动的,最后是要我们求A和B总共移动的步数。

思路:
这道题其实就是求最短路径的最大值,因为A和B是同时走的,并且就算B待在原地不动的话最后总共还是会+1(这里好像用时间好理解一点,即最后让我们求A追上B的时间,移动一步算1s,B如果原地不动时间也会+1)。所有说求最后总共的步数的话,就相当于是求A一共走过的步数的两倍。因为A和B肯定在同一棵树上,A又想尽可能快的追上B,所以A会直接向B走,不会走其他的支路,B是不想让A那么快追上,所以如果B还能往更深的地方走的话,他肯定会走下去,直到到底了以后,他就会在原地不动。这时候问题就转化成了求A能到达的最远的节点,同时也要判断B能否到达,而且要保证B是能比A先到的,这样就可以求出最大值了。

我们最开始是用最短路来求,最后过了,后来在网上翻博客,发现都是用搜索写的,不过思路都是一样的。

那就把两种代码都贴上:

//比赛时用最短路写的
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
#define inf 0x3f3f3f3f
#define maxn 400100
int first[maxn],Next[maxn],dis[maxn],dis1[maxn],u[maxn],v[maxn];
int main()
{
   
    int n,m,maxx=0;
    cin>>n>>m;
    for(int i=1; i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值