Fxx and game
Time Limit: 3000/1500 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 429 Accepted Submission(s): 102
Problem Description
Young theoretical computer scientist Fxx designed a game for his students.
In each game, you will get three integers X,k,t .In each step, you can only do one of the following moves:
1.X=X−i(0<=i<=t) .
2. if k|X,X=X/k .
Now Fxx wants you to tell him the minimum steps to make X become 1.
In each game, you will get three integers X,k,t .In each step, you can only do one of the following moves:
1.X=X−i(0<=i<=t) .
2. if k|X,X=X/k .
Now Fxx wants you to tell him the minimum steps to make X become 1.
Input
In the first line, there is an integer
T(1≤T≤20)
indicating the number of test cases.
As for the following T lines, each line contains three integers X,k,t(0≤t≤106,1≤X,k≤106)
For each text case,we assure that it's possible to make X become 1。
As for the following T lines, each line contains three integers X,k,t(0≤t≤106,1≤X,k≤106)
For each text case,we assure that it's possible to make X become 1。
Output
For each test case, output the answer.
Sample Input
2 9 2 1 11 3 3
Sample Output
4 3题意:青年理论计算机科学家Fxx给的学生设计了一款数字游戏。
一开始你将会得到一个数X,每次游戏将给定两个参数k,t, 任意时刻你可以对你的数执行下面两个步骤之一:
1.X=X−i(1<=i<=t)。
2.若X为k的倍数,X=X/k。
现在Fxx想要你告诉他最少的运行步骤,使X变成1。
方法:
单调队列维护dp 或者 bfs剪枝
这里就说说bfs剪枝:
操作2是不需要剪枝的,因为它的下一状态就一个
于是着手点在操作1,X的下一状态可以是X-t~X-1中的任意一种,有点多,我们是不是可以省掉一些状态呢?
可以的,对于X-t~X-1这些状态中,我们从小往大遍历,当遇到某一状态已经访问过,那我们就不再取该状态及之后状态
为什么呢?理由很简单,我们在步数少的情况下已经到达该状态,那之后的状态还留着干嘛用呢
#include<stdio.h> #include<iostream> #include<queue> using namespace std; #define N 1000005 struct node { int x,c; }now,we; int v[N]; int bfs(int x,int k,int t) { queue<node>q; if(k==1&&t) return (x+t-2)/t; int i,Min; node u; for(i=1;i<=x;i++) v[i]=0; now.x=x; now.c=0; q.push(now); v[x]=1; while(!q.empty()) { u=q.front(); q.pop(); if(u.x==1) return u.c; if(u.x%k==0&&!v[u.x/k]) { we.x=u.x/k; we.c=u.c+1; q.push(we); v[u.x/k]=1; } Min=min(t,u.x-1); for(i=Min;i>=1;i--) if(!v[u.x-i]) { we.x=u.x-i; we.c=u.c+1; q.push(we); v[u.x-i]=1; } else break;//剪枝 } } int main() { int T,X,k,t; scanf("%d",&T); while(T--) { scanf("%d%d%d",&X,&k,&t); printf("%d\n",bfs(X,k,t)); } return 0; }