题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5945
Fxx and game
Accepts: 74
Submissions: 1857
Time Limit: 3000/1500 MS (Java/Others)
Memory Limit: 131072/65536 K (Java/Others)
问题描述
青年理论计算机科学家Fxx给的学生设计了一款数字游戏。 一开始你将会得到一个数X,每次游戏将给定两个参数k,t, 任意时刻你可以对你的数执行下面两个步骤之一: 1.X=X−i(1<=i<=t)。 2.若X为k的倍数,X=X/k。 现在Fxx想要你告诉他最少的运行步骤,使X变成1。
输入描述
第一行一个整数T(1≤T≤20)表示数据组数。 接下来T行,每行三个数X,k,t(0≤t≤106,1≤X,k≤106) 数据保证有解。
输出描述
输出共T行。
每行一个整数表示答案。
输入样例
2 9 2 1 11 3 3
输出样例
4 3
题目大意:略
题目解析:用bfs搜下,注意去重(进去循环节 t )
代码如下:
#include<iostream>
#include<algorithm>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 1000009
using namespace std;
const int inf = 1e9;
const int mod = 1<<30;
const double eps = 1e-8;
const double pi = acos(-1.0);
typedef long long LL;
struct node
{
int x, f;
node(int x, int f) : x(x), f(f) {}
};
int vis[N];
int bfs(int x, int k, int t)
{
memset(vis, 0, sizeof(vis));
vis[x] = 1;
queue<node> q;
q.push(node(x, 0));
int cnt = 0;
while(!q.empty())
{
int kk = q.size(), i; cnt++;
while(kk--)
{
node now = q.front(); q.pop();
if(now.x % k == 0 && !vis[now.x / k])
{
int tm = now.x / k;
q.push(node(tm, 0));
if(tm == 1) return cnt;
vis[tm] = 1;
}
if(now.f) i = t;
else i = 1;
for(; i <= t; i++)
{
if(now.x <= i) break;
if(vis[now.x - i]) continue;
int tm = now.x - i;
if(tm == 1) return cnt;
vis[tm] = 1;
q.push(node(tm, 1));
}
}
}
return -1;
}
int main()
{
int T, t, x, k;
scanf("%d", &T);
while(T--)
{
scanf("%d%d%d", &x, &k, &t);
int ans = bfs(x, k, t);
printf("%d\n", ans);
}
return 0;
}