A-可达鸭数学

题目链接
A-可达鸭数学_第1张图片

示例1
输入

9
1
-1
0
6
54
-8
520
1907
-2023

输出

w
m
b
wmb
wmbbb
mbw
wmbwwmw
wbmbmmbm
mbwmbbwm

备注:

请注意,在可达鸭数学里是没有负号的。

请注意,不要输出多余的前导b,否则会被判Wrong Answer。(例如,虽然mwbmwbbbmw表示的是同一个数,但输出bmwbbbmw会被判Wrong Answer

题解:

首先是十进制转三进制,但由于转出来的有系数为2的
通过关系判断出公式: a ∗ 3 x = ( a − 3 ) ∗ 3 x + 3 x + 1 a*3^x=(a-3)*3^x+3^{x+1} a3x=(a3)3x+3x+1
就可以把2换成-1 2 ∗ 3 x = ( − 1 ) ∗ 3 x + 3 x + 1 2*3^x=(-1)*3^x+3^{x+1} 23x=(1)3x+3x+1

#include 
using namespace std;
void solve();
const int N = 1e6+10;
int idx;
int a[N];
void f(int x){
    if(!x){a[idx++]=0;return;}
    a[idx++]=x%3;//由于要转换,需要调整位置
    f(x/3);
}
bool fu;
int n;
void solve(){
    idx=0;
    cin>>n;
    fu=n<0;
    if(fu)n=-n;
    
    f(n);
    for(int i=0;i<idx;i++){
        while(a[i]!=-1&&a[i]!=0&&a[i]!=1){
            a[i]-=3,a[i+1]+=1;
            if(i+1>idx)idx=i;//更新最高位所在位置
        }
    }
    bool flag=false;
    if(idx==1&&a[0]==0){putchar('b');puts("");return ;}//特判
    for(int i=idx-1;i>=0;i--){
        if(a[i]!=0)flag=true;
        if(!flag&&a[i]==0)continue;//去掉前面的b
        if(fu&&a[i]==1)a[i]=-1;
        else if(fu&&a[i]==-1)a[i]=1;
        if(a[i]==-1)printf("m");
        else
        printf("%c","bw"[a[i]]);
    }
    puts("");
}
int main(){
    int _=1;
    cin>>_;
    while(_--)solve();
}

你可能感兴趣的:(c++,算法)