链接:https://codeforces.com/contest/1249/problem/C2

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

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

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

For example:

  • 3030 is a good number: 30=33+3130=33+31,
  • 11 is a good number: 1=301=30,
  • 1212 is a good number: 12=32+3112=32+31,
  • but 22 is not a good number: you can't represent it as a sum of distinct powers of 33 (2=30+302=30+30),
  • 1919 is not a good number: you can't represent it as a sum of distinct powers of 33 (for example, the representations 19=32+32+30=32+31+31+31+3019=32+32+30=32+31+31+31+30 are invalid),
  • 2020 is also not a good number: you can't represent it as a sum of distinct powers of 33 (for example, the representation 20=32+32+30+3020=32+32+30+30 is invalid).

Note, that there exist other representations of 1919 and 2020 as sums of powers of 33 but none of them consists of distinct powers of 33.

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

You have to answer qq independent queries.

Input

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

The only line of the query contains one integer nn (1≤n≤10181≤n≤1018).

Output

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

Example

input

Copy

8
1
2
6
13
14
3620
10000
1000000000000000000

output

Copy

1
3
9
13
27
6561
19683
1350851717672992089

题解:听说这题用3进制做但本人很菜,只能想到下面这个很蠢的办法呜呜呜

代码:

#include<bits/stdc++.h>
using namespace std;
unsigned long long t,n,x1,x2,s,k,j,min1,w;
long long qpow(long long a,long long n)//计算a^n % mod
{
    long long re = 1;
    while(n)
    {
        if(n & 1)//判断n的最后一位是否为1
            re = (re * a) ;
        n >>= 1;//舍去n的最后一位
        a = (a * a) ;//将a平方
    }
    return re ;
}
int main()
{
	cin>>t;
	while(t--)
	{
		cin>>n;
		//memset(a,0,sizeof(a));
		if(qpow(3,(long long)log(n)/log(3))==n)
		j=log(n)/log(3);
		else
		{
			j=log(n)/log(3);
			j++;
		}
		min1=qpow(3,j);
		//k=pow(3,j-1);
		//cout<<min1<<endl;
		for(int i=j-1;i>=0;i--)
		{
			w=0;
			int flag=0;
			for(int l=i;l>=0;l--)
			{
				w+=qpow(3,l);
				if(w>=n)
				{
					flag=1;
					if(w<min1)
					min1=w;
					w-=qpow(3,l);
				}
			}
			if(flag==0)
			break;
		}
		
		cout<<min1<<endl;
	}
}