2018第九届蓝桥杯B组决赛题解第四题 调手表(BFS)

#include<bits/stdc++.h>
using namespace std;
#define MAX 100010
int vis[MAX],num[MAX];
int k,n;
int ans,to;

struct node
{
	int cost;
	int time;
	node(int xx,int yy){
		cost=xx;
		time=yy;
	}	
};

queue <node>  q;
void bfs(int x,int y)
{
	
	num[0]=0;
	vis[0]=1;
	q.push(node(0,0));
	while(!q.empty())
	{
		node now =q.front();
		q.pop();
		
		to=(now.time+1)%n;
		if(!vis[to]){
			vis[to]=1;
			num[to]=now.cost+1;
			q.push(node(now.cost+1,to));
		}
		to=(now.time+k)%n;
		if(!vis[to]){
			vis[to]=1;
			num[to]=now.cost+1;
			q.push(node(now.cost+1,to));
		}
	}
	
}

int main()
{
	memset(vis,0,sizeof(vis));
	scanf("%d%d",&n,&k);
	bfs(0,0);
	sort(num,num+n);
	printf("%d",num[n-1]);
}

 

猜你喜欢

转载自blog.csdn.net/intmain_S/article/details/89243678