Official

C - Many Balls Editorial by en_translator


Suppose that every Spell \(A\) creates a different color of balls.
Also, suppose that Spell \(B\) preserves each color of balls when duplicated.

Assume that the \(i\)-th character of \(S\) is A, by which a blue ball is added.
Denoting yb \(k\) the number of B contained in \((i+1)\)-th and succeeding characters of \(S\), then there will be ultimately \(2^k\) blue balls.

Therefore, if we could decompose as \(N=2^p+2^q+2^r+\cdots\), based on this we can construct an \(S\) (of length not necessarily at most \(120\)).

Therefore, we can construct in the following way.

Let \(ans\) be a concatenation of \(60\) copies of B’s.
Let \(A\) be the binary notation of \(N\).

Inspect each digit of \(A\) in order, the most significant one first, performing the following operation:

  • If the \(2^k\)’s place is 1, then insert A to such position of \(ans\) that there are \(k\) number of B’s after the position

Since \(10^{18} \lt 2^{60}\), the number of digits is at most \(60\).
Therefore, the length of \(ans\) is at most \(120\), which satisfies the constraints.

Sample code in C++:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

signed main(){
    ll n;cin>>n;
    const ll len=60;
    auto a=bitset<len>(n);
    string ans(len,'B');
    for(ll i=len-1;i>=0;i--){
        if(a[i]==1){
            ans.insert(ans.size()-i,"A");
        }
    }
    cout<<ans<<endl;
    return 0;
}

posted:
last update: