↓あとで (accepted in practice)
class FoxAndHandle { public: string lexSmallestName(string S) { int N=S.size(); VVI hi(N+1, VI(256)); REP(i, N) { hi[N-1-i] = hi[N-1-i +1]; hi[N-1-i][S[N-1-i]]++; } string Hs; { VI w(256); REP(i, N) w[S[i]]++; REP(i, 256) { while(w[i]) { Hs.PB((char)i); w[i]-=2; } } } string H; int Si = 0; while(Hs.size()) { VI lhi(256); REP(j, Hs.size()) lhi[Hs[j]]++; REP(k, Hs.size()) { int idx=0; RANGE(i, Si, N) if(S[i]==Hs[k]) {idx=i;break;} int ok=1; REP(j, 256) if(hi[idx][j]<lhi[j]) ok=0; if(ok) { H.PB(Hs[k]); string nHs; int removed=0; REP(z, Hs.size()) { if(!removed && Hs[k]==Hs[z]) removed=1; else nHs.PB(Hs[z]); } Hs=nHs; //Si=idx; // だめ Si=idx+1; // OK break; } } } return H; } };