primitive calculator

Problem Description
Task.
Given an integer n, compute the minimum number of operations needed to obtain the number n
starting from the number 1.
Input Format.
The input consists of a single integer 1 n 106.
Output Format.
In the rst line, output the minimum number k of operations needed to get n from 1.
In the second line output a sequence of intermediate numbers. That is, the second line should contain
positive integers a0; a2; : : : ; ak-1�� such that a0 = 1, ak��1 = n and for all 0 i < k �� 1, ai+1 is equal to
either ai + 1, 2ai, or 3ai. If there are many such sequences, output any one of them.

Sample 1.
Input:
1
Output:
0
1
Sample 2.
Input:
5
Output:
3
1 2 4 5
Sample 3.
Input:
96234
Output:
14
1 3 9 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234

a=int(input())
i=0
b=[]
#c=[]
b.append(0)
b.append(0)
#print(b)
for i in range(2,a+1):
    c=[]
    if i%3==0:
        c.append(int(i/3))
    if i%2== 0:
        c.append(int(i/2))
    c.append(i-1)
    #print(c)
    if i%3==0 and i%2==0:
        b.append(min(b[c[0]],b[c[1]],b[c[2]])+1)
    elif i%3==0 or i%2==0:
        b.append(min(b[c[0]],b[c[1]])+1)
    else:
        b.append(b[c[0]]+1)
    #print(b)
#print(min(c))
print(b[a])

用一个数组存储每一步的最优解,有三种一步到达i的方法,*3 和 *2 和 +1,对应每一个i,算出对应的i/3和i/2和i-1的最优解如果都为整数的话。取三个最优解的最小值,则到i的最优解+1即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值