C. Unique Number

f:id:peroon:20201216183712p:plain

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    // input
    ll T; 
    cin>>T;
    
    map<ll,ll> mp;

    rep(f,1<<9){
      ll v=0;
      ll sum=0;
      rep(i,9){
        if(f>>i&1){
          v *= 10;
          v += (i+1);
          sum += (i+1);
        }
      }
      mp[sum]=v;
    }
    
    while(T--){
      ll v;cin>>v;
      if(mp.count(v)){
        p(mp[v]);
      }else{
        p(-1);
      }
    }

    return 0;
}

別解

  • editorialの通りにやるなら9~1の順に見ていって貪欲に採用すればいい
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    // input
    ll T; 
    cin>>T;
    
    while(T--){
      ll v;cin>>v;
      stringstream ss;
      for(int i=9; i>=1; i--){
        if(v>=i){
          v -= i;
          ss<<i;
        }
      }
      if(v==0){
        string s = ss.str();
        reverse(ALL(s));
        p(s);
      }else{
        p(-1);
      }
    }

    return 0;
}