标题:调手表
小明买了块高端大气上档次的电子手表,他正准备调时间呢。
在 M78 星云,时间的计量单位和地球上不同,M78 星云的一个小时有 n 分钟。
大家都知道,手表只有一个按钮可以把当前的数加一。在调分钟的时候,如果当前显示的数是 0 ,那么按一下按钮就会变成 1,再按一次变成 2 。如果当前的数是 n - 1,按一次后会变成 0 。
作为强迫症患者,小明一定要把手表的时间调对。如果手表上的时间比当前时间多1,则要按 n - 1 次加一按钮才能调回正确时间。
小明想,如果手表可以再添加一个按钮,表示把当前的数加 k 该多好啊……
他想知道,如果有了这个 +k 按钮,按照最优策略按键,从任意一个分钟数调到另外任意一个分钟数最多要按多少次。
注意,按 +k 按钮时,如果加k后数字超过n-1,则会对n取模。
比如,n=10, k=6 的时候,假设当前时间是0,连按2次 +k 按钮,则调为2。
「输入格式」
一行两个整数 n, k ,意义如题。
「输出格式」
一行一个整数
表示:按照最优策略按键,从一个时间调到另一个时间最多要按多少次。
「样例输入」
5 3
「样例输出」
2
「样例解释」
如果时间正确则按0次。否则要按的次数和操作系列之间的关系如下:
1:+1
2:+1, +1
3:+3
4:+3, +1
「数据范围」
对于 30% 的数据 0 < k < n <= 5
对于 60% 的数据 0 < k < n <= 100
对于 100% 的数据 0 < k < n <= 100000
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
思路:广搜即可,有同学的写的完全背包也是完全没问题.
代码:
#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
const double esp = 1e-12;
const int inf = 0x3f3f3f3f;
map<int,int>::iterator it;
struct node
{
int cost,time;
node(int cost,int time):cost(cost),time(time){}
};
int n,k;
int vis[maxn],num[maxn];
void bfs()
{
queue<node> q;
q.push(node(0,0));//假设从0开始走表,从哪都一样
num[0] = 0;
vis[0] = 1;
while(!q.empty())
{
node now = q.front();
q.pop();
int 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()
{
mem(num,inf);
cin>>n>>k;
bfs();
int ans = 0;
for(int i = 0;i< n;i++)
ans = max(ans,num[i]);
printf("%d\n",ans);
return 0;
}