Zigu Zagu (Codeforces 1672H)
Tags: Greedy, data structures

You have a binary string $$$a$$$ of length $$$n$$$ consisting only of digits $$$0$$$ and $$$1$$$. You are given $$$q$$$ queries. In the $$$i$$$-th query, you are given two indices $$$l$$$ and $$$r$$$ such that $$$1 \le l \le r \le n$$$. Let $$$s=a[l,r]$$$. You are allowed to do the following operation on $$$s$$$:  Choose two indices $$$x$$$ and $$$y$$$ such that $$$1 \le x \le y \le |s|$$$. Let $$$t$$$ be the substring $$$t = s[x, y]$$$. Then for all $$$1 \le i \le |t| - 1$$$, the condition $$$t_i \neq t_{i+1}$$$ has to hold. Note that $$$x = y$$$ is always a valid substring.  Delete the substring $$$s[x, y]$$$ from $$$s$$$. For each of the $$$q$$$ queries, find the minimum number of operations needed to make $$$s$$$ an empty string.Note that for a string $$$s$$$, $$$s[l,r]$$$ denotes the subsegment $$$s_l,s_{l+1},\ldots,s_r$$$.

Input: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10 ^ 5$$$)  — the length of the binary string $$$a$$$ and the number of queries respectively.The second line contains a binary string $$$a$$$ of length $$$n$$$ ($$$a_i \in \{0, 1\}$$$).Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$)  — representing the substring of each query.

Output: Print $$$q$$$ lines, the $$$i$$$-th line representing the minimum number of operations needed for the $$$i$$$-th query.

Note: In the first test case,   The substring is $$$\texttt{101}$$$, so we can do one operation to make the substring empty.  The substring is $$$\texttt{11011}$$$, so we can do one operation on $$$s[2, 4]$$$ to make $$$\texttt{11}$$$, then use two more operations to make the substring empty.  The substring is $$$\texttt{011}$$$, so we can do one operation on $$$s[1, 2]$$$ to make $$$\texttt{1}$$$, then use one more operation to make the substring empty. 

Sample Inputs:
5 3
11011
2 4
1 5
3 5

10 3
1001110110
1 10
2 5
5 10

Sample Outputs:
1
3
2

4
2
3

Solution (Python):
import sys
input = sys.stdin.readline
(n, q) = map(int, input().split())
S = input().strip()
A = [0]
B = [0]
for i in range(n - 1):
    A.append(A[-1])
    B.append(B[-1])
    if S[i] == S[i + 1] == '1':
        A[-1] += 1
    if S[i] == S[i + 1] == '0':
        B[-1] += 1
for queries in range(q):
    (x, y) = map(int, input().split())
    print(max(A[y - 1] - A[x - 1], B[y - 1] - B[x - 1]) + 1)

Solution (Python):
import sys
I = lambda : [*map(int, sys.stdin.readline().split())]
(n, q) = I()
s = input()
ones = [0, 0]
zeroes = [0, 0]
for i in range(1, n):
    if s[i] == s[i - 1] == '0':
        zeroes.append(zeroes[-1] + 1)
    else:
        zeroes.append(zeroes[-1])
    if s[i] == s[i - 1] == '1':
        ones.append(ones[-1] + 1)
    else:
        ones.append(ones[-1])
for i in range(q):
    (l, r) = I()
    o = ones[r] - ones[l]
    z = zeroes[r] - zeroes[l]
    print(max(o, z) + 1)

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 0)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        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.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')
(n, q) = MII()
s = [int(x) for x in I()]
zeros = list(accumulate((s[i] == s[i + 1] == 0 for i in range(n - 1)), initial=0))
ones = list(accumulate((s[i] == s[i + 1] == 1 for i in range(n - 1)), initial=0))
outs = []
for _ in range(q):
    (l, r) = GMI()
    outs.append(max(zeros[r] - zeros[l], ones[r] - ones[l]) + 1)
print('\n'.join(map(str, outs)))