贪心
题解:贪心
首先,如果,那么显然,操作2无法使变小,我们只能使用操作1,因此直接输出即可。
如果,那么我们一定是尽可能的需要多使用操作2,因为每次使用操作2,都可以让减少的数字
因此步骤如下:
步骤1:如果不是的倍数,首先将减小至的倍数,也就是,然后进入步骤2。
步骤2:如果此时执行完操作2,仍然有,那么就可以执行操作2,然后再次回到步骤1,否则去执行步骤3即可。
步骤3:执行操作1,直到等于,执行结束。
C++
#include<bits/stdc++.h> using namespace std; int x,y,k; int main(){ cin>>x>>y>>k; if(k==1){ //只能执行操作1 cout<<x-y<<endl; } else{ int res=0; while(x>y){ if(x/k>=y){ res+=x%k; //执行步骤1 x/=k; //执行步骤2 res++; } else{ //执行步骤3 res+=x-y; x=y; } } cout<<res<<endl; } return 0; }
Java
import java.util.Scanner; public class Main { static int x, y, k; public static void main(String[] args) { Scanner sc = new Scanner(System.in); x = sc.nextInt(); y = sc.nextInt(); k = sc.nextInt(); if (k == 1) { // 只能执行操作1 System.out.println(x - y); } else { int res = 0; while (x > y) { if (x / k >= y) { res += x % k; // 执行步骤1 x /= k; // 执行步骤2 res++; } else { // 执行步骤3 res += x - y; x = y; } } System.out.println(res); } sc.close(); } }
Python
x, y, k = map(int, input().split()) if k == 1: # 只能执行操作1 print(x - y) else: res = 0 while x > y: if x // k >= y: res += x % k # 执行步骤1 x //= k # 执行步骤2 res += 1 else: # 执行步骤3 res += x - y x = y print(res)