Artifact Content
Not logged in

Artifact e2ad405452c3a39a7601f13daacffe55dc169abf


#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <complex>
#include <queue>
#include <stack>
#include <cmath>
#include <cassert>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef complex<LD> CMP;

class FoxAndHandle { public:
	string lexSmallestName(string S)
	{
		string cur = "";
		int p = 0;
		while(cur.size()*2<S.size()) {
			string next_best;
			int next_p = -1;
			for(int x=p; x<S.size(); ++x)
				if(possible(cur+S[x], x+1, S)) {
					if(next_p==-1 || next_best>cur+S[x])
						next_best=cur+S[x], next_p=x+1;
				}
			cur = next_best;
			p = next_p;
		}
		return cur;
	}

	bool possible(const string& used, int x, const string& S)
	{
		int freq[26] = {0};
		int pos[26] = {0};
		int tot[26] = {0};
		for(int i=0; i<used.size(); ++i)
			freq[used[i]-'a']++;
		for(int i=0; i<S.size(); ++i) {
			if(x<=i)
				pos[S[i]-'a']++;
			tot[S[i]-'a']++;
		}
		for(int c=0; c<26; ++c)
			if((freq[c]+pos[c])*2<tot[c] || freq[c]*2>tot[c])
				return false;
		return true;
	}
};

// BEGIN CUT HERE
#include <ctime>
double start_time; string timer()
 { ostringstream os; os << " (" << int((clock()-start_time)/CLOCKS_PER_SEC*1000) << " msec)"; return os.str(); }
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v)
 { os << "{ ";
   for(typename vector<T>::const_iterator it=v.begin(); it!=v.end(); ++it)
   os << '\"' << *it << '\"' << (it+1==v.end() ? "" : ", "); os << " }"; return os; }
void verify_case(const string& Expected, const string& Received) {
 bool ok = (Expected == Received);
 if(ok) cerr << "PASSED" << timer() << endl;  else { cerr << "FAILED" << timer() << endl;
 cerr << "\to: \"" << Expected << '\"' << endl << "\tx: \"" << Received << '\"' << endl; } }
#define CASE(N) {cerr << "Test Case #" << N << "..." << flush; start_time=clock();
#define END	 verify_case(_, FoxAndHandle().lexSmallestName(S));}
int main(){

CASE(0)
	string S = "foxfox"; 
	string _ = "fox"; 
END
CASE(1)
	string S = "ccieliel"; 
	string _ = "ceil"; 
END
CASE(2)
	string S = "abaabbab"; 
	string _ = "aabb"; 
END
CASE(3)
	string S = "bbbbaaaa"; 
	string _ = "bbaa"; 
END
CASE(4)
	string S = "fedcbafedcba"; 
	string _ = "afedcb"; 
END
CASE(5)
	string S = "nodevillivedon"; 
	string _ = "deilvon"; 
END
/*
CASE(6)
	string S = ; 
	string _ = ; 
END
CASE(7)
	string S = ; 
	string _ = ; 
END
*/
}
// END CUT HERE