Variable Manipulation (35分)

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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值