(1)把n化成三进制;
(2)x位为0不考虑;
(3)x位为2考虑成3^(x+1)-3^x;为1考虑成3^x;
( 4 )还有一些细节消除多余项自己考虑。。。
#include<cstdio>
#include<queue>
#include<stack>
using namespace std;
int n,t;
long long thi[30];
int main()
{
scanf("%d",&t);
thi[0] = 1;
for(int i=1;i<=20;i++)
thi[i] = thi[i-1]*3;
while(t--)
{
bool sym = true;
scanf("%d",&n);
int n1 = n;
queue<int>qu;
stack<long long>ans;
while(n)
{
qu.push(n%3);
n/=3;
}
int ever = 0,i1 = 0;
while(qu.size())
{
int pre = qu.front();
qu.pop();
if(pre == 0);
else if(pre==2&&(ans.size()&&ans.top()==thi[i1]))
{
ans.pop();
ans.push(thi[i1+1]);
}
else if(pre==2)
{
ans.push(-1*thi[i1]);
ans.push(thi[i1+1]);
}
else if(pre==1&&(ans.size()&&ans.top()==thi[i1]))
{
ans.pop();
ans.push(-1*thi[i1]);
ans.push(thi[i1+1]);
}
else if(pre==1)
{
ans.push(thi[i1]);
}
ever = pre;
i1++;
}
i1 = 0;
if(sym)
{
printf("%d=",n1);
while(ans.size())
{
long long pre = ans.top();
ans.pop();
if(pre>=1&&i1)printf("+%I64d",pre);
else if(pre>=1)printf("%I64d",pre);
else printf("%I64d",pre);
i1++;
}
printf("\n");
}
else printf("Multiple Solutions\n");
}
return 0;
}