Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define int int64_t
- using namespace std;
- string compare(const string& a, string b)
- {
- sort(b.begin(), b.end(), greater<>());
- if(a > b)
- return "-1";
- multiset<char> can_use;
- for(auto i: b)
- can_use.insert(i);
- string ret;
- for(int i = 0; i < a.size(); i++){
- if(can_use.lower_bound(a[i]) == can_use.end()){
- do {
- can_use.insert(ret.back());
- ret.pop_back();
- i--;
- }while(can_use.upper_bound(a[i]) == can_use.end());
- ret.push_back(*can_use.upper_bound(a[i]));
- can_use.erase(can_use.upper_bound(a[i]));
- break;
- }
- ret.push_back(*can_use.lower_bound(a[i]));
- can_use.erase(can_use.lower_bound(a[i]));
- if(ret[i] != a[i])
- break;
- }
- while(!can_use.empty()){
- ret.push_back(*can_use.begin());
- can_use.erase(can_use.begin());
- }
- if(a >= ret)
- swap(ret.back(), ret[ret.size() - 2]);
- return ret;
- }
- int32_t main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr); cout.tie(nullptr);
- int q;
- cin >> q;
- while(q--){
- int n;
- cin >> n;
- string prev;
- cin >> prev;
- sort(prev.begin(), prev.end());
- bool good = true;
- while(n-- > 1)
- {
- string now;
- cin >> now;
- now = compare(prev, now);
- if(now == "-1")
- {
- good = false;
- break;
- }
- prev = now;
- }
- if(!good)
- cout << "NO" << endl;
- else
- cout << "YES" << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment