Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- string comp(string one, string other)
- {
- bitset <1000> used{};
- sort(other.begin(), other.end(), greater<>());
- if(one >= other)
- return "-1";
- string ret = other, pref;
- reverse(other.begin(), other.end());
- int idx = 0;
- while(one.size() - idx)
- {
- int idx_eq = -1, idx_gr = -1;
- for(int i = 0; i < other.size(); i++)
- {
- if(!used[i])
- {
- if(other[i] == one[idx] && idx_eq == -1)
- idx_eq = i;
- if(other[i] > one[idx] && idx_gr == -1)
- idx_gr = i;
- }
- if(idx_eq != -1 && idx_gr != -1)
- break;
- }
- if(idx_gr != -1)
- {
- string chg = pref;
- chg += other[idx_gr];
- for(int i = 0; i < other.size(); i++)
- if(!used[i] && i != idx_gr)
- chg += other[i];
- ret = min(ret, chg);
- }
- if(idx_eq != -1)
- {
- pref += one[idx];
- idx ++;
- used[idx_eq] = true;
- }
- else
- break;
- }
- if(!(one.size() - idx))
- {
- for(int i = 0; i < other.size(); i++)
- if(!used[i])
- pref += other[i];
- return pref;
- }
- else
- return ret;
- }
- int32_t main() {
- int q;
- cin >> q;
- while(q--)
- {
- int n;
- cin >> n;
- string prev;
- cin >> prev;
- sort(prev.begin(), prev.end());
- bool ok = true;
- while(n-- > 1)
- {
- string now;
- cin >> now;
- now = comp(prev, now);
- if(now == "-1")
- {
- ok = false;
- break;
- }
- prev = now;
- }
- cout << (ok ? "YES\n" : "NO\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment