#include #include #include #include #include #include using namespace std; class BearPasswordLexic { public: string findPassword(vector x); }; string BearPasswordLexic::findPassword(vector x) { int i; int ws; /* Keeping track of the password size. */ int j; /* This is the largest index of x such that x[j] > 0 */ char c; /* We'll set this to 'a' or 'b' when building the password. */ string rv; /* The password (return value) */ string k; /* This helps us build the password */ map S; /* The map whose key is contiguous letters, and whose val is the number of substrings with thos letters. */ map ::iterator ait; /* Iterator for a's. */ map ::iterator bit; /* Iterator for b's. */ if (x[0] != (int) x.size()) return ""; /* We are going to build S. */ ws = 0; while (ws < x.size()) { /* Find j */ for (j = x.size()-1; j >= 0 && x[j] == 0; j--) ; if (j < 0) return ""; ws += (j+1); /* Add j's string to the map */ S[j+1]++; /* Now subtract out the j substring for all indices less than or equal to j */ i = 1; while (j >= 0) { if (x[j] < i) return ""; x[j] -= i; j--; i++; } } /* Double-check: If any elements of x are non-zero, then x was illegal */ for (i = 0; i < x.size(); i++) if (x[i] != 0) return ""; /* Build the return string. I'm setting ait to be an iterator to the high end of S, and bit to be an iterator to the low end. */ rv = ""; c = 'a'; ait = S.end(); ait--; bit = S.begin(); /* Build the password from S. The a's come from the high end, and the b's come from the low end. */ while (rv.size() < ws) { if (c == 'a') { k.clear(); k.resize(ait->first, 'a'); rv += k; ait->second--; if (ait->second == 0) ait--; c = 'b'; } else { k.clear(); k.resize(bit->first, 'b'); rv += k; bit->second--; if (bit->second == 0) bit++; c = 'a'; } } return rv; }