CYLL has an integer-typed variable X whose initial value is 1. The variable can be updated in each step by applying either of the two operations:
Multiply the variable by a fixed integer K: X=X×K
Add an integer T (1≤T≤10) to the number: X=X+T
Given two integers N and K as inputs, can you help CYLL to decide the minimum number of steps required before she obtains the number N as the variable value?
Format of functions:
int FindMinSteps(int N, int K);
Here N (1≤N≤10
6
) is the target number and K (1≤K≤N) is the multiplication factor, which are integers as described in the problem specification.
The function is expected to return the minimum number of steps before the variable X reaches value N. (See the sample input/output for a concrete example.)
Sample program of judge:
#include <stdio.h>
int FindMinSteps(int N. int K)
int mian()
{
int N,K;
scanf("%d %d",&N,&K);
printf("%d", FindMinSteps(N, K));
return 0;
}
/* Implement the 'FindMinSteps' function here */
Sample input:
101 2
Sample output:
6
Sample explanation :
step 1: X=1+10=11
step 2: X=11∗2=22
step 3: X=22∗2=44
step 4: X=44+6=50
step 5: X=50∗2=100
step 6: X=100+1=101
Note that this is not the only way to reach 101 in 6 steps, however, we care about the minumum number of steps, which is unique, rather than how you reach there.
题目大概意思:输入n和k,从1开始,你有两种选择:加上1到10,或者乘以k。题目要求从1开始通过选择这两种方式,用最少的步骤达到n.输出步数。
int FindMinSteps(int N, int K)
{
int i,j,m;
int dp[1000005];
dp[1] = 0;
dp[2] = 1;
dp[3] = 1;
dp[4] = 1;
dp[5] = 1;
dp[6] = 1;
dp[7] = 1;
dp[8] = 1;
dp[9] = 1;
dp[10] = 1;
dp[11] = 1;//记录当N为前11时所需要的步数
for(i = 12; i<=N; i++)
{
m = dp[i-8];//这里m是i减1-10后所需步数,即返回上一步,这里i可减1-10;
if(i % K == 0 && K != 1)//当k为1时,不执行除K
{
m = dp[i/K];//当可以i除K时的,m为当N为i/k时所需的步数,即返回上一步
}
if(dp[i-1]<m) m = dp[i-1];
if(dp[i-2]<m) m = dp[i-2];
if(dp[i-3]<m) m = dp[i-3];
if(dp[i-4]<m) m = dp[i-4];
if(dp[i-5]<m) m = dp[i-5];
if(dp[i-6]<m) m = dp[i-6];
if(dp[i-7]<m) m = dp[i-7];
if(dp[i-8]<m) m = dp[i-8];
if(dp[i-9]<m) m = dp[i-9];
if(dp[i-10]<m) m = dp[i-10];//判断i减1-10和i/k谁步数更小
dp[i] = m + 1;
}
return dp[N];
}