Cod sursa(job #1727329)

Utilizator alittlezzCazaciuc Valentin alittlezz Data 10 iulie 2016 15:54:16
Problema Ordine Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.92 kb
#include <fstream>
#include <iostream>
#include <math.h>
#include <algorithm>

using namespace std;
#define ll long long
#define llu long long unsigned
#define pb push_back
#define mp make_pair

string problemName = "ordine";
string inFile = problemName+".in";
string outFile = problemName+".out";
ifstream fin(inFile.c_str());
ofstream fout(outFile.c_str());

int ap[26];

int main(){
    string s;
    fin>>s;
    int i,st,dr,nn;
    int n = s.size();
    for(i = 0;i < n;i++){
        ap[s[i]-'a']++;
    }
    nn = 0;
    string ans = "";
    string ans2 = "";
    char ch1,ch2;
    bool worstCase = false;
    for(st = 0;st < 26;st++){
        if(ap[st]){
            ch1 = st+'a';
            for(dr = st+1;dr < 26 && ap[st];dr++){
                if(ap[dr]){
                    ch2 = dr+'a';
                    for(;ap[st] > 1 && ap[dr];){
                        ans += ch1;
                        ans += ch2;
                        nn += 2;
                        ap[st]--;
                        ap[dr]--;
                    }
                }
                if(ap[st] == 1){
                    ap[st]--;
                    nn++;
                    ans += ch1;
                    break;
                }
            }
            if(ap[st] == 1){
                ap[st]--;
                nn++;
                ans += ch1;
            }
            if(ap[st]){
                worstCase = true;
                for(i = nn-1;i >= 0;i--){
                    if(ap[st]){
                        ans2 += ch1;
                        ap[st]--;
                    }
                    ans2 += ans[i];
                }
                if(ap[st]){
                    ans2 += ch1;
                }
            }
        }
    }
    if(worstCase){
        reverse(ans2.begin(), ans2.end());
        fout<<ans2;
    }else{
        fout<<ans;
    }
    return 0;
}