codeforces - 1249C2 Good Numbers (hard version)

题目链接:https://vjudge.net/problem/CodeForces-1249C2

题目描述:

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 (nmn≤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 (1q5001≤q≤500) — the number of queries. Then qq queries follow.

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

Output

For each query, print such smallest integer mm (where nmn≤m) that mm 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的数,这个数由3个不同次幂组成(即对于每个3的n次幂最多用一次)
我们可以让一个数从3的0次幂一直加到大于等于这个数,然后在从3的高次幂开始减,为什么不倒着减呢
因为一个数的高次幂肯定大于它的所有低次幂之和,所以如果倒着减可能会出来更大的数
#include<set>
#include
#include
#include
#include
#include
#include
#include<string>
#include
#include
#include
#include
#include
#include
#define endl '\n'
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define mst(a) memset(a, 0, sizeof(a))
#define IOS ios::sync_with_stdio(false)
#define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const double pi = acos(-1.0);
const double eps = 1e-7;
const ll MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
const int _NAN = -0x3f3f3f3f;
const int NIL = -1;
const int maxn = 2e3;
ll _ls[40] = {1};
int main(void) {
    int t;
    scanf("%d", &t);
    for (int i = 1; i<40; ++i)
        _ls[i] = _ls[i-1]*3;
    while(t--) {
        ll n, sum = 0;
        scanf("%lld", &n);
        int kase = 0;
        while(sum < n)
            sum += _ls[kase++];
        while(kase--)
            if (sum-_ls[kase] >= n)
                sum -= _ls[kase];
        printf("%lld\n", sum);
    }
    return 0;
}

 

你可能感兴趣的:(codeforces - 1249C2 Good Numbers (hard version))