Codeforces Round #595 (Div. 3) C2. Good Numbers (hard version)

C2. Good Numbers (hard version)

The only difference between easy and hard versions is the maximum value of n.

You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.

The positive integer is called good if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).

For example:

30 is a good number: 30=33+31,
1 is a good number: 1=30,
12 is a good number: 12=32+31,
but 2 is not a good number: you can’t represent it as a sum of distinct powers of 3 (2=30+30),
19 is not a good number: you can’t represent it as a sum of distinct powers of 3 (for example, the representations 19=32+32+30=32+31+31+31+30 are invalid),
20 is also not a good number: you can’t represent it as a sum of distinct powers of 3 (for example, the representation 20=32+32+30+30 is invalid).
Note, that there exist other representations of 19 and 20 as sums of powers of 3 but none of them consists of distinct powers of 3.

For the given positive integer n find such smallest m (n≤m) that m is a good number.

You have to answer q independent queries.

Input

The first line of the input contains one integer q (1≤q≤500) — the number of queries. Then q queries follow.

The only line of the query contains one integer n (1≤n≤10^18).

Output

For each query, print such smallest integer m (where n≤m) that m is a good number.

Example

input

8
1
2
6
13
14
3620
10000
1000000000000000000

output

1
3
9
13
27
6561
19683
1350851717672992089

不难发现,当n的三进制中仅含0和1时n一定为好数,然后我手写了一个模拟三进制加减法,由于python对字符串好操作一些,就没写C++,额,如果拿我代码提交的话要把注释去掉,否则会CE,AC代码如下:

def f(n,x):#将n转化为x进制的数
    ss=''
    a=['0','1','2','3','4','5','6','7','8','9']
    b=[]
    while True:
        s=n//x
        y=n%x
        b=b+[y]
        if s==0:
            break
        n=s
    b.reverse()
    for i in b:
       ss+=a[i]
    return(ss)

q=int(input())
for i in range(0,q):
    n=int(input())
    s=list(f(n,3))#一定要将字符串转化为list,因为python中不可以对字符串直接操作
    l=len(s)
    ss=''
    for i in range(l-1,-1,-1):#模拟三进制加减法找接近n的m,注意并不是最近的
        if s[i]=='1' or s[i]=='0':
            ss+=s[i]
        else:
            ss+='0'
            s[i-1]=str(ord(s[i-1])-ord('0')+1)
    if s[0]=='2' or s[0]=='3':
        ss+='1';
    ans=0
    ll=len(ss)
    if ll>l:#当找到的位数大于原来的时,即只用保留第一个1,后面全部当0处理,此时一定最接近
        ans+=pow(3,ll-1)
    else:#另一种情况就从前往后一位一位地把三进制转十进制,一旦大于n就退出即可,此时也一定是最近的
        for i in range(ll-1,-1,-1):
            if ans>=n:
                break
            ans+=pow(3,i)*(ord(ss[i])-ord('0'))
    print(ans)

你可能感兴趣的:(模拟,Codeforces,进制转换)