Скоро Codeforces Round 1133 (Div. 1, Div. 2)! Регистрация здесь. ×

Блог пользователя ChitreshApte

Автор ChitreshApte, история, 5 лет назад, По-английски

We start with 0 and we have to reach n

We can perform 3 operations:

  1. Multiply the current number by 2 (cost p)

  2. Multiply the current number by 3 (cost q)

  3. Increase/Decrease the current number by 1 (cost r)

Find the min-cost to reach from 0 to n

Constraints:
10 testcases
1 <= n <= 10^18
1 <= p,q,r <= 10^9

Example:

n,p,q,r = 11,1,2,8

Answer : 20

Order: +1, *3, *2, *2, -1 = 8 + 2 + 1 + 1 + 8 = 20

  • Проголосовать: нравится
  • +17
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Maybe generate all natural x and y such that $$$2^x 3^y \leq n$$$. There exist only $$$O(log^2(n))$$$ such pairs. Get the minimum cost seeing the solution generated by each pair.

UPD: Not always the optimal strategy. By seeing the editorial provided in the comments below, it seems we should start backwards and either decrease until zero or decrease until find a multiple of 2 or 3 of the form $$$k \ floor(\frac{n}{k})$$$ or $$$k \ ceil(\frac{n}{k})$$$. So the solution is always of the form $$$\sum c_i + \sum 2^{a_j} 3^{b_j}$$$.

»
5 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится -9 Проголосовать: не нравится

I was mistaken I didn't see the contraints

»
5 лет назад, скрыть # |
 
Проголосовать: нравится -26 Проголосовать: не нравится

I guess you can simply use recursion. Just keeping check of the usage of +1/-1 will not give TLE. Something like this:

def cost(curr):
    if curr == 0:
        return 0 
    if curr%2!=0 and curr%3!=0:
        return cost(curr - 1) + r
    ans1,ans2 = 10**18,10**18
    if curr%2==0:
        ans1 = cost(curr//2) + p 
    if curr%3==0:
        ans2 = cost(curr//3) + q
    return min(ans1,ans2)
    
    
n = 10**18
p = 1
q = 2 
r = 8 
print(min(cost(n),cost(n+1)+r))
»
5 лет назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

This problem was asked in previous Atcoder round. i am sharing the link below

Problem Link : Pay to Win

Editorial : this