Nezzar and Binary String (Codeforces 1477B)
Tags: Greedy, data structures

Nezzar has a binary string $$$s$$$ of length $$$n$$$ that he wants to share with his best friend, Nanako. Nanako will spend $$$q$$$ days inspecting the binary string. At the same time, Nezzar wants to change the string $$$s$$$ into string $$$f$$$ during these $$$q$$$ days, because it looks better.It is known that Nanako loves consistency so much. On the $$$i$$$-th day, Nanako will inspect a segment of string $$$s$$$ from position $$$l_i$$$ to position $$$r_i$$$ inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.After this inspection, at the $$$i$$$-th night, Nezzar can secretly change strictly less than half of the characters in the segment from $$$l_i$$$ to $$$r_i$$$ inclusive, otherwise the change will be too obvious.Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string $$$f$$$ at the end of these $$$q$$$ days and nights.

Input: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases.The first line of each test case contains two integers $$$n,q$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$).The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$.The third line of each test case contains a binary string $$$f$$$ of length $$$n$$$.Then $$$q$$$ lines follow, $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le n$$$)  — bounds of the segment, that Nanako will inspect on the $$$i$$$-th day.It is guaranteed that the sum of $$$n$$$ for all test cases doesn't exceed $$$2 \cdot 10^5$$$, and the sum of $$$q$$$ for all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output: For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string $$$f$$$ at the end of $$$q$$$ days and nights. Otherwise, print "NO".You can print each letter in any case (upper or lower).

Note: In the first test case, $$$\underline{00000} \rightarrow \underline{000}11 \rightarrow 00111$$$ is one of the possible sequences of string changes.In the second test case, it can be shown that it is impossible to have the string $$$f$$$ at the end.

Sample Inputs:
4
5 2
00000
00111
1 5
1 3
2 1
00
01
1 2
10 6
1111111111
0110001110
1 10
5 9
7 10
1 7
3 5
6 10
5 2
10000
11000
2 5
1 3

Sample Outputs:
YES
NO
YES
NO

Solution (Python):
import os, sys
from io import BytesIO, IOBase

def construct(n, x, si):
    tree = [0] * (si << 1)
    for i in range(si, si + n):
        tree[i] = x[i - si]
    (a, b) = (si >> 1, si)
    while a:
        for i in range(a, b):
            tree[i] = tree[i << 1] + tree[i << 1 | 1]
        (a, b) = (a >> 1, b >> 1)
    return tree

def build(tree, lazy, le, pos):
    pos >>= 1
    while pos:
        tree[pos] = lazy[pos] * le[pos] if lazy[pos] != -1 else tree[pos << 1] + tree[pos << 1 | 1]
        pos >>= 1

def apply(tree, lazy, le, pos, val):
    tree[pos] = val * le[pos]
    if pos < len(lazy):
        lazy[pos] = val

def push(tree, lazy, le, pos, h):
    for s in range(h, 0, -1):
        ne = pos >> s
        if lazy[ne] != -1:
            apply(tree, lazy, le, ne << 1, lazy[ne])
            apply(tree, lazy, le, ne << 1 | 1, lazy[ne])
            lazy[ne] = -1

def update(tree, lazy, le, l, r, val, si, h):
    (l, r) = (l + si - 1, r + si - 1)
    (l0, r0) = (l, r)
    push(tree, lazy, le, l, h)
    push(tree, lazy, le, r, h)
    while l < r:
        if l & 1:
            apply(tree, lazy, le, l, val)
            l += 1
        if not r & 1:
            apply(tree, lazy, le, r, val)
            r -= 1
        (l, r) = (l >> 1, r >> 1)
    if l == r:
        apply(tree, lazy, le, l, val)
    build(tree, lazy, le, l0)
    build(tree, lazy, le, r0)

def query(tree, lazy, le, l, r, si, h):
    (l, r, ans) = (l + si - 1, r + si - 1, 0)
    push(tree, lazy, le, l, h)
    push(tree, lazy, le, r, h)
    while l < r:
        if l & 1:
            ans += tree[l]
            l += 1
        if not r & 1:
            ans += tree[r]
            r -= 1
        (l, r) = (l >> 1, r >> 1)
    if l == r:
        return ans + tree[l]
    return ans

def main():
    for _ in range(int(input())):
        (n, q) = map(int, input().split())
        (s, f) = (list(map(int, input())), list(map(int, input())))
        h = n.bit_length() - (not n & n - 1)
        si = 1 << h
        tree = construct(n, f, si)
        le = construct(n, [1] * n, si)
        lazy = [-1] * si
        for (l, r) in reversed([tuple(map(int, input().split())) for _ in range(q)]):
            su = query(tree, lazy, le, l, r, si, h)
            if 2 * su < r - l + 1:
                update(tree, lazy, le, l, r, 0, si, h)
            elif 2 * su == r - l + 1:
                print('NO')
                break
            else:
                update(tree, lazy, le, l, r, 1, si, h)
        else:
            for i in range(si):
                if lazy[i] != -1:
                    apply(tree, lazy, le, i << 1, lazy[i])
                    apply(tree, lazy, le, i << 1 | 1, lazy[i])
                    lazy[i] = -1
            if tree[si:si + n] == s:
                print('YES')
            else:
                print('NO')
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()

Solution (Python):
import sys, io, os
if os.environ['USERNAME'] == 'kissz':
    inp1 = inp2 = open('in.txt', 'r').readline

    def debug(*args):
        print(*args, file=sys.stderr)
else:
    inp1 = inp2 = sys.stdin.readline

    def debug(*args):
        pass

class lazytree:

    def __init__(self, array):
        n = len(array) - 1
        i = 1
        while n:
            n >>= 1
            i += 1
        self.tree = [0] * (2 ** (i - 1) - 1) + array + [0] * (2 ** (i - 1) - len(array))
        self.l = 0
        self.r = 2 ** (i - 1) - 1
        self.lazy = [0] * (2 ** i - 1)
        self.lazyval = [0] * (2 ** i - 1)
        for i in range(2 ** (i - 1) - 2, -1, -1):
            self.tree[i] = self.tree[2 * i + 1] + self.tree[2 * i + 2]

    def query(self, l, r):
        if l == self.l and r == self.r:
            parents = []
            children = [(0, l, r)]
        else:
            parents = [(0, self.l, self.r)]
            children = []
            i = 0
            while i < len(parents):
                (loc, L, R) = parents[i]
                left = (loc * 2 + 1, L, L + (R - L + 1) // 2 - 1)
                right = (loc * 2 + 2, L + (R - L + 1) // 2, R)
                if self.lazy[loc]:
                    self.lazy[loc] = 0
                    self.tree[left[0]] = self.tree[right[0]] = (left[2] - left[1] + 1) * self.lazyval[loc]
                    self.lazy[left[0]] = self.lazy[right[0]] = 1
                    self.lazyval[left[0]] = self.lazyval[right[0]] = self.lazyval[loc]
                if l <= left[1] and left[2] <= r:
                    children.append(left)
                elif left[1] <= l <= left[2] or left[1] <= r <= left[2]:
                    parents.append(left)
                if l <= right[1] and right[2] <= r:
                    children.append(right)
                elif right[1] <= l <= right[2] or right[1] <= r <= right[2]:
                    parents.append(right)
                i += 1
        ones = sum((self.tree[child[0]] for child in children))
        zeros = r - l + 1 - ones
        if ones == zeros:
            return -1
        elif ones > zeros:
            for child in children:
                self.tree[child[0]] = child[2] - child[1] + 1
                self.lazy[child[0]] = 1
                self.lazyval[child[0]] = 1
        else:
            for child in children:
                self.tree[child[0]] = 0
                self.lazy[child[0]] = 1
                self.lazyval[child[0]] = 0
        for (i, _, _) in reversed(parents):
            self.tree[i] = self.tree[2 * i + 1] + self.tree[2 * i + 2]
        return self.tree[child[0]]

    def get_all(self):
        n = self.r - self.l
        for i in range(n):
            if self.lazy[i]:
                self.lazy[i] = 0
                self.tree[2 * i + 1] = self.tree[2 * i + 2] = self.lazyval[i]
                self.lazy[2 * i + 1] = self.lazy[2 * i + 2] = 1
                self.lazyval[2 * i + 1] = self.lazyval[2 * i + 2] = self.lazyval[i]
        return self.tree[n:]
for _ in range(int(inp2())):
    (n, q) = map(int, inp2().split())
    s = [int(c) for c in inp1().strip()]
    f = [int(c) for c in inp1().strip()]
    moves = []
    ans = True
    for _ in range(q):
        (l, r) = map(int, inp2().split())
        moves.append((l - 1, r - 1))
    tr = lazytree(f)
    for (l, r) in reversed(moves):
        success = tr.query(l, r)
        if success == -1:
            break
    else:
        f = tr.get_all()[:n]
        if f != s:
            success = -1
    if success >= 0:
        print('YES')
    else:
        print('NO')

Solution (Python):
import sys
input = sys.stdin.readline

def indexes(L, R):
    INDLIST = []
    R -= 1
    L >>= 1
    R >>= 1
    while L != R:
        if L > R:
            INDLIST.append(L)
            L >>= 1
        else:
            INDLIST.append(R)
            R >>= 1
    while L != 0:
        INDLIST.append(L)
        L >>= 1
    return INDLIST

def updates(l, r, x):
    L = l + seg_el
    R = r + seg_el
    L //= L & -L
    R //= R & -R
    UPIND = indexes(L, R)
    for ind in UPIND[::-1]:
        if LAZY[ind] != None:
            update_lazy = LAZY[ind] * (1 << seg_height - 1 - ind.bit_length())
            LAZY[ind << 1] = LAZY[1 + (ind << 1)] = LAZY[ind]
            SEG[ind << 1] = SEG[1 + (ind << 1)] = update_lazy
            LAZY[ind] = None
    while L != R:
        if L > R:
            SEG[L] = x * (1 << seg_height - L.bit_length())
            LAZY[L] = x
            L += 1
            L //= L & -L
        else:
            R -= 1
            SEG[R] = x * (1 << seg_height - R.bit_length())
            LAZY[R] = x
            R //= R & -R
    for ind in UPIND:
        SEG[ind] = SEG[ind << 1] + SEG[1 + (ind << 1)]

def getvalues(l, r):
    L = l + seg_el
    R = r + seg_el
    L //= L & -L
    R //= R & -R
    UPIND = indexes(L, R)
    for ind in UPIND[::-1]:
        if LAZY[ind] != None:
            update_lazy = LAZY[ind] * (1 << seg_height - 1 - ind.bit_length())
            LAZY[ind << 1] = LAZY[1 + (ind << 1)] = LAZY[ind]
            SEG[ind << 1] = SEG[1 + (ind << 1)] = update_lazy
            LAZY[ind] = None
    ANS = 0
    while L != R:
        if L > R:
            ANS += SEG[L]
            L += 1
            L //= L & -L
        else:
            R -= 1
            ANS += SEG[R]
            R //= R & -R
    return ANS
t = int(input())
for tests in range(t):
    (n, q) = map(int, input().split())
    S = input().strip()
    F = input().strip()
    Q = [tuple(map(int, input().split())) for i in range(q)]
    seg_el = 1 << n.bit_length()
    seg_height = 1 + n.bit_length()
    SEG = [0] * (2 * seg_el)
    LAZY = [None] * (2 * seg_el)
    for i in range(n):
        SEG[i + seg_el] = int(F[i])
    for i in range(seg_el - 1, 0, -1):
        SEG[i] = SEG[i * 2] + SEG[i * 2 + 1]
    for (l, r) in Q[::-1]:
        SUM = r - l + 1
        xx = getvalues(l - 1, r)
        if xx * 2 == SUM:
            print('NO')
            break
        elif xx * 2 > SUM:
            updates(l - 1, r, 1)
        else:
            updates(l - 1, r, 0)
    else:
        for i in range(n):
            if getvalues(i, i + 1) == int(S[i]):
                True
            else:
                print('NO')
                break
        else:
            print('YES')