1709C - Recover an RBS - CodeForces Solution


constructive algorithms greedy implementation strings

Please click on ads to support us..

Python Code:

import sys

lines = sys.stdin.readlines()
cur_line = -1

def input():
    global lines, cur_line
    cur_line += 1
    return lines[cur_line][:-1]


for _ in range(int(input())):
    s = input()
    op = s.count('(')
    cl = s.count(')')
    q = s.count('?')

    toop = max(0, cl - op) + (len(s) - 2*max(op, cl)) // 2
    tocl = max(0, op - cl) + (len(s) - 2*max(op, cl)) // 2


    if min(toop, tocl) == 0:
        print("YES")
        continue
    
    t = list(s)
    inv = False
    for i in range(len(s)):
        if t[i] == '?':
            if toop > 1:
                toop -= 1
                t[i] = '('
            elif toop == 1 and not inv:
                inv = True
                t[i] = ')'
            elif toop > 0:
                t[i] = '('
                toop -= 1
            else:
                t[i] = ')'

    x = 0
    pos = True
    for c in t:
        if c == '(':
            x += 1
        else:
            x -= 1
        if x < 0:
            pos = False

    print("YES" if not pos else "NO")

C++ Code:

#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#define int long long
using namespace std;
const int N=200010;
bool flag[26];



void solve(){
	int n,k,cnt=0,q=0;
    string s;
    cin>>s;
    for (char c : s) {
        if (c == '(')cnt++;
        if (c == ')')cnt--;
        if (c == '?')q++;
        if (cnt + q == 1) {
            cnt = 1;
            q = 0;
        }
    }
    if (abs(cnt) == q) cout<<"YES\n";
    else cout<<"NO\n";
    return;
}
//(??)==>no    (?)(?)==>yes(()())
//?((?(???==>((()())
signed main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int T;
    cin>>T;
    while(T--){
        solve();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks
1251B - Binary Palindromes
768B - Code For 1
363B - Fence
991B - Getting an A
246A - Buggy Sorting
884A - Book Reading
1180A - Alex and a Rhombus
445A - DZY Loves Chessboard
1372A - Omkar and Completion
159D - Palindrome pairs
981B - Businessmen Problems
1668A - Direction Change
1667B - Optimal Partition
1668B - Social Distance
88B - Keyboard
580B - Kefa and Company
960A - Check the string
1220A - Cards
897A - Scarborough Fair
1433B - Yet Another Bookshelf
1283B - Candies Division
1451B - Non-Substring Subsequence
1408B - Arrays Sum
1430A - Number of Apartments
1475A - Odd Divisor
1454B - Unique Bid Auction
978C - Letters