ahu-563-3次幂分解

本文介绍了一种将十进制整数转换为三进制表示,并进一步转换为特定形式的算法实现。该算法使用队列和栈来辅助处理三进制数的每一位,通过特定规则简化表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值