380C - Sereja and Brackets - CodeForces Solution


data structures schedules *2000

Please click on ads to support us..

Python Code:

import os,sys
from io import BytesIO, IOBase
from array import array
 
def construct(n,x,si):
    left = array('i',[0]*(si<<1))
    right = array('i',[0]*(si<<1))
    tree = array('i',[0]*(si<<1))
    for i in range(si,si+n):
        if x[i-si] == '(':
            left[i] = 1
        else:
            right[i] = 1
    a,b = si>>1,si
    while a:
        for i in range(a,b):
            z = min(left[i<<1],right[i<<1|1])
            tree[i] = tree[i<<1]+tree[i<<1|1]+2*z
            left[i] = left[i<<1]+left[i<<1|1]-z
            right[i] = right[i<<1]+right[i<<1|1]-z
        a,b = a>>1,b>>1
    return left,right,tree
 
def query(tree,left,right,l,r,si):
    l,r = l+si-1,r+si-1
    partl,partr = [],[]
    while l < r:
        if l&1:
            partl.append(l)
            l += 1
        if not r&1:
            partr.append(r)
            r -= 1
        l,r = l>>1,r>>1
    if l == r:
        partl.append(l)
    ans,le = 0,0
    for i in partl+partr[::-1]:
        tk = min(le,right[i])
        ans += 2*tk+tree[i]
        le += left[i]-tk
    return ans
 
def main():
    s = input().strip()
    n = len(s)
    si = 1<<n.bit_length()-(not n&n-1)
    left,right,tree = construct(n,s,si)
    for _ in range(int(input())):
        l,r = map(int,input().split())
        print(query(tree,left,right,l,r,si))
 
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
    main()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
class info
{
public:
	int open , close , full;
	info(int _open , int _close , int _full)
	{
		open = _open;
		close = _close;
		full = _full;
	}
	info()
	{
		open = 0;
		close = 0;
		full = 0;
	}

};

#define endl "\n"
#define ll long long
const int mod = 1000000007;

info merge(info left , info right)
{
	info ans = info(0 , 0 , 0);
	ans.full = left.full + right.full + min(left.open , right.close);
	ans.open = left.open + right.open - min(left.open , right.close);
	ans.close = left.close + right.close - min(left.open , right.close);
	return ans;

}
void build(int ind , int low , int high , string& s , info seg[])
{
	if (low == high)
	{
		seg[ind] = info(s[low] == '(' , s[low] == ')' , 0);
		return;
	}
	int mid = (low + high) / 2;
	build(2 * ind + 1 , low , mid , s , seg);
	build(2 * ind + 2 , mid + 1 , high , s , seg);
	seg[ind] = merge(seg[2 * ind + 1] , seg[2 * ind + 2]);
}
info query(int ind , int low, int high , int l , int r , info seg[])
{
	if (r < low ||  l > high) return info();
	if (low >= l && high <= r) return seg[ind];

	int mid = (low + high) >> 1;
	info left = query(2 * ind + 1 , low , mid , l , r , seg );
	info right = query(2 * ind + 2 , mid + 1 , high, l , r , seg );
	return merge(left , right);
}
void solve()
{
	string s;
	cin >> s;
	int n = s.size();
	info seg[4 * n];
	build(0 , 0 , n - 1 , s , seg);
	int q;
	cin >> q;
	while (q--)
	{
		int l , r;
		cin >> l >> r;
		l-- ; r--;
		info ans = query(0 , 0 , n - 1 , l , r , seg);
		cout << ans.full * 2 << endl;
	}

}

int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt"  , "r", stdin);
	freopen("output.txt" , "w", stdout);
#endif
	solve();
}


Comments

Submit
0 Comments
More Questions

352A - Jeff and Digits
1327A - Sum of Odd Integers
1276A - As Simple as One and Two
812C - Sagheer and Nubian Market
272A - Dima and Friends
1352C - K-th Not Divisible by n
545C - Woodcutters
1528B - Kavi on Pairing Duty
339B - Xenia and Ringroad
189A - Cut Ribbon
1182A - Filling Shapes
82A - Double Cola
45A - Codecraft III
1242A - Tile Painting
1663E - Are You Safe
1663D - Is it rated - 3
1311A - Add Odd or Subtract Even
977F - Consecutive Subsequence
939A - Love Triangle
755A - PolandBall and Hypothesis
760B - Frodo and pillows
1006A - Adjacent Replacements
1195C - Basketball Exercise
1206A - Choose Two Numbers
1438B - Valerii Against Everyone
822A - I'm bored with life
9A - Die Roll
1430B - Barrels
279B - Books
1374B - Multiply by 2 divide by 6