[Blue Bridge Cup] 2018 Final Tuning Watch (bfs)

topic:

Title description

Xiao Ming bought a high-end, high-end electronic watch, and he is about to adjust the time.
In the M78 Nebula, the unit of measurement of time is different from that on Earth. An hour in the M78 Nebula has n minutes.
Everyone knows that the watch has only one button to increase the current number by one. When adjusting the minutes, if the currently displayed number is 0, it will change to 1 when you press the button, and it will change to 2 when you press it again. If the current number is n-1, it will become 0 after pressing it once.
As a patient with obsessive-compulsive disorder, Xiao Ming must adjust the time of his watch. If the time on the watch is 1 more than the current time, you have to press the plus one button n-1 times to return to the correct time.
Xiao Ming thought, if the watch can add another button, it means adding k to the current number...
He wants to know that if there is this +k button, press the button according to the optimal strategy to adjust from any minute to another The maximum number of times to press any one minute.
Note that when you press the +k button, if the number after adding k exceeds n-1, n will be modulo n.
For example, when n=10 and k=6, assuming the current time is 0, press the +k button twice to adjust to 2.

enter

Two integers n, k have the same meaning as the title.
0 <k <n <= 100000

Output

One integer
per line means: according to the optimal strategy, how many times should be pressed at most to adjust from one time to another.

Sample input

5 3

Sample output

2

prompt

If the time is correct, press 0 times. Otherwise, the relationship between the number of times to be pressed and the operation series is as follows:
1: +1
2: +1, +1
3: +3
4: +3, +1


Code:

According to the characteristics of bfs: the first time it arrives must be the shortest, run a wide search.

Finding the shortest number of steps at these points from 0 to n-1, and then finding the maximum number of steps in these steps is the answer.

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn=100020; 
ll n,k,ans=0,dis[maxn];
bool vis[maxn]={
    
    false};

void bfs()
{
    
    
	queue<int> q;
	fill(dis,dis+maxn,0); //初始化为0
	vis[0]=1;
	q.push(0);
	while(!q.empty())
	{
    
    
		int p = q.front();
		q.pop();
		ans = max(ans,dis[p]);
		
		int x=(p+1)%n; //超过n-1就取余n 
		if(!vis[x]) //没到过
		{
    
    
			q.push(x);
			dis[x]=dis[p]+1;
			vis[x]=1; //记录到过
		}
		
		int y=(p+k)%n; //超过n-1就取余n 
		if(!vis[y]) 
		{
    
    
			q.push(y);
			dis[y]=dis[p]+1;
			vis[y]=1; //记录到过
		}
	}
}
int main() 
{
    
    
	cin>>n>>k;
	bfs();
	cout<<ans;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/109319512