fork download
  1. #include <bits/stdc++.h>
  2. #define all(x) (x).begin(), (x).end()
  3. #define ll long long
  4. using namespace std;
  5.  
  6. int main() {
  7. ios_base::sync_with_stdio(false);
  8. cin.tie(nullptr);
  9.  
  10. int t;
  11. cin >> t;
  12. while (t--) {
  13. int n;
  14. cin >> n;
  15. string a, b;
  16. cin >> a >> b;
  17.  
  18. int to = 0;
  19. for (int i = 0; i < n; ++i) {
  20. if (a[i] == '(') ++to;
  21. if (b[i] == '(') ++to;
  22. }
  23.  
  24. if (to != n) {
  25. cout << "NO\n";
  26. continue;
  27. }
  28.  
  29. int ba = 0, bb = 0;
  30. bool ok = true;
  31. for (int i = 0; i < n; ++i) {
  32. char x = a[i], y = b[i];
  33. if (x == '(' && y == '(') {
  34. ++ba; ++bb;
  35. } else if (x == ')' && y == ')') {
  36. --ba; --bb;
  37. } else {
  38. if (ba <= bb) {
  39. ++ba; --bb;
  40. } else {
  41. --ba; ++bb;
  42. }
  43. }
  44. if (ba < 0 || bb < 0) {
  45. ok = false;
  46. break;
  47. }
  48. }
  49.  
  50. if (ok && ba == 0 && bb == 0) cout << "YES\n";
  51. else cout << "NO\n";
  52. }
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 5316KB
stdin
7
2
()
()
4
))((
(())
4
((((
))))
4
()()
(())
6
(((())
()()))
8
()()()()
(((())))
4
((((
((((
stdout
YES
NO
NO
YES
YES
YES
NO