Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code: A Simple RBS Problem

#include <bits/stdc++.h>

#define int long long

void solve() {
    int n;
    std::cin >> n;
    std::string s, t;
    std::cin >> s >> t;

    auto get1 = [&](std::string st) {
        std::vector<int> t1(n), t2;
        for (int i = 0; i < n; ++i) {
            if (st[i] == '(') {
                t2.push_back(i);
            } else {
                t1[t2.back()] = i;
                t1[i] = t2.back();
                t2.pop_back();
            }
        }

        int re = 0, l = 0, r = n - 1;
        while (l < r && t1[l] == r) {
            re++;
            l++;
            r--;
        }
        return re;
    };

    auto get2 = [&](std::string st) {
        int re = 0;
        for (int i = 0; i < n - 1; ++i) {
            if (st[i] == '(' && st[i + 1] == ')') {
                re++;
            }
        }
        return re;
    };

    std::cout << (get1(s) == get1(t) && get2(s) == get2(t) ? "YES\n" : "NO\n");
}

int32_t main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr), std::cout.tie(nullptr);

    int _ = 1;
    std::cin >> _;

    while (_--) {
        solve();
    }

    return 0;
}