http://codeforces.com/problemset/problem/1249/C2
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 mm 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≤1018 ).
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 1000000000000000000Output
1 3 9 13 27 6561 19683 1350851717672992089
题意:一个数n,求比n大的最小数,满足是3的任意次幂之和,且3的幂指数都不能相同,
思路:转换为三进制问题,每位数只能是0或1,(保证不重复),
#include<stdio.h>
#include<string.h>
#include<algorithm>
typedef long long ll;
const int N=1e5+10;
using namespace std;
ll a[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ll n;
memset(a,0,sizeof(a));
scanf("%lld",&n);
ll nn=n,k=0;
while(nn)
{
a[k++]=nn%3;
nn/=3;
}
int flag=-1;
for(int i=0; i<k; i++)
{
if(a[i]>=2)
{
flag=i;
a[i]=0;
a[i+1]++;
}
}
if(flag!=-1)///yao min
for(int i=0; i<flag; i++)
a[i]=0;
ll ans=0,res=1;
for(int i=0; i<=k; i++)
{
ans+=res*a[i];
res*=3;
}
printf("%lld\n",ans);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
typedef long long ll;
const int N=1e5+10;
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ll n;
scanf("%lld",&n);
vector<int>v;///!!!qing kong
while(n)
{
v.push_back(n%3);
n/=3;
}
v.push_back(0);
int i;
for(i=v.size()-1; i>=0; i--)
{
if(v[i]==2)
break;
}
if(i!=-1)
{
for(int j=0; j<=i; j++)
v[j]=0;
for(int j=i+1; j<v.size(); j++)
{
if(v[j]==0)
{
v[j]=1;
break;
}
else
v[j]=0;
}
}
ll ans=0,res=1;
for( i=0; i<v.size(); i++)
{
ans+=res*v[i];
res*=3;
}
printf("%lld\n",ans);
}
return 0;
}