Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector< vector<int> > let;
- vector<string> ans;
- bool check(int i, int it)
- {
- vector<int> curr = let[i];
- bool pref = true;
- for (int j = 0; j < it && pref; ++j)
- {
- if (curr[ans[i - 1][j] - 'a'] > 0)
- --curr[ans[i - 1][j] - 'a'];
- else
- pref = false;
- }
- if (!pref)
- return false;
- for (int j = it; j < ans[i - 1].size(); ++j)
- {
- int more = -1;
- for (int l = ans[i - 1][j] - 'a' + 1; l < let[i].size(); ++l)
- if (curr[l] > 0)
- more = l;
- if (more != -1)
- return true;
- if (curr[ans[i - 1][j] - 'a'] <= 0)
- return false;
- --curr[ans[i - 1][j] - 'a'];
- }
- return true;
- }
- void build(int i, int it)
- {
- for (int l = 0; l < it; ++l)
- ans[i] += ans[i - 1][l], --let[i][ans[i - 1][l] - 'a'];
- int more = -1;
- for (int l = ans[i - 1][it] - 'a' + 1; l < let[i].size(); ++l)
- if (let[i][l] > 0)
- {
- more = l;
- break;
- }
- if (more != -1 && let[i][more] > 0)
- {
- ans[i] += more + 'a';
- --let[i][more];
- }
- else if (let[i][ans[i - 1][it]] > 0)
- {
- ans[i] += ans[i - 1][it] + 'a';
- --let[i][ans[i - 1][it]];
- }
- for (int l = 0; l < let[i].size(); ++l)
- for (int k = 0; k < let[i][l]; ++k)
- ans[i] += l + 'a';
- }
- int main()
- {
- // freopen("A.in", "r", stdin);
- int n;
- cin >> n;
- let.resize(n, vector<int> (26, 0));
- ans.resize(n);
- for (int i = 0; i < n; ++i)
- {
- string curr;
- cin >> curr;
- if (i == 0)
- ans[0] = curr, sort(ans[i].begin(), ans[i].end());
- else
- for (int it = 0; it < curr.size(); ++it)
- ++let[i][curr[it] - 'a'];
- }
- bool bad = false;
- for (int i = 1; i < n && !bad; ++i)
- {
- int l = 0;
- int r = ans[i - 1].size() + 1;
- while(r - l != 1)
- {
- int m = l + (r - l) / 2;
- if (check(i, m))
- l = m;
- else
- r = m;
- }
- if (check(i, l))
- {
- build(i, l);
- }
- else
- bad = true;
- }
- if (bad)
- cout << -1;
- else
- for (int i = 0; i < n; ++i)
- cout << ans[i] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment