ProgMe

Untitled

Feb 7th, 2021
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int int64_t
  3.  
  4. using namespace std;
  5.  
  6. string compare(const string& a, string b)
  7. {
  8. sort(b.begin(), b.end(), greater<>());
  9. if(a > b)
  10. return "-1";
  11. multiset<char> can_use;
  12. for(auto i: b)
  13. can_use.insert(i);
  14. string ret;
  15. for(int i = 0; i < a.size(); i++){
  16. if(can_use.lower_bound(a[i]) == can_use.end()){
  17. do {
  18. can_use.insert(ret.back());
  19. ret.pop_back();
  20. i--;
  21. }while(can_use.upper_bound(a[i]) == can_use.end());
  22. ret.push_back(*can_use.upper_bound(a[i]));
  23. can_use.erase(can_use.upper_bound(a[i]));
  24. break;
  25. }
  26. ret.push_back(*can_use.lower_bound(a[i]));
  27. can_use.erase(can_use.lower_bound(a[i]));
  28. if(ret[i] != a[i])
  29. break;
  30. }
  31. while(!can_use.empty()){
  32. ret.push_back(*can_use.begin());
  33. can_use.erase(can_use.begin());
  34. }
  35. if(a >= ret)
  36. swap(ret.back(), ret[ret.size() - 2]);
  37. return ret;
  38. }
  39.  
  40. int32_t main() {
  41. ios_base::sync_with_stdio(false);
  42. cin.tie(nullptr); cout.tie(nullptr);
  43. int q;
  44. cin >> q;
  45. while(q--){
  46. int n;
  47. cin >> n;
  48. string prev;
  49. cin >> prev;
  50. sort(prev.begin(), prev.end());
  51. bool good = true;
  52. while(n-- > 1)
  53. {
  54. string now;
  55. cin >> now;
  56. now = compare(prev, now);
  57. if(now == "-1")
  58. {
  59. good = false;
  60. break;
  61. }
  62. prev = now;
  63. }
  64. if(!good)
  65. cout << "NO" << endl;
  66. else
  67. cout << "YES" << endl;
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment