読者です 読者をやめる 読者になる 読者になる

ICPC2012国内予選 Problem B繰り返す10進数

Problem B繰り返す10進数
http://www.psg.cs.titech.ac.jp/icpc/icpc2012/contest/B_ja.html
解法:最初のinputをstringで受け取り、ソートして最小最大を求める

#include<iostream>
#include<vector>
#include<string>
#include<sstream>


using namespace std;

inline int toInt(string s) {
    int v;
    istringstream sin(s);
    sin >> v;
    return v;
}
template <class T> inline string toString(T x) {
    ostringstream sout;
    sout << x;
    return sout.str();
}

int main() {
    string a0;
    int n;
    
    while (cin >> a0 >> n) {
        if(a0 == "0" && n == 0) break;
        
        while(a0.size() != n) {
            string tmp = a0;
            string s = "0";
            s += a0;
            a0 = s;
        }
        
        vector<int> data;
        int J=0,Ai=0,IJ=0;
        while (1) {
            //計算
            
            string A = a0;
            int tmp = toInt(A);
            data.push_back(tmp);
            //昇順
            sort(a0.begin(),a0.end());
            
            string min = a0;
            
            string max = "";
            for (int i=a0.size()-1; i >= 0; i--) {
                max += a0[i];
            }
            
            //cout << min << " " << max << endl;
            bool flag = false;
            int sa = toInt(max) - toInt(min);
            //cout << "sa" <<  sa << endl;
            for (int i=0; i < data.size(); i++) {
                //cout << sa << " " << data[i] << endl;
                if(sa == data[i]) {
                    flag = true;
                    J = i;
                    break;
                }
            }
            
            
            if(flag) {
                Ai = sa;
                IJ = data.size() - J;
                //cout << data.size() << endl;
                //cout << data.size() << " " << J << endl;
                break;
            }
            
            
            
            a0 = toString(sa);
            while(a0.size() != n) {
                string tmp = a0;
                string s = "0";
                s += a0;
                a0 = s;
            }
            
            
        }
        
        cout << J << " " << Ai << " " << IJ << endl;
        //cout << endl;
    }
    
    
}