Nezzar and Binary String (Codeforces 1478E)
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 io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

class segment_tree(object):

    def merge(self, num1, num2):
        return num1 + num2

    def __init__(self, n, initial):
        self.n = n
        self.arr = [0] * (2 * n)
        self.weight = [0] * (2 * n)
        self.lazy = [0] * n
        self.layer = n.bit_length() + 1
        for i in range(2 * n - 1, n - 1, -1):
            self.arr[i] = initial[i - n]
            self.weight[i] = 1
        for i in range(n - 1, -1, -1):
            self.arr[i] = self.merge(self.arr[2 * i], self.arr[2 * i + 1])
            self.weight[i] = self.weight[2 * i] + self.weight[2 * i + 1]

    def rebuild(self, index):
        index = index >> 1
        while index > 0:
            if self.lazy[index] > 0:
                self.arr[index] = self.lazy[index] * self.weight[index]
            else:
                self.arr[index] = self.merge(self.arr[index << 1], self.arr[index << 1 | 1])
            index = index >> 1

    def changetarget(self, index, target):
        self.arr[index] = target * self.weight[index]
        if index < self.n:
            self.lazy[index] = target

    def update(self, left, right, target):
        (i, j) = (self.n + left, self.n + right)
        (i0, j0) = (i, j)
        self.pushdown(i0)
        self.pushdown(j0)
        while i < j:
            if i & 1:
                self.changetarget(i, target)
                i += 1
            if not j & 1:
                self.changetarget(j, target)
                j -= 1
            i = i >> 1
            j = j >> 1
        if i == j:
            self.changetarget(i, target)
        self.rebuild(i0)
        self.rebuild(j0)

    def pushdown(self, index):
        for move in range(self.layer, 0, -1):
            father = index >> move
            if father < 1 or father >= self.n:
                continue
            if self.lazy[father] == 0:
                continue
            child = father << 1
            self.arr[child] = self.lazy[father] * self.weight[child]
            self.arr[child + 1] = self.lazy[father] * self.weight[child + 1]
            if child < self.n:
                self.lazy[child] = self.lazy[father]
            if child + 1 < self.n:
                self.lazy[child + 1] = self.lazy[father]
            self.lazy[father] = 0

    def query(self, left, right):
        (i, j) = (self.n + left, self.n + right)
        output = 0
        self.pushdown(i)
        self.pushdown(j)
        while i < j:
            if i & 1:
                output = self.merge(self.arr[i], output)
                i += 1
            if not j & 1:
                output = self.merge(self.arr[j], output)
                j -= 1
            i = i >> 1
            j = j >> 1
        if i == j:
            output = self.merge(self.arr[i], output)
        return output

def main(t):
    (n, r) = map(int, input().split())
    start = input()[:-1]
    end = input()[:-1]
    endarr = []
    for i in range(n):
        endarr.append(end[i] - ord('0') + 1)
    tree = segment_tree(n, endarr)
    op = []
    for _ in range(r):
        (front, rear) = map(int, input().split())
        op.append([front - 1, rear - 1])
    for [front, rear] in op[::-1]:
        maximum = rear - front + 1
        tot = tree.query(front, rear) - maximum
        if tot * 2 == maximum:
            print('NO')
            return
        elif tot * 2 > maximum:
            tree.update(front, rear, 2)
        else:
            tree.update(front, rear, 1)
    for i in range(n):
        if tree.query(i, i) != start[i] - ord('0') + 1:
            print('NO')
            return
    print('YES')
T = int(input())
t = 1
while t <= T:
    main(t)
    t += 1

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

class FastIO(IOBase):

    def __init__(self, file):
        self.newlines = 0
        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 = sys.stdin.readline

def RL():
    return map(int, sys.stdin.readline().split())

def RLL():
    return list(map(int, sys.stdin.readline().split()))

def N():
    return int(input())

def S():
    return input().strip()

def print_list(l):
    print(' '.join(map(str, l)))

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:
        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:
            t = ind << 1
            update_lazy = LAZY[ind] * (1 << seg_height - 1 - ind.bit_length())
            LAZY[t] = LAZY[1 + t] = LAZY[ind]
            SEG[t] = SEG[1 + t] = 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:
            t = ind << 1
            update_lazy = LAZY[ind] * (1 << seg_height - 1 - ind.bit_length())
            LAZY[t] = LAZY[1 + t] = LAZY[ind]
            SEG[t] = SEG[1 + t] = 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

def match():
    for i in range(n):
        if getvalues(i, i + 1) != int(S[i]):
            return False
    return True
for _ in range(N()):
    (n, q) = RL()
    S = input().strip()
    F = [int(c) for c in input().strip()]
    Q = [tuple(RL()) for _ in range(q)]
    seg_el = 1 << n.bit_length()
    seg_height = 1 + n.bit_length()
    SEG = [0] * seg_el + F + [0] * (seg_el - n)
    LAZY = [None] * (2 * seg_el)
    for i in range(seg_el - 1, 0, -1):
        SEG[i] = SEG[i * 2] + SEG[i * 2 + 1]
    f = True
    for (l, r) in Q[::-1]:
        SUM = r - l + 1
        xx = getvalues(l - 1, r) * 2
        if xx == SUM:
            f = False
            break
        updates(l - 1, r, 1 if xx > SUM else 0)
    print('YES' if f and match() else 'NO')

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

class FastIO(IOBase):

    def __init__(self, file):
        self.newlines = 0
        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 = sys.stdin.readline

def RL():
    return map(int, sys.stdin.readline().split())

def RLL():
    return list(map(int, sys.stdin.readline().split()))

def N():
    return int(input())

def S():
    return input().strip()

def print_list(l):
    print(' '.join(map(str, l)))

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
for _ in range(N()):
    (n, q) = RL()
    S = input().strip()
    F = [int(c) for c in input().strip()]
    Q = [tuple(RL()) for _ in range(q)]
    seg_el = 1 << n.bit_length()
    seg_height = 1 + n.bit_length()
    SEG = [0] * seg_el + F + [0] * (seg_el - n)
    LAZY = [None] * (2 * seg_el)
    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) * 2
        if xx == SUM:
            print('NO')
            break
        updates(l - 1, r, 1 if xx > SUM else 0)
    else:
        for i in range(n):
            if getvalues(i, i + 1) == int(S[i]):
                True
            else:
                print('NO')
                break
        else:
            print('YES')