【AtCoder-4152】解题报告(数学,进制,贪心)

原始题目

C - Strange Bank

  • Time limit : 2sec
  • Memory limit : 256MB
  • Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 62(=36) yen, 63(=216) yen, ...

9 yen, 92(=81) yen, 93(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1≤N≤100000 N is an integer. ### Input Input is given from Standard Input in the following format:

N ### Output If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4
  • By withdrawing 1 yen, 9 yen, 36(=62) yen and 81(=92) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3
  • By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16

题目大意

规定三种取钱的方法,一次可以取1元,6k元或者9k元 (k>=1) ,问取n元最少的次数是多少。

解题思路

将n拆成i和n-i。分别用6和9进制表示,维护系数和最小值即可。

解题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <cstdio>
#include <iostream>
using namespace std;

int n;
int main()
{
while(~scanf("%d" ,&n))
{
int res=n; //最大情况肯定为n次 全部每次取1元
for(int i=0;i<=n;i++)
{
int cc=0;
int t=i;
while(t) cc+=t%6,t/=6; //计算6进制的系数和
t=n-i;
while(t) cc+=t%9,t/=9; //计算9进制的系数和
if(res>cc) res=cc;

}
printf("%d\n",res);
}

}

收获与反思

  • 理解题意,三种方法算最小值其实就是求一个数用6/9进制混合表达的系数最小值。
  • 把n拆成两部分,维护系数最小值。

    while(t) cc+=t%k,t/=k;

  • 该方法得到的cc为t用k进制表达的系数和。