問題 M: Playing Tag on Tree------------------------------思維(圖論)

題目描述
We have a tree with N vertices. The i-th edge connects Vertex Ai and Bi bidirectionally.
Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.
Now, they will play a game of tag as follows:

  1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.
  2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.
  3. Go back to step 1.
    Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible.
    Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other’s position and strategy.
    It can be proved that the game is bound to end.

Constraints
·2≤N≤105
·1≤u,v≤N
·u≠v
·1≤Ai,Bi≤N
·The given graph is a tree.
輸入
Input is given from Standard Input in the following format:

N u v
A1 B1
:
AN−1 BN−1

輸出
Print the number of moves Aoki will perform before the end of the game.
樣例輸入 Copy
【樣例1】

5 4 1
1 2
2 3
3 4
3 5
【樣例2】
5 4 5
1 2
1 3
1 4
1 5
【樣例3】
2 1 2
1 2
【樣例4】
9 6 1
1 2
2 3
3 4
4 5
5 6
4 7
7 8
8 9
樣例輸出 Copy
【樣例1】

2
【樣例2】
1
【樣例3】
0
【樣例4】
5
提示
樣例1解釋

If both players play optimally, the game will progress as follows:
·Takahashi moves to Vertex 3.
·Aoki moves to Vertex 2.
·Takahashi moves to Vertex 5.
·Aoki moves to Vertex 3.
·Takahashi moves to Vertex 3.
Here, Aoki performs two moves.

Note that, in each move, it is prohibited to stay at the current vertex.
題意:
給一棵樹,x和y博弈,首先x在u點,y在v點,遊戲結束條件是x和y重合,x先動,x希望遊戲更晚結束,y希望遊戲更早結束,求y在遊戲結束前走的步數
解析:

設最終在點p處結束遊戲 那麼滿足dist(p,u)<=dist(p,v)
因爲x可以跑很遠,y肯定要走x走過的路,自然y到p點就遠了
所以取滿足離y最遠且x到達該結點比y早即可

由於x先動,所以我們要去dist(p,v)的最大值

#include<bits/stdc++.h> 
using namespace std;
const int N=1e5+1000;
vector<int> G[N];
int d[N],d1[N];
bool st[N];
int n,u,v,a,b;
void bfs1(int u,int d[])
{
	memset(st,false,sizeof st);
	queue<int> q;
	q.push(u);
	st[u]=true;
	d[u]=0;
	while(q.size())
	{
		int t=q.front();
		q.pop();
		for(int j: G[t])
		{
			if(j==t) continue;
			if(st[j]) continue;
			d[j]=d[t]+1;
			st[j]=true;
			q.push(j);
		}
	}
	
}
void bfs2(int u,int d1[])
{
	memset(st,false,sizeof st);
	queue<int> q;
	q.push(u);
	st[u]=true;
	d1[u]=0;
	while(q.size())
	{
		int t=q.front();
		q.pop();
		for(int j: G[t])
		{
			if(j==t) continue;
			if(st[j]) continue;
			d1[j]=d1[t]+1;
			st[j]=true;
			q.push(j);
		}
	}
	
}
int main()
{
	cin>>n>>u>>v;
	for(int i=0;i<n-1;i++)
	{
		cin>>a>>b;
		G[a].push_back(b);G[b].push_back(a);
	}
	bfs1(u,d);bfs2(v,d1);
	int ans=0;;
	for(int i=1;i<=n;i++)
	{
	//	cout<<d[i]<<" "<<d1[i]<<endl;
		if(d[i]<d1[i]) ans=max(ans,d1[i]);
	}
	cout<<ans-1<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章