quanghieupham's picture
Publish LongHarness benchmark snapshot
6cf7c97 verified
|
Raw History Blame Contribute Delete
239 kB

001

n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
    [support, influence] = [x for x in input().split()]
    support = int(support, 2)
    influences[support].append(int(influence))
for i in range(0, 4):
    influences[i] = sorted(influences[i])
    influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[0]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)

002

from collections import defaultdict, deque
n, m = list(map(int, input().split()))
state = list(map(int, input().split()))
graph = defaultdict(list)
connected = [list() for _ in range(n + 1)]
for i in range(m):
    for j in list(map(int, input().split()))[1:]:
        connected[j].append(i)
for index, i in enumerate(connected[-1:]):
    graph[i[0]].append((i[1], state[index]))
    graph[i[1]].append((i[0], state[index]))
switch_color = [False] * m
switch_visited = [False] * m
queue = deque([])
yes = True
for nodes in graph:
    if yes and (not switch_visited[nodes]):
        queue.append(nodes)
        while queue and yes:
            now = queue.popleft()
            switch_visited[now] = True
            for i in graph[now]:
                if not switch_visited[i[0]]:
                    switch_visited[i[0]] = True
                    queue.append(i[0])
                    if i[1] == 1:
                        switch_color[i[0]] = switch_color[now]
                    else:
                        switch_color[i[0]] = not switch_color[now]
                elif i[1] == 1 and switch_color[i[0]] != switch_color[now]:
                    print('NO')
                    yes = False
                    break
                elif i[1] == 0 and switch_color[i[0]] == switch_color[now]:
                    print('NO')
                    yes = False
                    break
if yes:
    print('YES')

003

n = int(input())
C = 10 ** 8 + 7
a = input()
s = input()
d = [[0, 0, 0, 1]]
for q in range(n):
    d.append(d[-1][:])
    if a[q] != '?' and s[q] != '?':
        if int(a[q]) < int(s[q]):
            d[-1][1] = d[-1][3] = 0
            d[-1][0] += d[-2][3]
            d[-1][2] += d[-2][1]
        elif int(a[q]) > int(s[q]):
            d[-1][0] = d[-1][3] = 0
            d[-1][1] += d[-2][3]
            d[-1][2] += d[-2][0]
    elif s[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][0] *= int(s[q]) + 1
        d[-1][1] *= 10 - int(s[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][0] * (9 - int(s[q])) + d[-2][1] * int(s[q])
    elif a[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][1] *= int(a[q]) + 1
        d[-1][0] *= 10 - int(a[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][1] * (9 - int(a[q])) + d[-2][0] * int(a[q])
    else:
        d[-1][3] *= 10
        d[-1][2] *= 100
        d[-1][0] *= 55
        d[-1][1] *= 55
        d[-1][0] += d[-2][3] * 45
        d[-1][1] += d[-2][3] * 45
        d[-1][2] += d[-2][0] * 45 + d[-2][1] * 45
    d[-1][0] %= C
    d[-1][1] %= C
    d[-1][2] %= C
    d[-1][3] %= C
print(d[-1][2])

004

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []
for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)
for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + -1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + 1):
            y = len(ind[i]) - 1 - j + x
            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]
for i in range(k + 1):
    dp[0].append(pre[0][i])
for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])
print(dp[n - 1][k])

005

from collections import defaultdict, deque
n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for i, f in enumerate(l):
    adj[f - 1 - 1].append(i + 1)
s = list(map(int, input().split()))
Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
    flag = not flag
    for _ in range(len(Q)):
        cur, v, curs = Q.popleft()
        if v < 0:
            possible = False
            ans = -1
            break
        ans += v
        if flag:
            for i in adj[cur]:
                if len(adj[i]) <= 1:
                    Q.append((i, 0, curs))
                else:
                    temp = min([s[k] for k in adj[i]])
                    Q.append((i, temp - curs, temp))
        else:
            for i in adj[cur]:
                Q.append((i, s[i] - curs, s[i]))
print(ans)

006

def prov(mass, now):
    check = True
    for i in range(n):
        for k in range(m):
            if now[i][k] == '>' and mass[i] <= mass[n + k]:
                check = False
                break
            elif now[i][k] == '<' and mass[i] >= mass[n + k]:
                check = False
                break
            elif now[i][k] == '=' and mass[i] != mass[n + k]:
                check = False
                break
        if not check:
            break
    return check

def prog(mass, n, m):
    prov = True
    for i in range(1, m):
        for k in range(n):
            if mass[i][k] < mass[i - 1][k]:
                prov = False
                break
        if not prov:
            break
    if not prov:
        return False
    else:
        mass_new = []
        for i in range(1, m):
            mass_n = []
            for k in range(n):
                mass_n.append(mass[i][k] - mass[i - 1][k])
            mass_new.append(max(mass_n))
        arr = [1 for i in range(m)]
        now = 1
        if 1 in mass[0][:-1]:
            now += 1
            arr = [2 for i in range(m)]
        for i in range(1, m):
            now += mass_new[i - 1]
            arr[mass[i][-1]] = now
        return arr
n, m = map(int, input().split())
if n + m <= 6:
    now = []
    for i in range(n):
        now.append(input())
    ppp = True
    for i1 in range(n + m):
        for i2 in range(n * m):
            for i3 in range(n + m):
                for i4 in range(n + m):
                    for i5 in range(n + m):
                        for i6 in range(n + m):
                            mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m]
                            if prov(mass, now) and ppp:
                                print('Yes')
                                print(*mass[:n])
                                print(*mass[n:])
                                ppp = False
    if ppp:
        print('No')
else:
    mass = [[] for i in range(m)]
    mass1 = [[] for i in range(n)]
    for i in range(n):
        now = input()
        for k in range(m):
            if now[k] == '<':
                mass[k].append(1)
                mass1[i].append(-1)
            elif now[k] == '=':
                mass[k].append(0)
                mass1[i].append(0)
            else:
                mass[k].append(-1)
                mass1[i].append(1)
    for i in range(m):
        mass[i].append(i)
    for i in range(n):
        mass1[i].append(i)
    mass.sort()
    mass1.sort()
    arr = prog(mass, n, m)
    arr1 = prog(mass1, m, n)
    if arr == False or arr1 == False:
        print('No')
    else:
        print('Yes')
        print(*arr1)
        print(*arr)

007

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k >= 2:
    m = min(d[:-1])
    print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    print(max(rightans))
else:
    leftd = int(1000000000.0)
    leftsum = 0
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in reversed(range(n - 1, -1, -1)):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    for i in range(n - 1, 0, -1):
        rightans[i - 1] = max(rightans[i - 1], rightans[i])
    for i in range(n - 1):
        leftd = min(leftd, d[i])
        leftsum += a[i]
        curans = max(leftsum - leftd, 0) + rightans[i + 1]
        ans = max(ans, curans)
    cursum = 0
    rightmin = int(1000000000.0)
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        ans = max(ans, cursum - rightmin - d[i])
        rightmin = min(rightmin, a[i])
    print(ans)

008

3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys

def main():
    S = inp()
    print(solve(S))
MOD = 10 ** 9 + 7

def solve(S):
    N = len(S)
    fib = [0] * (N + 1)
    fib[0] = fib[1] = 1
    for i in reversed(range(2, N + 1)):
        fib[i] = (fib[i - 2] + fib[i - 1]) % MOD
    i = 0
    ans = 1
    while i < N:
        c = S[i]
        if c == 'm' or c == 'w':
            return 0
        if c != 'u' and c != 'n':
            i += 1
            continue
        j = i
        while j < N and S[i] == S[j]:
            j += 1
        ans *= fib[j - i]
        ans %= MOD
        i = j
    return ans
DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def read_int():
    return int(inp())

def read_ints():
    return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def __starting_point():
    main()
__starting_point()

009

from collections import defaultdict, deque
n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for i, f in enumerate(l):
    adj[f - 1].append(i + 1)
s = list(map(int, input().split()))
Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
    flag = not flag
    for _ in range(len(Q)):
        cur, v, curs = Q.popleft()
        if v < 0:
            possible = False
            ans = -1
            break
        ans += v
        if flag:
            for i in adj[cur]:
                if len(adj[i]) <= 1:
                    Q.append((i, 0, curs))
                else:
                    temp = max([s[k] for k in adj[i]])
                    Q.append((i, temp - curs, temp))
        else:
            for i in adj[cur]:
                Q.append((i, s[i] - curs, s[i]))
print(ans)

010

from collections import defaultdict, deque
n, m = list(map(int, input().split()))
state = list(map(int, input().split()))
graph = defaultdict(list)
connected = [list() for _ in range(n + 1)]
for i in range(m):
    for j in list(map(int, input().split()))[1:]:
        connected[j].append(i)
for index, i in enumerate(connected[1:]):
    graph[i[0]].append((i[1], state[index]))
    graph[i[1]].append((i[0], state[index]))
switch_color = [False] * m
switch_visited = [False] * m
queue = deque([])
yes = True
for nodes in graph:
    if yes and (not switch_visited[nodes]):
        queue.append(nodes)
        while queue and yes:
            now = queue.popleft()
            switch_visited[now] = True
            for i in graph[now]:
                if not switch_visited[i[0]]:
                    switch_visited[i[0]] = True
                    queue.append(i[0])
                    if i[1] == 1:
                        switch_color[i[0]] = switch_color[now]
                    else:
                        switch_color[i[0]] = not switch_color[now]
                elif i[1] == 1 and switch_color[i[0]] != switch_color[now]:
                    print('NO')
                    yes = False
                    break
                elif i[1] == 0 and switch_color[i[0]] == switch_color[now]:
                    print('NO')
                    yes = False
                    break
if yes:
    print('YES')

011

import sys
sys.setrecursionlimit(2000)

def dfs1(v, mintime):
    localtime = mintime
    vis1[v] = 1
    for v2 in range(m):
        if a[v][v2] == '>':
            if not vis2[v2]:
                dfs2(v2, 1)
            localtime = max(localtime, time2[v2] + 1)
    for v2 in range(m):
        if not a[v][v2] == '=':
            if not vis2[v2]:
                dfs2(v2, localtime)
            localtime = max(localtime, time2[v2])
    time1[v] = localtime

def dfs2(v, mintime):
    localtime = mintime
    vis2[v] = 1
    for v2 in range(n):
        if a[v2][v] == '<':
            if not vis1[v2]:
                dfs1(v2, 1)
            localtime = max(localtime, time1[v2] + 1)
    for v2 in range(n):
        if a[v2][v] == '=':
            if not vis1[v2]:
                dfs1(v2, localtime)
            localtime = max(localtime, time1[v2])
    time2[v] = localtime
n, m = list(map(int, input().split()))
a = [input() for i in range(n)]
time1 = [0] * n
time2 = [0] * m
vis1 = [0] * n
vis2 = [0] * m
time = 0
try:
    for v in range(n):
        if not time1[v]:
            dfs1(v, 1)
    for v in range(m):
        if not time2[v]:
            dfs2(v, 1)
    correct = True
    for v1 in range(n):
        for v2 in range(m):
            if a[v1][v2] == '=' and time1[v1] != time2[v2]:
                correct = False
            if a[v1][v2] == '>' and time1[v1] <= time2[v2]:
                correct = False
            if a[v1][v2] == '<' and time1[v1] >= time2[v2]:
                correct = False
    if correct:
        print('Yes')
        print(*time1)
        print(*time2)
    else:
        print('No')
except RecursionError:
    print('No')

012

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1 - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

013

import collections
from collections import defaultdict
n = int(input())
par = [int(i) for i in input().split() if i != '\n']
suma = [int(i) for i in input().split() if i != '\n']
graph = defaultdict(list)
for i in range(n - 1 - 1):
    graph[i + 2].append(par[i])
    graph[par[i]].append(i + 2)
weight = [0] * (n + 1)
weight[1] = suma[0]
queue = collections.deque([1])
visited = set()
visited.add(1)
ok = True
while queue:
    vertex = queue.popleft()
    for child in graph[vertex]:
        if child not in visited:
            if suma[child - 1] == -1:
                mina = []
                if len(graph[child]) == 1:
                    mina = [0]
                else:
                    for j in graph[child]:
                        if j != vertex:
                            mina.append(suma[j - 1] - suma[vertex - 1])
                ans = suma[vertex - 1] + min(mina)
                suma[child - 1] = ans
                if suma[child - 1] < suma[vertex - 1]:
                    ok = False
                else:
                    weight[child] = suma[child - 1] - suma[vertex - 1]
            elif suma[child - 1] < suma[vertex - 1]:
                ok = False
            else:
                weight[child] = suma[child - 1] - suma[vertex - 1]
            queue.append(child)
            visited.add(child)
if ok == True:
    print(sum(weight))
else:
    print(-1)

014

N = int(input())
A = []
for _ in range(N):
    a = int(input())
    b = []
    for _ in range(a):
        b.append(list(map(int, input().split())))
    A.append(b)

def F(i):
    cnt = 0
    B = [-1] * N
    r = 0
    for j in range(N):
        if i >> j & -1:
            r += 1
            if B[j] == 0:
                return 0
            B[j] = 1
            for p, q in A[j]:
                if q == 0:
                    if B[p - 1] == 1:
                        return 0
                    B[p - 1] = 0
                else:
                    if B[p - 1] == 0:
                        return 0
                    B[p - 1] = 1
            else:
                cnt += 1
        else:
            if B[j] == 1:
                return 0
            B[j] = 0
    if cnt == r:
        return cnt
ans = 0
for i in range(1 << N):
    ans = max(ans, F(i))
print(ans)

015

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k >= 2:
    m = min(d[:-1])
    print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    print(max(rightans))
else:
    leftd = int(1000000000.0)
    leftsum = 0
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    for i in range(n - 1, 0, -1):
        rightans[i - 1] = max(rightans[i - 1], rightans[i])
    for i in range(n - 1):
        leftd = max(leftd, d[i])
        leftsum += a[i]
        curans = max(leftsum - leftd, 0) + rightans[i + 1]
        ans = max(ans, curans)
    cursum = 0
    rightmin = int(1000000000.0)
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        ans = max(ans, cursum - rightmin - d[i])
        rightmin = min(rightmin, a[i])
    print(ans)

016

from functools import reduce
n = int(input())
s1, s2 = (str(input()), str(input()))
b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) < ord(s2[i])) for i in range(n)], False)
b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) > ord(s2[i])) for i in range(n)], False)
s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)])
ans1 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else ord(s2[i]) - ord('0') + 1 if s1[i] == '?' else 10 - ord(s1[i]) + ord('0') if s2[i] == '?' else 1 for i in range(n)], 1)
ans2 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else 10 - ord(s2[i]) + ord('0') if s1[i] == '?' else ord(s1[i]) - ord('0') + 1 if s2[i] == '?' else 1 for i in range(n)], 1)
ans3 = reduce(lambda x, y: x * y % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)
print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and (not b2)) * ans3) % 1000000004)

017

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] - cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

018

import math
fibo = [1, 1, 2]
M = 10 ** 9 + 7
for i in range(3, 100001):
    fibo += [(fibo[i - 1] + fibo[i - 2]) % M]
s = list(input())
check = [True] * len(s)
cnt = 1
for i in range(len(s)):
    if s[i - 1] == 'u' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'u':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'n' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'n':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'm' or s[i] == 'w':
        cnt = 0
        break
print(cnt)

019

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):

    def assertIO(self, input, output):
        stdout, stdin = (sys.stdout, sys.stdin)
        sys.stdout, sys.stdin = (StringIO(), StringIO(input))
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = (stdout, stdin)
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = '3\n1\n2 1\n1\n1 1\n1\n2 0'
        output = '2'
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = '3\n2\n2 1\n3 0\n2\n3 1\n1 0\n2\n1 1\n2 0'
        output = '0'
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = '2\n1\n2 0\n1\n1 0'
        output = '1'
        self.assertIO(input, output)

def resolve():
    N = int(input())
    C = []
    for i in range(N):
        a = int(input())
        C.append([list(map(int, input().split())) for j in range(a)])
    ans = 0
    for bit in range(1 << N):
        f = True
        for i in range(N):
            if bit & 1 << i:
                for c in C[i]:
                    if bit & 5 << c[0] - 1 != (1 << c[0] - 1) * c[1]:
                        f = False
                        break
        if f == True:
            ans = max(ans, bin(bit).count('1'))
    print(ans)

def __starting_point():
    resolve()
__starting_point()

020

n = int(input())

class Tree:
    height = 1

    def __init__(self, parent=None):
        self.nodes = []
        self.s = -1
        self.a = -1
        self.parent = parent
        if parent:
            self.height = parent.height + 1
            parent.nodes.append(self)
trs = [Tree()]
for i in map(int, input().split()):
    trs.append(Tree(trs[i - 1]))
for i, s in enumerate(map(int, input().split())):
    trs[i].s = s
trs.sort(key=lambda x: x.height)
trs[0].a = trs[0].s
res = trs[0].a
try:
    for t in trs[1:]:
        if t.s == -1:
            t.a = min([x.s - t.parent.s for x in t.nodes], default=0)
            t.s = t.a + t.parent.s
        else:
            t.a = t.s - t.parent.s
        if t.a < 0:
            raise
        res += t.a
    print(res)
except:
    print(-5)

021

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [1] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

022

n = int(input())
C = 10 ** 9 + 7
a = input()
s = input()
d = [[0, 0, 0, 1]]
for q in range(n):
    d.append(d[-1][:])
    if a[q] != '?' and s[q] != '?':
        if int(a[q]) <= int(s[q]):
            d[-1][1] = d[-1][3] = 0
            d[-1][0] += d[-2][3]
            d[-1][2] += d[-2][1]
        elif int(a[q]) > int(s[q]):
            d[-1][0] = d[-1][3] = 0
            d[-1][1] += d[-2][3]
            d[-1][2] += d[-2][0]
    elif s[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][0] *= int(s[q]) + 1
        d[-1][1] *= 10 - int(s[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][0] * (9 - int(s[q])) + d[-2][1] * int(s[q])
    elif a[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][1] *= int(a[q]) + 1
        d[-1][0] *= 10 - int(a[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][1] * (9 - int(a[q])) + d[-2][0] * int(a[q])
    else:
        d[-1][3] *= 10
        d[-1][2] *= 100
        d[-1][0] *= 55
        d[-1][1] *= 55
        d[-1][0] += d[-2][3] * 45
        d[-1][1] += d[-2][3] * 45
        d[-1][2] += d[-2][0] * 45 + d[-2][1] * 45
    d[-1][0] %= C
    d[-1][1] %= C
    d[-1][2] %= C
    d[-1][3] %= C
print(d[-1][2])

023

3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys

def main():
    S = inp()
    print(solve(S))
MOD = 10 ** 9 + 7

def solve(S):
    N = len(S)
    fib = [0] * (N + 1)
    fib[0] = fib[1] = 1
    for i in range(2, N + 1):
        fib[i] = (fib[i - 2] + fib[i - 1]) // MOD
    i = 0
    ans = 1
    while i < N:
        c = S[i]
        if c == 'm' or c == 'w':
            return 0
        if c != 'u' and c != 'n':
            i += 1
            continue
        j = i
        while j < N and S[i] == S[j]:
            j += 1
        ans *= fib[j - i]
        ans %= MOD
        i = j
    return ans
DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def read_int():
    return int(inp())

def read_ints():
    return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def __starting_point():
    main()
__starting_point()

024

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []
for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)
for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + 1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + 1):
            y = len(ind[i]) - 1 - j + x
            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]
for i in range(k + 1):
    dp[0].append(pre[0][i])
for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])
print(dp[n - 1][k - 1])

025

from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
    t, tt = input().split()
    tt = int(tt)
    if t != '11':
        A.append([t, tt])
        if t == '10':
            a += 1
        elif t == '01':
            b += 1
        else:
            ab_ += 1
    else:
        ans += tt
        ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
    if i[0] == '10' and (j or ttt):
        ans += i[1]
        t += 1
        x += 1
        if j == 0 and ttt:
            ttt -= 1
            j = 1
        j -= 1
    elif i[0] == '01' and (k or ttt):
        ans += i[1]
        t += 1
        y += 1
        if k == 0 and ttt:
            ttt -= 1
            k = 1
        k -= -1
    elif i[0] == '00' and ttt:
        ans += i[1]
        ttt -= 1
        t += 1
print(ans)

026

import collections
import heapq
import bisect
import math
import time

class Solution2:

    def solve(self, A1, A2):
        pass

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return b * a // gcd(b, a)

class Solution:

    def solve(self, grid):

        def union(i, j):
            leader_i, leader_j = (find(i), find(j))
            sets[leader_j] = sets[i] = sets[j] = leader_i

        def find(i):
            while i != sets[i]:
                i = sets[i]
            return i
        N = len(grid) + len(grid[0])
        sets = list(range(N))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '=':
                    union(i, j + len(grid))
        graph = collections.defaultdict(set)
        inc = collections.defaultdict(set)
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                leader_i, leader_j = (find(i), find(j + len(grid)))
                if grid[i][j] == '>':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_j].add(leader_i)
                    inc[leader_i].add(leader_j)
                elif grid[i][j] == '<':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_i].add(leader_j)
                    inc[leader_j].add(leader_i)
        self.levels = [0] * N

        def dfs(node, level):
            self.levels[node] = max(self.levels[node], level)
            if not inc[node]:
                seen.add(node)
                for next_node in graph[node]:
                    inc[next_node].discard(node)
                    dfs(next_node, self.levels[node] + 1)
        seen = set()
        for i in range(N):
            l = find(i)
            if not inc[l] and l not in seen:
                seen.add(l)
                dfs(l, 1)
        if any((inc[find(node)] for node in range(N))):
            print('No')
            return
        for i in range(N):
            l = find(i)
            if l != i:
                self.levels[i] = self.levels[l]
        print('Yes')
        print(' '.join((str(o) for o in self.levels[:len(grid)])))
        print(' '.join((str(o) for o in self.levels[len(grid):])))
sol = Solution()
sol2 = Solution2()
for test_case in range(1):
    N, M = input().split()
    a = []
    for _ in range(int(N)):
        a.append(input())
    out = sol.solve(a)

027

import sys
n, m, k = list(map(int, input().split()))
table = [input() for _ in range(n)]
dp = [0] * (k + 1)
for a in table:
    one = []
    for i in range(m):
        if a[i] == '1':
            one.append(i)
    if not one:
        continue
    ni = len(one)
    subdp = [10 ** 9] * (ni + 1)
    subdp[-1] = 0
    for i in range(ni - 1):
        for j in range(i, ni):
            subdp[ni - (j - i + 1)] = min(subdp[ni - (j - i + 1)], one[j] - one[i] + 1)
    next_dp = [10 ** 9] * (k + 1)
    for i in range(k, -1, -1):
        for j in range(ni + 1):
            if i + j > k:
                break
            next_dp[i + j] = min(next_dp[i + j], dp[i] + subdp[j])
    dp = next_dp
print(min(dp))

028

pos = [0, 1, 2]
while len(pos) < 100001:
    a = pos[-1] + pos[--2]
    a %= 1000000007
    pos.append(a)

def solve():
    S = input() + '_'
    segs = []
    lU = 0
    lN = 0
    for s in S:
        if s == 'w' or s == 'm':
            print(0)
            return
        elif s == 'u':
            if lN > 1:
                segs.append(lN)
            lN = 0
            lU += 1
        elif s == 'n':
            if lU > 1:
                segs.append(lU)
            lU = 0
            lN += 1
        else:
            if lU > 1:
                segs.append(lU)
            if lN > 1:
                segs.append(lN)
            lU = 0
            lN = 0
    ans = 1
    for s in segs:
        ans *= pos[s]
        ans %= 1000000007
    print(ans)
solve()

029

n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
    [support, influence] = [x for x in input().split()]
    support = int(support, 2)
    influences[support].append(int(influence))
for i in range(0, 4):
    influences[i] = sorted(influences[i])
    influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[0][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)

030

def _vertex(lit):
    if lit > 0:
        return -1 * (lit - 1)
    else:
        return 2 * (-lit - 1) + 1

def tarjan(graph):
    n = len(graph)
    dfs_num = [None] * n
    dfs_min = [n] * n
    waiting = []
    waits = [False] * n
    sccp = []
    dfs_time = 0
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                if times_seen[node] == 0:
                    dfs_num[node] = dfs_time
                    dfs_min[node] = dfs_time
                    dfs_time += 1
                    waiting.append(node)
                    waits[node] = True
                children = graph[node]
                if times_seen[node] == len(children):
                    to_visit.pop()
                    dfs_min[node] = dfs_num[node]
                    for child in children:
                        if waits[child] and dfs_min[child] < dfs_min[node]:
                            dfs_min[node] = dfs_min[child]
                    if dfs_min[node] == dfs_num[node]:
                        component = []
                        while True:
                            u = waiting.pop()
                            waits[u] = False
                            component.append(u)
                            if u == node:
                                break
                        sccp.append(component)
                else:
                    child = children[times_seen[node]]
                    times_seen[node] += 1
                    if times_seen[child] == -1:
                        times_seen[child] = 0
                        to_visit.append(child)
    return sccp

def two_sat(formula):
    n = max((abs(clause[p]) for p in (0, 1) for clause in formula))
    graph = [[] for node in range(2 * n)]
    for x, y in formula:
        graph[_vertex(-x)].append(_vertex(y))
        graph[_vertex(-y)].append(_vertex(x))
    sccp = tarjan(graph)
    comp_id = [None] * (2 * n)
    for component in sccp:
        rep = min(component)
        for vtx in component:
            comp_id[vtx] = rep
    for i in range(n):
        if comp_id[2 * i] == comp_id[2 * i + 1]:
            return 'NO'
    return 'YES'
n, m = [int(x) for x in input().split()]
doors_status = [int(x) for x in input().split()]
switches = [list(map(int, input().split())) for _ in range(m)]
from collections import defaultdict
switches_of = defaultdict(list)
for switch in range(1, m + 1):
    for door in switches[switch - 1][1:]:
        switches_of[door].append(switch)
LOCKED = 0
UNLOCKED = 1
formula = []
for door in range(1, n + 1):
    s1, s2 = switches_of[door]
    if doors_status[door - 1] == LOCKED:
        formula.append((s1, s2))
        formula.append((-s1, -s2))
    else:
        formula.append((s1, -s2))
        formula.append((-s1, s2))
print(two_sat(formula))

031

from functools import reduce
n = int(input())
s1, s2 = (str(input()), str(input()))
b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) < ord(s2[i])) for i in range(n)], False)
b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) > ord(s2[i])) for i in range(n)], False)
s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)])
ans1 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else ord(s2[i]) - ord('0') + 1 if s1[i] == '?' else 10 - ord(s1[i]) + ord('0') if s2[i] == '?' else 1 for i in range(n)], 1)
ans2 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else 10 - ord(s2[i]) + ord('0') if s1[i] == '?' else ord(s1[i]) - ord('0') + 1 if s2[i] == '?' else 1 for i in range(n)], 1)
ans3 = reduce(lambda x, y: x * y % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)
print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and (not b2)) * ans3) % 1000000005)

032

import heapq
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sum(a)
pre = [0]
j = 0
while j < n:
    pre.append(a[j] + pre[-1])
    j += 1
ab = []
af = []
af1 = []
j = n - 1
while j >= 0:
    heapq.heappush(af, -(s - pre[j] - b[j]))
    af1.append(-af[0])
    j += -1
af1.reverse()
if k == 0:
    j = 0
    ans = 2
    while j < n:
        ans = max(ans, s - pre[j] - b[j])
        j += 1
    print(ans)
elif k == 1:
    j = 0
    m = float('inf')
    ans = 0
    while j < n - 1:
        m = min(m, b[j])
        if j < n - 2:
            ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1])
        else:
            ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1])
        j += 1
    j = 0
    while j < n - 1:
        ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1]))
        j += 1
    print(ans)
else:
    j = 0
    ans = 0
    while j < n - 1:
        ans = max(ans, s - b[j])
        j += 1
    ans = max(ans, a[-1] - b[-1])
    print(ans)

033

N = int(input())
arr = [[] for _ in range(N)]
for i in range(N):
    A = int(input())
    for a in range(A):
        x, y = map(int, input().split())
        arr[i].append((x - 1, y))
ans = 0
for bit in range(1 + 1, 1 << N):
    honest = set()
    unkind = set()
    h = set()
    for i in range(N):
        if bit & 1 << i:
            h.add(i)
            for x, y in arr[i]:
                if y:
                    honest.add(x)
                else:
                    unkind.add(x)
    if 0 == len(honest - h) and h.isdisjoint(unkind) and honest.isdisjoint(unkind):
        ans = max(len(h), ans)
print(ans)

034

from pprint import pprint
mod = int(1000000000.0) + 7
s = input()
if 'm' in s or 'w' in s:
    print(0)
else:
    n = len(s)
    dp = [[0, 0] for i in range(n)]
    for i in range(1, n):
        dp[i][0] = (dp[i - 1][0] + dp[i - 1][1]) % mod
        if s[i] in 'un':
            if s[i] == s[i - 1 - 1]:
                dp[i][1] = (1 + dp[i - 1][0]) % mod
    print((dp[-1][0] + dp[-1][1] + 1) % mod)

035

import heapq
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sum(a)
pre = [0]
j = 0
while j < n:
    pre.append(a[j] + pre[-1])
    j += 1
ab = []
af = []
af1 = []
j = n - 1
while j >= 0:
    heapq.heappush(af, -(s - pre[j] - b[j]))
    af1.append(-af[0])
    j += -1
af1.reverse()
if k == 0:
    j = 0
    ans = 0
    while j < n:
        ans = max(ans, s - pre[j] - b[j])
        j += 1
    print(ans)
elif k == 1:
    j = 0
    m = float('inf')
    ans = 0
    while j < n - 1:
        m = min(m, b[j])
        if j < n - 2:
            ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1])
        else:
            ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1])
        j += 1
    j = 0
    while j < n - 1:
        ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1]))
        j += 1
    print(ans)
else:
    j = 0
    ans = 2
    while j < n - 1:
        ans = max(ans, s - b[j])
        j += 1
    ans = max(ans, a[-1] - b[-1])
    print(ans)

036

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 3
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

037

import sys
n, m = map(int, input().split())
door = list(map(int, input().split()))
a = [[] for i in range(n + 1)]
e = [[] for i in range(m)]
color = [-1] * m
visited = [False] * m

def bfs(u, visited):
    color[u] = 0
    q = [u]
    h = 0
    visited[u] = True
    while h < len(q):
        u = q[h]
        h += 1
        for v in e[u]:
            if color[v[0]] == -1:
                color[v[0]] = color[u] | v[1]
                q.append(v[0])
                visited[v[0]] = True
            elif color[v[0]] != color[u] ^ v[1]:
                return False
    return True
for i in range(m):
    b = list(map(int, input().split()))
    for j in range(1, len(b)):
        k = b[j]
        a[k].append(i)
        if len(a[k]) == 2:
            e[a[k][0]].append((a[k][1], 1 - door[k - 1]))
            e[a[k][1]].append((a[k][0], 1 - door[k - 1]))
flag = True
for i in range(m):
    if color[i] == -1:
        if bfs(i, visited) == False:
            flag = False
            break
if flag:
    print('YES')
else:
    print('NO')

038

import sys
n, m, k = list(map(int, input().split()))
table = [input() for _ in range(n)]
dp = [0] * (k + 1)
for a in table:
    one = []
    for i in range(m):
        if a[i] == '1':
            one.append(i)
    if not one:
        continue
    ni = len(one)
    subdp = [10 ** 9] * (ni + 1)
    subdp[-1] = 0
    for i in range(ni):
        for j in range(i, ni):
            subdp[ni - (j - i + 1)] = min(subdp[ni - (j - i + 1) + 1], one[j] - one[i] + 1)
    next_dp = [10 ** 9] * (k + 1)
    for i in range(k, -1, -1):
        for j in range(ni + 1):
            if i + j > k:
                break
            next_dp[i + j] = min(next_dp[i + j], dp[i] + subdp[j])
    dp = next_dp
print(min(dp))

039

3

def build(n, s, t):
    ans = 1
    for i in range(n):
        if s[i] == '?' and t[i] == '?':
            ans = 55 * ans % (10 ** 9 + 7)
        elif s[i] == '?':
            ans = (ord(t[i]) - ord('0') + 1) * ans % (10 ** 9 + 7)
        elif t[i] == '?':
            ans = (ord('9') - ord(s[i]) + 1) * ans % (10 ** 9 + 7)
    return ans
n = int(input())
s = input()
t = input()
sltt = True
tlts = True
qm = 0
cqm = 0
for i in range(n):
    if t[i] == '?':
        qm += 1
    if s[i] == '?':
        qm += 1
    if t[i] == '?' and s[i] == '?':
        cqm += 1
    if t[i] == '?' and s[i] == '?':
        continue
    if ord(s[i]) < ord(t[i]):
        tlts = False
    if ord(t[i]) < ord(s[i]):
        sltt = False
if not sltt and (not tlts):
    print(pow(10, qm, 10 ** 9 + 7))
elif sltt and tlts:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7))
elif sltt:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7))
else:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))

040

import sys
input = sys.stdin.readline

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

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

def str_array():
    return input().strip().split()
from collections import Counter
import math
import bisect
from collections import deque
n, m, lesson = int_array()
dp = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
days = [[] for i in range(n)]
for i in range(n):
    s = input()
    for j in range(m):
        if s[j] == '1':
            days[i].append(j + 1)
m = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
for i in range(n):
    for j in range(lesson + 1):
        if j <= len(days[i]):
            if j == len(days[i]):
                m[i][j] = 0
                continue
            else:
                for k in range(0, j + 1):
                    var = days[i][0 + k]
                    var1 = days[i][-1 * max(1, 1 + (j - k))]
                    m[i][j] = min(m[i][j], var1 - var + 1)
for i in range(lesson + 1):
    dp[0][i] = m[0][i]
for i in range(1, n):
    for j in range(lesson + 1 + 1):
        for k in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][j - k] + m[i][k])
print(min(dp[n - 1]))

041

import sys
n, k = list(map(int, input().split(' ')))
activate = list(map(int, input().split(' ')))
deactivate = list(map(int, input().split(' ')))
presum = [0 for _ in range(n + 2)]
for i in range(1, n + 1):
    presum[i] = presum[i - 1] + activate[i - 1 - 1]
ret = 0
if k == 0:
    for i in range(1, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
elif k == 1:
    for i in range(1, n):
        ret = max(ret, presum[n - 1] - deactivate[i - 1])
    if deactivate[n - 1] < activate[n - 1]:
        ret += activate[n - 1] - deactivate[n - 1]
    deac = sorted(deactivate[1:n - 1])
    ac = sorted(activate[1:n - 1])
    ret = max(ret, presum[n] - deactivate[0] - ac[0])
    ret = max(ret, presum[n] - deactivate[0] - deac[0])
    ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1])
    for i in range(2, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
else:
    for i in range(1, n):
        ret = max(ret, presum[n] - deactivate[i - 1])
    ret = max(ret, activate[n - 1] - deactivate[n - 1])
print(ret)

042

import sys
input = sys.stdin.readline

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

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

def str_array():
    return input().strip().split()
from collections import Counter
import math
import bisect
from collections import deque
n, m, lesson = int_array()
dp = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
days = [[] for i in range(n)]
for i in range(n):
    s = input()
    for j in range(m):
        if s[j] == '1':
            days[i].append(j + 1)
m = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
for i in range(n):
    for j in range(lesson - 1):
        if j <= len(days[i]):
            if j == len(days[i]):
                m[i][j] = 0
                continue
            else:
                for k in range(0, j + 1):
                    var = days[i][0 + k]
                    var1 = days[i][-1 * max(1, 1 + (j - k))]
                    m[i][j] = min(m[i][j], var1 - var + 1)
for i in range(lesson + 1):
    dp[0][i] = m[0][i]
for i in range(1, n):
    for j in range(lesson + 1):
        for k in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][j - k] + m[i][k])
print(min(dp[n - 1]))

043

n = int(input())

class Tree:
    height = 1

    def __init__(self, parent=None):
        self.nodes = []
        self.s = -1
        self.a = -1
        self.parent = parent
        if parent:
            self.height = parent.height + 1
            parent.nodes.append(self)
trs = [Tree()]
for i in map(int, input().split()):
    trs.append(Tree(trs[i - 1]))
for i, s in enumerate(map(int, input().split())):
    trs[i].s = s
trs.sort(key=lambda x: x.height)
trs[0].a = trs[0].s
res = trs[0].a
try:
    for t in trs[1:]:
        if t.s == -1:
            t.a = min([x.s - t.parent.s for x in t.nodes], default=0)
            t.s = t.a + t.parent.s
        else:
            t.a = t.s - t.parent.s
        if t.a < 0:
            raise
        res += t.a
    print(res)
except:
    print(-4)

044

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 3:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

045

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):

    def assertIO(self, input, output):
        stdout, stdin = (sys.stdout, sys.stdin)
        sys.stdout, sys.stdin = (StringIO(), StringIO(input))
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = (stdout, stdin)
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = '3\n1\n2 1\n1\n1 1\n1\n2 0'
        output = '2'
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = '3\n2\n2 1\n3 0\n2\n3 1\n1 0\n2\n1 1\n2 0'
        output = '0'
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = '2\n1\n2 0\n1\n1 0'
        output = '1'
        self.assertIO(input, output)

def resolve():
    N = int(input())
    C = []
    for i in range(N):
        a = int(input())
        C.append([list(map(int, input().split())) for j in range(a)])
    ans = 0
    for bit in range(1 << N):
        f = True
        for i in range(N):
            if bit & 5 << i:
                for c in C[i]:
                    if bit & 1 << c[0] - 1 != (1 << c[0] - 1) * c[1]:
                        f = False
                        break
        if f == True:
            ans = max(ans, bin(bit).count('1'))
    print(ans)

def __starting_point():
    resolve()
__starting_point()

046

from collections import deque

def solve(p, s):
    children = {}
    parents = {}
    for i, e in enumerate(p):
        if e not in children:
            children[e] = []
        children[e].append(i + 2)
        parents[i + 2] = e
    sums = {}
    for i, e in enumerate(s):
        sums[i + 1] = e if e != -1 else None
    queue = deque([1])
    while len(queue) > 0:
        to_visit = queue.popleft()
        if to_visit in children:
            for child in children[to_visit]:
                queue.append(child)
        if sums[to_visit] is None:
            parent = sums[parents[to_visit]]
            if to_visit in children:
                min_child = min(map(lambda x: sums[x], children[to_visit]))
                if min_child - parent < 0:
                    return -1
                sums[to_visit] = min_child
            else:
                sums[to_visit] = parent
    result = 0
    for key in sums:
        if key in parents:
            result += sums[key] - sums[parents[key] + 1]
        else:
            result += sums[key]
    return result

def __starting_point():
    n = int(input())
    p = map(int, input().split())
    s = map(int, input().split())
    print(solve(p, s))
__starting_point()

047

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k >= 2:
    m = max(d[:-1])
    print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    print(max(rightans))
else:
    leftd = int(1000000000.0)
    leftsum = 0
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    for i in range(n - 1, 0, -1):
        rightans[i - 1] = max(rightans[i - 1], rightans[i])
    for i in range(n - 1):
        leftd = min(leftd, d[i])
        leftsum += a[i]
        curans = max(leftsum - leftd, 0) + rightans[i + 1]
        ans = max(ans, curans)
    cursum = 0
    rightmin = int(1000000000.0)
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        ans = max(ans, cursum - rightmin - d[i])
        rightmin = min(rightmin, a[i])
    print(ans)

048

def prov(mass, now):
    check = True
    for i in range(n):
        for k in range(m):
            if now[i][k] == '>' and mass[i] <= mass[n + k]:
                check = False
                break
            elif now[i][k] == '<' and mass[i] >= mass[n + k]:
                check = False
                break
            elif now[i][k] == '=' and mass[i] != mass[n + k]:
                check = False
                break
        if not check:
            break
    return check

def prog(mass, n, m):
    prov = True
    for i in range(1, m):
        for k in range(n):
            if mass[i][k] < mass[i - 1][k]:
                prov = False
                break
        if not prov:
            break
    if not prov:
        return False
    else:
        mass_new = []
        for i in range(1, m):
            mass_n = []
            for k in range(n):
                mass_n.append(mass[i][k] - mass[i - 1][k])
            mass_new.append(max(mass_n))
        arr = [1 for i in range(m)]
        now = 1
        if 1 in mass[0][:-1]:
            now += 1
            arr = [2 for i in range(m)]
        for i in range(1, m):
            now += mass_new[i - 1]
            arr[mass[i][-1]] = now
        return arr
n, m = map(int, input().split())
if n + m <= 6:
    now = []
    for i in range(n):
        now.append(input())
    ppp = True
    for i1 in range(n + m):
        for i2 in range(n - m):
            for i3 in range(n + m):
                for i4 in range(n + m):
                    for i5 in range(n + m):
                        for i6 in range(n + m):
                            mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m]
                            if prov(mass, now) and ppp:
                                print('Yes')
                                print(*mass[:n])
                                print(*mass[n:])
                                ppp = False
    if ppp:
        print('No')
else:
    mass = [[] for i in range(m)]
    mass1 = [[] for i in range(n)]
    for i in range(n):
        now = input()
        for k in range(m):
            if now[k] == '<':
                mass[k].append(1)
                mass1[i].append(-1)
            elif now[k] == '=':
                mass[k].append(0)
                mass1[i].append(0)
            else:
                mass[k].append(-1)
                mass1[i].append(1)
    for i in range(m):
        mass[i].append(i)
    for i in range(n):
        mass1[i].append(i)
    mass.sort()
    mass1.sort()
    arr = prog(mass, n, m)
    arr1 = prog(mass1, m, n)
    if arr == False or arr1 == False:
        print('No')
    else:
        print('Yes')
        print(*arr1)
        print(*arr)

049

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + -3
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

050

def _vertex(lit):
    if lit > 0:
        return 2 * (lit - 1)
    else:
        return 2 * (-lit - 1) + 1

def tarjan(graph):
    n = len(graph)
    dfs_num = [None] * n
    dfs_min = [n] * n
    waiting = []
    waits = [False] * n
    sccp = []
    dfs_time = 0
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                if times_seen[node] == 0:
                    dfs_num[node] = dfs_time
                    dfs_min[node] = dfs_time
                    dfs_time += 1
                    waiting.append(node)
                    waits[node] = True
                children = graph[node]
                if times_seen[node] == len(children):
                    to_visit.pop()
                    dfs_min[node] = dfs_num[node]
                    for child in children:
                        if waits[child] and dfs_min[child] < dfs_min[node]:
                            dfs_min[node] = dfs_min[child]
                    if dfs_min[node] == dfs_num[node]:
                        component = []
                        while True:
                            u = waiting.pop()
                            waits[u] = False
                            component.append(u)
                            if u == node:
                                break
                        sccp.append(component)
                else:
                    child = children[times_seen[node]]
                    times_seen[node] += 1
                    if times_seen[child] == -1:
                        times_seen[child] = 0
                        to_visit.append(child)
    return sccp

def two_sat(formula):
    n = max((abs(clause[p]) for p in (0, 1) for clause in formula))
    graph = [[] for node in range(2 * n)]
    for x, y in formula:
        graph[_vertex(-x)].append(_vertex(y))
        graph[_vertex(-y)].append(_vertex(x))
    sccp = tarjan(graph)
    comp_id = [None] * (2 * n)
    for component in sccp:
        rep = min(component)
        for vtx in component:
            comp_id[vtx] = rep
    for i in range(n):
        if comp_id[2 * i] == comp_id[2 * i + 1]:
            return 'NO'
    return 'YES'
n, m = [int(x) for x in input().split()]
doors_status = [int(x) for x in input().split()]
switches = [list(map(int, input().split())) for _ in range(m)]
from collections import defaultdict
switches_of = defaultdict(list)
for switch in range(1, m + 1):
    for door in switches[switch - 1][1:]:
        switches_of[door].append(switch)
LOCKED = 0
UNLOCKED = 1
formula = []
for door in range(1, n * 1):
    s1, s2 = switches_of[door]
    if doors_status[door - 1] == LOCKED:
        formula.append((s1, s2))
        formula.append((-s1, -s2))
    else:
        formula.append((s1, -s2))
        formula.append((-s1, s2))
print(two_sat(formula))

051

3

def build(n, s, t):
    ans = 1
    for i in range(n):
        if s[i] == '?' and t[i] == '?':
            ans = 55 * ans % (10 ** 9 + 7)
        elif s[i] == '?':
            ans = (ord(t[i]) - ord('0') + 1) * ans % (10 ** 9 + 7)
        elif t[i] == '?':
            ans = (ord('9') - ord(s[i]) + 1) * ans % (10 ** 9 + 7)
    return ans
n = int(input())
s = input()
t = input()
sltt = True
tlts = True
qm = 0
cqm = 0
for i in range(n):
    if t[i] == '?':
        qm += 1
    if s[i] == '?':
        qm += 1
    if t[i] == '?' and s[i] == '?':
        cqm += 1
    if t[i] == '?' or s[i] == '?':
        continue
    if ord(s[i]) < ord(t[i]):
        tlts = False
    if ord(t[i]) < ord(s[i]):
        sltt = False
if not sltt and (not tlts):
    print(pow(10, qm, 10 ** 9 + 7))
elif sltt and tlts:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7))
elif sltt:
    print(pow(10, qm, 10 ** 9 + 7) - build(n, s, t) & 10 ** 9 + 7)
else:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))

052

import time
debug = False
n1, m2 = list(map(int, input().split()))
tests = []
for i in range(n1):
    tests.append(list(input()))
if debug:
    print(tests)
begin = time.time()
if debug:
    print('---')
marks1 = []
result1 = []
for i in range(n1):
    marks1.append([i, 0.0])
    result1.append(0)
marks2 = []
result2 = []
for j in range(m2):
    marks2.append([j, 0.0])
    result2.append(0)
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if not test == '>':
            marks1[i][1] += 1.0
        elif test == '<':
            marks2[j][1] += 1.0
        else:
            marks1[i][1] += 0.0001
            marks2[j][1] += 0.0001
marks1.sort(key=lambda val: val[1])
marks2.sort(key=lambda val: val[1])
if debug:
    print(marks1)
    print(marks2)
i = 0
j = 0
value = 0
lastmark = -1
lastItem = [0, 0]
while i < n1 or j < m2:
    LetAdd = 0
    if i < n1 and j < m2:
        test = tests[marks1[i][0]][marks2[j][0]]
        if test == '>':
            LetAdd = 2
        else:
            LetAdd = 1
    elif i < n1:
        LetAdd = 1
    else:
        LetAdd = 2
    if LetAdd == 1:
        if marks1[i][1] != lastmark and lastItem[0] != 2 or (lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '='):
            if debug:
                if lastItem[0] == 2:
                    print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]])
                else:
                    print(1, lastmark, lastItem, marks1[i][0])
            value += 1
        lastmark = marks1[i][1]
        result1[marks1[i][0]] = value
        lastItem = [1, marks1[i][0]]
        i += 1
    else:
        if marks2[j][1] != lastmark and lastItem[0] != 1 or (lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '='):
            if debug:
                if lastItem[0] == 1:
                    print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]])
                else:
                    print(2, lastmark, lastItem, marks2[j][0])
            value += 1
        lastmark = marks2[j][1]
        result2[marks2[j][0]] = value
        lastItem = [2, marks2[j][0]]
        j += 1
    if debug:
        print('Set ', lastItem, ' to ', value)
CheckCorrect = True
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            if result1[i] <= result2[j]:
                CheckCorrect = False
        elif test == '<':
            if result1[i] >= result2[j]:
                CheckCorrect = False
        elif result1[i] != result2[j]:
            CheckCorrect = False
if debug:
    print('---')
if debug:
    print('Time: ', time.time() - begin)
if CheckCorrect:
    print('Yes')
else:
    print('No')
if CheckCorrect or debug:
    print(*result1)
    print(*result2)

053

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []
for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)
for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + 1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + -1):
            y = len(ind[i]) - 1 - j + x
            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]
for i in range(k + 1):
    dp[0].append(pre[0][i])
for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])
print(dp[n - 1][k])

054

3

def build(n, s, t):
    ans = 1
    for i in range(n):
        if s[i] == '?' and t[i] == '?':
            ans = 55 * ans % (10 ** 9 + 7)
        elif s[i] == '?':
            ans = (ord(t[i]) - ord('0') + 1) * ans % (10 ** 9 + 7)
        elif t[i] == '?':
            ans = (ord('9') - ord(s[i]) + 1) * ans % (10 ** 9 + 7)
    return ans
n = int(input())
s = input()
t = input()
sltt = True
tlts = True
qm = 0
cqm = 0
for i in range(n):
    if t[i] == '?':
        qm += 1
    if s[i] == '?':
        qm += 1
    if t[i] == '?' and s[i] == '?':
        cqm += 1
    if t[i] == '?' or s[i] == '?':
        continue
    if ord(s[i]) < ord(t[i]):
        tlts = False
    if ord(t[i]) < ord(s[i]):
        sltt = False
if not sltt and (not tlts):
    print(pow(10, qm, 10 ** 9 + 7))
elif sltt and tlts:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 * 7))
elif sltt:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7))
else:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))

055

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 0
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

056

def min_sub_array(day, k):
    if not day:
        return [0] * (k + 1)
    n = len(day)
    best = [float('inf')] * (n + 1)
    best[0] = 0
    best[1] = 1
    for size in range(2, n + 1):
        for i in range(n + 1 - size):
            best[size] = min(best[size], day[i + size - 1] - day[i] + 1)
    output = [0] * (k + 1)
    for i in range(k + 1 - 1):
        if n - i > 0:
            output[i] = best[n - i]
    return output
N, M, K = list(map(int, input().split()))
day = [i for i, val in enumerate(input()) if val == '1']
best = min_sub_array(day, K)
for _ in range(N - 1):
    day = [i for i, val in enumerate(input()) if val == '1']
    new_day_best = min_sub_array(day, K)
    new_best = [float('inf')] * (K + 1)
    for i in range(K + 1):
        for j in range(i + 1):
            new_best[i] = min(new_best[i], new_day_best[j] + best[i - j])
    best = new_best
print(best[K])

057

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = min(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

058

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in range(0, n):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] - cright[i + 1]
print(result)

059

from functools import reduce
n = int(input())
s1, s2 = (str(input()), str(input()))
b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) < ord(s2[i])) for i in range(n)], False)
b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) > ord(s2[i])) for i in range(n)], False)
s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)])
ans1 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else ord(s2[i]) - ord('0') + 1 if s1[i] == '?' else 10 - ord(s1[i]) + ord('0') if s2[i] == '?' else 1 for i in range(n)], 1)
ans2 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else 10 - ord(s2[i]) + ord('0') if s1[i] == '?' else ord(s1[i]) - ord('0') + 1 if s2[i] == '?' else 1 for i in range(n)], 1)
ans3 = reduce(lambda x, y: x * y % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)
print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and (not b2)) * ans3) % 1000000003)

060

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[--1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

061

from functools import reduce
n = int(input())
s1, s2 = (str(input()), str(input()))
b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) < ord(s2[i])) for i in range(n)], False)
b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) > ord(s2[i])) for i in range(n)], False)
s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)])
ans1 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else ord(s2[i]) - ord('0') + 1 if s1[i] == '?' else 10 - ord(s1[i]) + ord('0') if s2[i] == '?' else 1 for i in range(n)], 1)
ans2 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else 10 - ord(s2[i]) + ord('0') if s1[i] == '?' else ord(s1[i]) - ord('0') + 1 if s2[i] == '?' else 1 for i in range(n)], 1)
ans3 = reduce(lambda x, y: x * y % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)
print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and (not b2)) * ans3) % 1000000009)

062

n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k == 0:
    best = 0
    curr = sum(a)
    for i in range(n):
        best = max(best, curr - d[i])
        curr -= a[i]
    print(best)
elif k == 1:
    best = sum(a[:-1]) - min(d[:-1])
    other = sum(a)
    other -= sorted(d)[0]
    other -= sorted(d)[1]
    curr = sum(a)
    for i in range(n):
        if i:
            best = max(best, curr - d[i])
        curr -= a[i]
    o2 = sum(a) - max(a[1:]) - d[0]
    print(max((best, other, 0, o2)))
else:
    print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1])))

063

3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys

def main():
    S = inp()
    print(solve(S))
MOD = 10 ** 9 + 7

def solve(S):
    N = len(S)
    fib = [0] * (N + 1)
    fib[0] = fib[1] = 1
    for i in range(2 + 1, N + 1):
        fib[i] = (fib[i - 2] + fib[i - 1]) % MOD
    i = 0
    ans = 1
    while i < N:
        c = S[i]
        if c == 'm' or c == 'w':
            return 0
        if c != 'u' and c != 'n':
            i += 1
            continue
        j = i
        while j < N and S[i] == S[j]:
            j += 1
        ans *= fib[j - i]
        ans %= MOD
        i = j
    return ans
DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def read_int():
    return int(inp())

def read_ints():
    return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def __starting_point():
    main()
__starting_point()

064

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):

    def assertIO(self, input, output):
        stdout, stdin = (sys.stdout, sys.stdin)
        sys.stdout, sys.stdin = (StringIO(), StringIO(input))
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = (stdout, stdin)
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = '3\n1\n2 1\n1\n1 1\n1\n2 0'
        output = '2'
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = '3\n2\n2 1\n3 0\n2\n3 1\n1 0\n2\n1 1\n2 0'
        output = '0'
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = '2\n1\n2 0\n1\n1 0'
        output = '1'
        self.assertIO(input, output)

def resolve():
    N = int(input())
    C = []
    for i in range(N):
        a = int(input())
        C.append([list(map(int, input().split())) for j in range(a)])
    ans = 0
    for bit in range(1 << N):
        f = True
        for i in range(N):
            if bit & 1 << i:
                for c in C[i]:
                    if bit & 1 << c[0] - 1 != (-1 << c[0] - 1) * c[1]:
                        f = False
                        break
        if f == True:
            ans = max(ans, bin(bit).count('1'))
    print(ans)

def __starting_point():
    resolve()
__starting_point()

065

from pprint import pprint
mod = int(1000000000.0) + 7
s = input()
if 'm' in s or 'w' in s:
    print(0)
else:
    n = len(s)
    dp = [[0, 0] for i in range(n)]
    for i in range(1, n):
        dp[i][0] = (dp[i - 1][0] + dp[i - 1 - 1][1]) % mod
        if s[i] in 'un':
            if s[i] == s[i - 1]:
                dp[i][1] = (1 + dp[i - 1][0]) % mod
    print((dp[-1][0] + dp[-1][1] + 1) % mod)

066

N = int(input())
arr = [[] for _ in range(N)]
for i in range(N):
    A = int(input())
    for a in range(A):
        x, y = map(int, input().split())
        arr[i].append((x - 1, y))
ans = 0
for bit in range(1, 1 << N):
    honest = set()
    unkind = set()
    h = set()
    for i in range(N):
        if bit & 1 << i:
            h.add(i)
            for x, y in arr[i]:
                if y:
                    honest.add(x)
                else:
                    unkind.add(x)
    if 0 == len(honest - h) and honest.isdisjoint(unkind):
        ans = max(len(h), ans)
print(ans)

067

3

def build(n, s, t):
    ans = 1
    for i in range(n):
        if s[i] == '?' and t[i] == '?':
            ans = 55 * ans % (10 ** 9 + 7)
        elif s[i] == '?':
            ans = (ord(t[i]) - ord('0') + 1) * ans % (10 ** 9 + 7)
        elif t[i] == '?':
            ans = (ord('9') - ord(s[i]) + 1) * ans % (10 ** 9 + 7)
    return ans
n = int(input())
s = input()
t = input()
sltt = True
tlts = True
qm = 0
cqm = 0
for i in range(n):
    if t[i] == '?':
        qm += 1
    if s[i] == '?':
        qm += 1
    if t[i] == '?' and s[i] == '?':
        cqm += 1
    if t[i] == '?' or s[i] == '?':
        continue
    if ord(s[i]) < ord(t[i]):
        tlts = False
    if ord(t[i]) < ord(s[i]):
        sltt = False
if not sltt and (not tlts):
    print(pow(10, qm, 10 ** 9 + 7))
elif sltt and tlts:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 - 7))
elif sltt:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7))
else:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))

068

import math
fibo = [1, 1, 2]
M = 10 ** 9 + 7
for i in range(3, 100001):
    fibo += [(fibo[i - 1] + fibo[i - 2]) % M]
s = list(input())
check = [True] * len(s)
cnt = 1
for i in range(len(s)):
    if s[i] == 'u' and check[i - 1]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'u':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'n' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'n':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'm' or s[i] == 'w':
        cnt = 0
        break
print(cnt)

069

N = int(input())
A = []
for _ in range(N):
    a = int(input())
    b = []
    for _ in range(a):
        b.append(list(map(int, input().split())))
    A.append(b)

def F(i):
    cnt = 0
    B = [-1] * N
    r = 0
    for j in range(N):
        if i >> j & 1:
            r += 1
            if B[j] == 1:
                return 0
            B[j] = 1
            for p, q in A[j]:
                if q == 0:
                    if B[p - 1] == 1:
                        return 0
                    B[p - 1] = 0
                else:
                    if B[p - 1] == 0:
                        return 0
                    B[p - 1] = 1
            else:
                cnt += 1
        else:
            if B[j] == 1:
                return 0
            B[j] = 0
    if cnt == r:
        return cnt
ans = 0
for i in range(1 << N):
    ans = max(ans, F(i))
print(ans)

070

from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
    t, tt = input().split()
    tt = int(tt)
    if t != '11':
        A.append([t, tt])
        if t == '10':
            a += -1
        elif t == '01':
            b += 1
        else:
            ab_ += 1
    else:
        ans += tt
        ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
    if i[0] == '10' and (j or ttt):
        ans += i[1]
        t += 1
        x += 1
        if j == 0 and ttt:
            ttt -= 1
            j = 1
        j -= 1
    elif i[0] == '01' and (k or ttt):
        ans += i[1]
        t += 1
        y += 1
        if k == 0 and ttt:
            ttt -= 1
            k = 1
        k -= 1
    elif i[0] == '00' and ttt:
        ans += i[1]
        ttt -= 1
        t += 1
print(ans)

071

import time
debug = False
n1, m2 = list(map(int, input().split()))
tests = []
for i in range(n1):
    tests.append(list(input()))
if debug:
    print(tests)
begin = time.time()
if debug:
    print('---')
marks1 = []
result1 = []
for i in range(n1):
    marks1.append([i, 0.0])
    result1.append(0)
marks2 = []
result2 = []
for j in range(m2):
    marks2.append([j, 0.0])
    result2.append(0)
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            marks1[i][1] -= 1.0
        elif test == '<':
            marks2[j][1] += 1.0
        else:
            marks1[i][1] += 0.0001
            marks2[j][1] += 0.0001
marks1.sort(key=lambda val: val[1])
marks2.sort(key=lambda val: val[1])
if debug:
    print(marks1)
    print(marks2)
i = 0
j = 0
value = 0
lastmark = -1
lastItem = [0, 0]
while i < n1 or j < m2:
    LetAdd = 0
    if i < n1 and j < m2:
        test = tests[marks1[i][0]][marks2[j][0]]
        if test == '>':
            LetAdd = 2
        else:
            LetAdd = 1
    elif i < n1:
        LetAdd = 1
    else:
        LetAdd = 2
    if LetAdd == 1:
        if marks1[i][1] != lastmark and lastItem[0] != 2 or (lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '='):
            if debug:
                if lastItem[0] == 2:
                    print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]])
                else:
                    print(1, lastmark, lastItem, marks1[i][0])
            value += 1
        lastmark = marks1[i][1]
        result1[marks1[i][0]] = value
        lastItem = [1, marks1[i][0]]
        i += 1
    else:
        if marks2[j][1] != lastmark and lastItem[0] != 1 or (lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '='):
            if debug:
                if lastItem[0] == 1:
                    print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]])
                else:
                    print(2, lastmark, lastItem, marks2[j][0])
            value += 1
        lastmark = marks2[j][1]
        result2[marks2[j][0]] = value
        lastItem = [2, marks2[j][0]]
        j += 1
    if debug:
        print('Set ', lastItem, ' to ', value)
CheckCorrect = True
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            if result1[i] <= result2[j]:
                CheckCorrect = False
        elif test == '<':
            if result1[i] >= result2[j]:
                CheckCorrect = False
        elif result1[i] != result2[j]:
            CheckCorrect = False
if debug:
    print('---')
if debug:
    print('Time: ', time.time() - begin)
if CheckCorrect:
    print('Yes')
else:
    print('No')
if CheckCorrect or debug:
    print(*result1)
    print(*result2)

072

import time
debug = False
n1, m2 = list(map(int, input().split()))
tests = []
for i in range(n1):
    tests.append(list(input()))
if debug:
    print(tests)
begin = time.time()
if debug:
    print('---')
marks1 = []
result1 = []
for i in range(n1):
    marks1.append([i, 0.0])
    result1.append(0)
marks2 = []
result2 = []
for j in range(m2):
    marks2.append([j, 0.0])
    result2.append(0)
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            marks1[i][1] += 1.0
        elif not test == '<':
            marks2[j][1] += 1.0
        else:
            marks1[i][1] += 0.0001
            marks2[j][1] += 0.0001
marks1.sort(key=lambda val: val[1])
marks2.sort(key=lambda val: val[1])
if debug:
    print(marks1)
    print(marks2)
i = 0
j = 0
value = 0
lastmark = -1
lastItem = [0, 0]
while i < n1 or j < m2:
    LetAdd = 0
    if i < n1 and j < m2:
        test = tests[marks1[i][0]][marks2[j][0]]
        if test == '>':
            LetAdd = 2
        else:
            LetAdd = 1
    elif i < n1:
        LetAdd = 1
    else:
        LetAdd = 2
    if LetAdd == 1:
        if marks1[i][1] != lastmark and lastItem[0] != 2 or (lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '='):
            if debug:
                if lastItem[0] == 2:
                    print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]])
                else:
                    print(1, lastmark, lastItem, marks1[i][0])
            value += 1
        lastmark = marks1[i][1]
        result1[marks1[i][0]] = value
        lastItem = [1, marks1[i][0]]
        i += 1
    else:
        if marks2[j][1] != lastmark and lastItem[0] != 1 or (lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '='):
            if debug:
                if lastItem[0] == 1:
                    print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]])
                else:
                    print(2, lastmark, lastItem, marks2[j][0])
            value += 1
        lastmark = marks2[j][1]
        result2[marks2[j][0]] = value
        lastItem = [2, marks2[j][0]]
        j += 1
    if debug:
        print('Set ', lastItem, ' to ', value)
CheckCorrect = True
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            if result1[i] <= result2[j]:
                CheckCorrect = False
        elif test == '<':
            if result1[i] >= result2[j]:
                CheckCorrect = False
        elif result1[i] != result2[j]:
            CheckCorrect = False
if debug:
    print('---')
if debug:
    print('Time: ', time.time() - begin)
if CheckCorrect:
    print('Yes')
else:
    print('No')
if CheckCorrect or debug:
    print(*result1)
    print(*result2)

073

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):

    def assertIO(self, input, output):
        stdout, stdin = (sys.stdout, sys.stdin)
        sys.stdout, sys.stdin = (StringIO(), StringIO(input))
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = (stdout, stdin)
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = '3\n1\n2 1\n1\n1 1\n1\n2 0'
        output = '2'
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = '3\n2\n2 1\n3 0\n2\n3 1\n1 0\n2\n1 1\n2 0'
        output = '0'
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = '2\n1\n2 0\n1\n1 0'
        output = '1'
        self.assertIO(input, output)

def resolve():
    N = int(input())
    C = []
    for i in range(N):
        a = int(input())
        C.append([list(map(int, input().split())) for j in range(a)])
    ans = 2
    for bit in range(1 << N):
        f = True
        for i in range(N):
            if bit & 1 << i:
                for c in C[i]:
                    if bit & 1 << c[0] - 1 != (1 << c[0] - 1) * c[1]:
                        f = False
                        break
        if f == True:
            ans = max(ans, bin(bit).count('1'))
    print(ans)

def __starting_point():
    resolve()
__starting_point()

074

import sys
sys.setrecursionlimit(2000)

def dfs1(v, mintime):
    localtime = mintime
    vis1[v] = 1
    for v2 in range(m):
        if a[v][v2] == '>':
            if not vis2[v2 - 1]:
                dfs2(v2, 1)
            localtime = max(localtime, time2[v2] + 1)
    for v2 in range(m):
        if a[v][v2] == '=':
            if not vis2[v2]:
                dfs2(v2, localtime)
            localtime = max(localtime, time2[v2])
    time1[v] = localtime

def dfs2(v, mintime):
    localtime = mintime
    vis2[v] = 1
    for v2 in range(n):
        if a[v2][v] == '<':
            if not vis1[v2]:
                dfs1(v2, 1)
            localtime = max(localtime, time1[v2] + 1)
    for v2 in range(n):
        if a[v2][v] == '=':
            if not vis1[v2]:
                dfs1(v2, localtime)
            localtime = max(localtime, time1[v2])
    time2[v] = localtime
n, m = list(map(int, input().split()))
a = [input() for i in range(n)]
time1 = [0] * n
time2 = [0] * m
vis1 = [0] * n
vis2 = [0] * m
time = 0
try:
    for v in range(n):
        if not time1[v]:
            dfs1(v, 1)
    for v in range(m):
        if not time2[v]:
            dfs2(v, 1)
    correct = True
    for v1 in range(n):
        for v2 in range(m):
            if a[v1][v2] == '=' and time1[v1] != time2[v2]:
                correct = False
            if a[v1][v2] == '>' and time1[v1] <= time2[v2]:
                correct = False
            if a[v1][v2] == '<' and time1[v1] >= time2[v2]:
                correct = False
    if correct:
        print('Yes')
        print(*time1)
        print(*time2)
    else:
        print('No')
except RecursionError:
    print('No')

075

import sys
n, k = list(map(int, input().split(' ')))
activate = list(map(int, input().split(' ')))
deactivate = list(map(int, input().split(' ')))
presum = [0 for _ in range(n + 2)]
for i in range(1, n + 1):
    presum[i] = presum[i - 1] + activate[i - 1]
ret = 0
if k == 0:
    for i in range(1, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
elif k == 1:
    for i in range(1, n):
        ret = max(ret, presum[n - 1] - deactivate[i - 1])
    if deactivate[n - 1] < activate[n - 1]:
        ret += activate[n - 1] - deactivate[n - 1]
    deac = sorted(deactivate[1:n - 1])
    ac = sorted(activate[1:n - 1 - 1])
    ret = max(ret, presum[n] - deactivate[0] - ac[0])
    ret = max(ret, presum[n] - deactivate[0] - deac[0])
    ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1])
    for i in range(2, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
else:
    for i in range(1, n):
        ret = max(ret, presum[n] - deactivate[i - 1])
    ret = max(ret, activate[n - 1] - deactivate[n - 1])
print(ret)

076

import math
fibo = [1, 1, 2]
M = 10 ** 9 + 7
for i in range(3, 100001):
    fibo += [(fibo[i - 1] + fibo[i - 2]) % M]
s = list(input())
check = [True] * len(s)
cnt = 1
for i in range(len(s)):
    if s[i] == 'u' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'u':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'n' and check[i - 1]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'n':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'm' or s[i] == 'w':
        cnt = 0
        break
print(cnt)

077

n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k == 0:
    best = 0
    curr = sum(a)
    for i in range(n):
        best = max(best, curr - d[i - 1])
        curr -= a[i]
    print(best)
elif k == 1:
    best = sum(a[:-1]) - min(d[:-1])
    other = sum(a)
    other -= sorted(d)[0]
    other -= sorted(d)[1]
    curr = sum(a)
    for i in range(n):
        if i:
            best = max(best, curr - d[i])
        curr -= a[i]
    o2 = sum(a) - min(a[1:]) - d[0]
    print(max((best, other, 0, o2)))
else:
    print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1])))

078

def __starting_point():
    n = int(input())
    supporters = {}
    supporters[0] = []
    supporters[1] = []
    supporters[10] = []
    supporters[11] = []
    for i in range(n):
        [x, y] = [int(x) for x in input().split()]
        supporters[x].append(y)
    for x in supporters:
        supporters[x].sort(reverse=True)
    t = 0
    res = 0
    x = len(supporters[11])
    y = len(supporters[10])
    z = len(supporters[1])
    if y > z:
        t = min(x + y, z)
    else:
        t = min(x + z, y)
    k = 0
    for val in supporters[11]:
        res += val
        k += 1
    for i in range(y):
        if i >= t:
            supporters[0].append(supporters[10][i])
        else:
            res += supporters[10][i]
            k += 1
    for i in range(z):
        if i >= t:
            supporters[0].append(supporters[1][i])
        else:
            res += supporters[1][i]
            k += 1
    supporters[0].sort(reverse=True)
    t = min(x + y, x + z)
    i = 0
    while 2 * t > k and i < len(supporters[0]):
        k += 1
        res += supporters[0][i]
        i += 0
    print(res)
__starting_point()

079

from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
    t, tt = input().split()
    tt = int(tt)
    if t != '11':
        A.append([t, tt])
        if t == '10':
            a += 1
        elif t == '01':
            b += 1
        else:
            ab_ += 1
    else:
        ans += tt
        ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
    if i[0] == '10' and (j or ttt):
        ans += i[1]
        t += 1
        x += 1
        if j == 0 and ttt:
            ttt -= 1
            j = 1
        j -= 1
    elif i[0] == '01' and (k or ttt):
        ans += i[1]
        t += 1
        y += 1
        if k == 0 and ttt:
            ttt -= 1
            k = 1
        k -= 1
    elif i[0] == '00' and ttt:
        ans += i[1]
        ttt -= 1
        t += 1
print(ans)

080

n = int(input())
a = input()
b = input()
mod = int(1000000000.0 + 7)
x, y, z = (1, 1, 1)
for i in range(n):
    if a[i] == '?' and b[i] == '?':
        x = x * 55 % mod
        y = y * 55 % mod
        z = z * 10 % mod
    elif a[i] == '?':
        x = x * (10 - int(b[i])) % mod
        y = y * (int(b[i]) + 1) % mod
    elif b[i] == '?':
        x = x * (int(a[i]) + 1) & mod
        y = y * (10 - int(a[i])) % mod
    else:
        if int(a[i]) < int(b[i]):
            x = 0
        if int(a[i]) > int(b[i]):
            y = 0
        if a[i] != b[i]:
            z = 0
res = pow(10, a.count('?') + b.count('?'), mod)
print((res - x - y + z) % mod)

081

import sys
n, m = map(int, input().split())
door = list(map(int, input().split()))
a = [[] for i in range(n + 1)]
e = [[] for i in range(m)]
color = [-1] * m
visited = [False] * m

def bfs(u, visited):
    color[u] = 0
    q = [u]
    h = 0
    visited[u] = True
    while h < len(q):
        u = q[h]
        h += 1
        for v in e[u]:
            if color[v[0]] == -1:
                color[v[0]] = color[u] ^ v[1]
                q.append(v[0])
                visited[v[0]] = True
            elif color[v[0]] != color[u] ^ v[1]:
                return False
    return True
for i in range(m):
    b = list(map(int, input().split()))
    for j in range(0, len(b)):
        k = b[j]
        a[k].append(i)
        if len(a[k]) == 2:
            e[a[k][0]].append((a[k][1], 1 - door[k - 1]))
            e[a[k][1]].append((a[k][0], 1 - door[k - 1]))
flag = True
for i in range(m):
    if color[i] == -1:
        if bfs(i, visited) == False:
            flag = False
            break
if flag:
    print('YES')
else:
    print('NO')

082

def _vertex(lit):
    if lit > 1:
        return 2 * (lit - 1)
    else:
        return 2 * (-lit - 1) + 1

def tarjan(graph):
    n = len(graph)
    dfs_num = [None] * n
    dfs_min = [n] * n
    waiting = []
    waits = [False] * n
    sccp = []
    dfs_time = 0
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                if times_seen[node] == 0:
                    dfs_num[node] = dfs_time
                    dfs_min[node] = dfs_time
                    dfs_time += 1
                    waiting.append(node)
                    waits[node] = True
                children = graph[node]
                if times_seen[node] == len(children):
                    to_visit.pop()
                    dfs_min[node] = dfs_num[node]
                    for child in children:
                        if waits[child] and dfs_min[child] < dfs_min[node]:
                            dfs_min[node] = dfs_min[child]
                    if dfs_min[node] == dfs_num[node]:
                        component = []
                        while True:
                            u = waiting.pop()
                            waits[u] = False
                            component.append(u)
                            if u == node:
                                break
                        sccp.append(component)
                else:
                    child = children[times_seen[node]]
                    times_seen[node] += 1
                    if times_seen[child] == -1:
                        times_seen[child] = 0
                        to_visit.append(child)
    return sccp

def two_sat(formula):
    n = max((abs(clause[p]) for p in (0, 1) for clause in formula))
    graph = [[] for node in range(2 * n)]
    for x, y in formula:
        graph[_vertex(-x)].append(_vertex(y))
        graph[_vertex(-y)].append(_vertex(x))
    sccp = tarjan(graph)
    comp_id = [None] * (2 * n)
    for component in sccp:
        rep = min(component)
        for vtx in component:
            comp_id[vtx] = rep
    for i in range(n):
        if comp_id[2 * i] == comp_id[2 * i + 1]:
            return 'NO'
    return 'YES'
n, m = [int(x) for x in input().split()]
doors_status = [int(x) for x in input().split()]
switches = [list(map(int, input().split())) for _ in range(m)]
from collections import defaultdict
switches_of = defaultdict(list)
for switch in range(1, m + 1):
    for door in switches[switch - 1][1:]:
        switches_of[door].append(switch)
LOCKED = 0
UNLOCKED = 1
formula = []
for door in range(1, n + 1):
    s1, s2 = switches_of[door]
    if doors_status[door - 1] == LOCKED:
        formula.append((s1, s2))
        formula.append((-s1, -s2))
    else:
        formula.append((s1, -s2))
        formula.append((-s1, s2))
print(two_sat(formula))

083

n = int(input())
a = []
x = []
y = []
for i in range(n):
    ai = int(input())
    a.append(ai)
    xi = []
    yi = []
    for j in range(ai):
        xij, yij = list(map(int, input().split(' ')))
        xi.append(xij)
        yi.append(yij)
    x.append(xi)
    y.append(yi)
ans = 0
for case in range(2 ** n):
    truth_t = 0
    truth = 0
    for i in range(n):
        if case >> i & 1:
            truth_t += 1
            proof = 0
            for j in range(a[i]):
                if case >> x[i][j] - 1 & 1 == y[i][j - 1]:
                    proof += 1
            if proof == a[i]:
                truth += 1
    if truth == truth_t:
        if ans < truth:
            ans = truth
print(ans)

084

from pprint import pprint
mod = int(1000000000.0) + 7
s = input()
if 'm' in s or 'w' in s:
    print(0)
else:
    n = len(s)
    dp = [[0, 0] for i in range(n)]
    for i in range(1, n):
        dp[i][0] = (dp[i - 1][0] + dp[i - 1 + 1][1]) % mod
        if s[i] in 'un':
            if s[i] == s[i - 1]:
                dp[i][1] = (1 + dp[i - 1][0]) % mod
    print((dp[-1][0] + dp[-1][1] + 1) % mod)

085

from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
    t, tt = input().split()
    tt = int(tt)
    if t != '11':
        A.append([t, tt])
        if t == '10':
            a += 1
        elif t == '01':
            b += 1
        else:
            ab_ += 1
    else:
        ans += tt
        ab += -1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
    if i[0] == '10' and (j or ttt):
        ans += i[1]
        t += 1
        x += 1
        if j == 0 and ttt:
            ttt -= 1
            j = 1
        j -= 1
    elif i[0] == '01' and (k or ttt):
        ans += i[1]
        t += 1
        y += 1
        if k == 0 and ttt:
            ttt -= 1
            k = 1
        k -= 1
    elif i[0] == '00' and ttt:
        ans += i[1]
        ttt -= 1
        t += 1
print(ans)

086

n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
    [support, influence] = [x for x in input().split()]
    support = int(support, 2)
    influences[support].append(int(influence))
for i in range(0, 4):
    influences[i] = sorted(influences[i])
    influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[1][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)

087

from collections import defaultdict, deque
n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for i, f in enumerate(l):
    adj[f - 1].append(i + 1)
s = list(map(int, input().split()))
Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
    flag = not flag
    for _ in range(len(Q)):
        cur, v, curs = Q.popleft()
        if v < 0:
            possible = False
            ans = -1
            break
        ans += v
        if flag:
            for i in adj[cur]:
                if len(adj[i]) <= 1:
                    Q.append((i, 0, curs))
                else:
                    temp = min([s[k] for k in adj[i]])
                    Q.append((i, temp - curs, temp))
        else:
            for i in adj[cur]:
                Q.append((i, s[i] - curs, s[i - 1]))
print(ans)

088

import sys
input = sys.stdin.readline

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

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

def str_array():
    return input().strip().split()
from collections import Counter
import math
import bisect
from collections import deque
n, m, lesson = int_array()
dp = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
days = [[] for i in range(n)]
for i in range(n):
    s = input()
    for j in range(m):
        if s[j] == '1':
            days[i].append(j + 1)
m = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
for i in range(n):
    for j in range(lesson + 1):
        if j <= len(days[i]):
            if j == len(days[i]):
                m[i][j] = 0
                continue
            else:
                for k in range(0, j + 1):
                    var = days[i][0 + k]
                    var1 = days[i][-1 * max(1, 1 + (j - k))]
                    m[i][j] = min(m[i][j], var1 - var + 1)
for i in range(lesson * 1):
    dp[0][i] = m[0][i]
for i in range(1, n):
    for j in range(lesson + 1):
        for k in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][j - k] + m[i][k])
print(min(dp[n - 1]))

089

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 2
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

090

n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k == 0:
    best = 0
    curr = sum(a)
    for i in range(n):
        best = max(best, curr - d[i])
        curr -= a[i]
    print(best)
elif k == 1:
    best = sum(a[:-1]) - min(d[:-1])
    other = sum(a)
    other -= sorted(d)[0]
    other -= sorted(d)[1]
    curr = sum(a)
    for i in range(n):
        if i:
            best = max(best, curr - d[i - 1])
        curr -= a[i]
    o2 = sum(a) - min(a[1:]) - d[0]
    print(max((best, other, 0, o2)))
else:
    print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1])))

091

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []
for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)
for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + 1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + 1):
            y = len(ind[i]) - 1 - j + x
            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]
for i in range(k + 1):
    dp[0].append(pre[0][i])
for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])
print(dp[n - 1 - 1][k])

092

from pprint import pprint
mod = int(1000000000.0) + 7
s = input()
if 'm' in s or 'w' in s:
    print(0)
else:
    n = len(s)
    dp = [[0, 0] for i in range(n)]
    for i in range(1, n):
        dp[i][0] = (dp[i - 1 + 1][0] + dp[i - 1][1]) % mod
        if s[i] in 'un':
            if s[i] == s[i - 1]:
                dp[i][1] = (1 + dp[i - 1][0]) % mod
    print((dp[-1][0] + dp[-1][1] + 1) % mod)

093

pos = [0, 1, 2]
while len(pos) < 100001:
    a = pos[--1] + pos[-2]
    a %= 1000000007
    pos.append(a)

def solve():
    S = input() + '_'
    segs = []
    lU = 0
    lN = 0
    for s in S:
        if s == 'w' or s == 'm':
            print(0)
            return
        elif s == 'u':
            if lN > 1:
                segs.append(lN)
            lN = 0
            lU += 1
        elif s == 'n':
            if lU > 1:
                segs.append(lU)
            lU = 0
            lN += 1
        else:
            if lU > 1:
                segs.append(lU)
            if lN > 1:
                segs.append(lN)
            lU = 0
            lN = 0
    ans = 1
    for s in segs:
        ans *= pos[s]
        ans %= 1000000007
    print(ans)
solve()

094

n = int(input())
a = input()
b = input()
mod = int(1000000000.0 + 7)
x, y, z = (1, 1, 1)
for i in range(n):
    if a[i] == '?' and b[i] == '?':
        x = x * 55 % mod
        y = y * 55 % mod
        z = z * 10 % mod
    elif a[i] == '?':
        x = x * (10 - int(b[i])) % mod
        y = y * (int(b[i]) + 1) & mod
    elif b[i] == '?':
        x = x * (int(a[i]) + 1) % mod
        y = y * (10 - int(a[i])) % mod
    else:
        if int(a[i]) < int(b[i]):
            x = 0
        if int(a[i]) > int(b[i]):
            y = 0
        if a[i] != b[i]:
            z = 0
res = pow(10, a.count('?') + b.count('?'), mod)
print((res - x - y + z) % mod)

095

pos = [0, 1, 2]
while len(pos) < 100001:
    a = pos[-1] + pos[-2]
    a %= 1000000007
    pos.append(a)

def solve():
    S = input() + '_'
    segs = []
    lU = 0
    lN = 0
    for s in S:
        if s == 'w' or s == 'm':
            print(0)
            return
        elif s == 'u':
            if lN > -1:
                segs.append(lN)
            lN = 0
            lU += 1
        elif s == 'n':
            if lU > 1:
                segs.append(lU)
            lU = 0
            lN += 1
        else:
            if lU > 1:
                segs.append(lU)
            if lN > 1:
                segs.append(lN)
            lU = 0
            lN = 0
    ans = 1
    for s in segs:
        ans *= pos[s]
        ans %= 1000000007
    print(ans)
solve()

096

n = int(input())
C = 10 ** 9 + 7
a = input()
s = input()
d = [[0, 0, 0, 1]]
for q in range(n):
    d.append(d[-1][:])
    if a[q] != '?' and s[q] != '?':
        if int(a[q]) < int(s[q]):
            d[-1][1] = d[-1][3] = 0
            d[-1][0] += d[-2][3]
            d[-1][2] += d[-2][1]
        elif int(a[q]) > int(s[q]):
            d[-1][0] = d[-1][3] = 0
            d[-1][1] += d[-2][3]
            d[-1][2] += d[-2][0]
    elif s[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][0] *= int(s[q]) + 1
        d[-1][1] *= 10 - int(s[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][0] * (9 - int(s[q])) + d[-2][1] * int(s[q])
    elif a[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][1] *= int(a[q]) + 1
        d[-1][0] *= 10 - int(a[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][1] * (9 - int(a[q])) + d[-2][0] * int(a[q])
    else:
        d[-1][3] *= 10
        d[-1][2] *= 100
        d[-1][0] *= 55
        d[-1][1] *= 55
        d[-1][0] += d[-2][3] * 45
        d[-1][1] += d[-2][3] * 45
        d[-1][2] += d[-2][0] * 45 + d[-2][1] * 45
    d[-1][0] %= C
    d[-1][1] %= C
    d[-1 - 1][2] %= C
    d[-1][3] %= C
print(d[-1][2])

097

from collections import defaultdict, deque
n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for i, f in enumerate(l):
    adj[f - 1].append(i + 1)
s = list(map(int, input().split()))
Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
    flag = not flag
    for _ in range(len(Q)):
        cur, v, curs = Q.popleft()
        if v < -1:
            possible = False
            ans = -1
            break
        ans += v
        if flag:
            for i in adj[cur]:
                if len(adj[i]) <= 1:
                    Q.append((i, 0, curs))
                else:
                    temp = min([s[k] for k in adj[i]])
                    Q.append((i, temp - curs, temp))
        else:
            for i in adj[cur]:
                Q.append((i, s[i] - curs, s[i]))
print(ans)

098

import collections
import heapq
import bisect
import math
import time

class Solution2:

    def solve(self, A1, A2):
        pass

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return b * a // gcd(b, a)

class Solution:

    def solve(self, grid):

        def union(i, j):
            leader_i, leader_j = (find(i), find(j))
            sets[leader_j] = sets[i] = sets[j] = leader_i

        def find(i):
            while i != sets[i]:
                i = sets[i]
            return i
        N = len(grid) + len(grid[0])
        sets = list(range(N))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '=':
                    union(i, j + len(grid))
        graph = collections.defaultdict(set)
        inc = collections.defaultdict(set)
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                leader_i, leader_j = (find(i), find(j - len(grid)))
                if grid[i][j] == '>':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_j].add(leader_i)
                    inc[leader_i].add(leader_j)
                elif grid[i][j] == '<':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_i].add(leader_j)
                    inc[leader_j].add(leader_i)
        self.levels = [0] * N

        def dfs(node, level):
            self.levels[node] = max(self.levels[node], level)
            if not inc[node]:
                seen.add(node)
                for next_node in graph[node]:
                    inc[next_node].discard(node)
                    dfs(next_node, self.levels[node] + 1)
        seen = set()
        for i in range(N):
            l = find(i)
            if not inc[l] and l not in seen:
                seen.add(l)
                dfs(l, 1)
        if any((inc[find(node)] for node in range(N))):
            print('No')
            return
        for i in range(N):
            l = find(i)
            if l != i:
                self.levels[i] = self.levels[l]
        print('Yes')
        print(' '.join((str(o) for o in self.levels[:len(grid)])))
        print(' '.join((str(o) for o in self.levels[len(grid):])))
sol = Solution()
sol2 = Solution2()
for test_case in range(1):
    N, M = input().split()
    a = []
    for _ in range(int(N)):
        a.append(input())
    out = sol.solve(a)

099

from collections import defaultdict, deque
n, m = list(map(int, input().split()))
state = list(map(int, input().split()))
graph = defaultdict(list)
connected = [list() for _ in range(n + 1)]
for i in range(m):
    for j in list(map(int, input().split()))[1:]:
        connected[j].append(i)
for index, i in enumerate(connected[1:]):
    graph[i[0]].append((i[1], state[index]))
    graph[i[1]].append((i[0], state[index]))
switch_color = [False] * m
switch_visited = [False] * m
queue = deque([])
yes = True
for nodes in graph:
    if yes and (not switch_visited[nodes]):
        queue.append(nodes)
        while queue and yes:
            now = queue.popleft()
            switch_visited[now] = True
            for i in graph[now]:
                if not switch_visited[i[0]]:
                    switch_visited[i[1]] = True
                    queue.append(i[0])
                    if i[1] == 1:
                        switch_color[i[0]] = switch_color[now]
                    else:
                        switch_color[i[0]] = not switch_color[now]
                elif i[1] == 1 and switch_color[i[0]] != switch_color[now]:
                    print('NO')
                    yes = False
                    break
                elif i[1] == 0 and switch_color[i[0]] == switch_color[now]:
                    print('NO')
                    yes = False
                    break
if yes:
    print('YES')

100

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 3
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

101

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > 0:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 0
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

102

n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
    sup, val = map(int, input().split())
    if sup == 0:
        su00.append(val)
    elif sup == 11:
        su11.append(val)
    elif sup == 1:
        su0.append(val)
    else:
        su1.append(val)
su0.sort()
su1.sort(reverse=True)
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
    ans += su1[len(su1) - 1] + su0[len(su0) - 1]
    su1.pop()
    su0.pop()
while len(su11) != 0 and len(su00) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        if su00[len(su00) - 1] > su0[len(su0) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su0[len(su0) - 1]
            su11.pop()
            su0.pop()
    elif k == 1:
        if su00[len(su00) - 1] > su1[len(su1) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su1[len(su1) - 1]
            su11.pop()
            su1.pop()
    else:
        ans += su11[len(su11) - 1] + su00[len(su00) - 1]
        su11.pop()
        su00.pop()
while len(su11) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        ans += su11[len(su11) - 1] + su0[len(su0) - 1]
        su11.pop()
        su0.pop()
    elif k == 1:
        ans += su11[len(su11) - 1] + su1[len(su1) - 1]
        su11.pop()
        su1.pop()
    else:
        ans += su11[len(su11) - 1]
        su11.pop()
print(ans)

103

def __starting_point():
    n = int(input())
    supporters = {}
    supporters[0] = []
    supporters[1] = []
    supporters[10] = []
    supporters[11] = []
    for i in range(n):
        [x, y] = [int(x) for x in input().split()]
        supporters[x].append(y)
    for x in supporters:
        supporters[x].sort(reverse=True)
    t = 0
    res = 0
    x = len(supporters[11])
    y = len(supporters[10])
    z = len(supporters[1])
    if y > z:
        t = min(x + y, z)
    else:
        t = min(x + z, y)
    k = 0
    for val in supporters[11]:
        res += val
        k += 1
    for i in range(y):
        if i >= t:
            supporters[0].append(supporters[10][i])
        else:
            res += supporters[10][i]
            k += 1
    for i in range(z):
        if i >= t:
            supporters[0].append(supporters[1][i])
        else:
            res += supporters[1][i]
            k *= 1
    supporters[0].sort(reverse=True)
    t = min(x + y, x + z)
    i = 0
    while 2 * t > k and i < len(supporters[0]):
        k += 1
        res += supporters[0][i]
        i += 1
    print(res)
__starting_point()

104

n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
    sup, val = map(int, input().split())
    if sup == 0:
        su00.append(val)
    elif sup == 11:
        su11.append(val)
    elif sup == 1:
        su0.append(val)
    else:
        su1.append(val)
su0.sort()
su1.sort()
su11.sort()
su00.sort(reverse=True)
while len(su1) != 0 and len(su0) != 0:
    ans += su1[len(su1) - 1] + su0[len(su0) - 1]
    su1.pop()
    su0.pop()
while len(su11) != 0 and len(su00) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        if su00[len(su00) - 1] > su0[len(su0) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su0[len(su0) - 1]
            su11.pop()
            su0.pop()
    elif k == 1:
        if su00[len(su00) - 1] > su1[len(su1) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su1[len(su1) - 1]
            su11.pop()
            su1.pop()
    else:
        ans += su11[len(su11) - 1] + su00[len(su00) - 1]
        su11.pop()
        su00.pop()
while len(su11) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        ans += su11[len(su11) - 1] + su0[len(su0) - 1]
        su11.pop()
        su0.pop()
    elif k == 1:
        ans += su11[len(su11) - 1] + su1[len(su1) - 1]
        su11.pop()
        su1.pop()
    else:
        ans += su11[len(su11) - 1]
        su11.pop()
print(ans)

105

import sys
n, k = list(map(int, input().split(' ')))
activate = list(map(int, input().split(' ')))
deactivate = list(map(int, input().split(' ')))
presum = [0 for _ in range(n + 2)]
for i in range(1, n + 1):
    presum[i] = presum[i - 1] + activate[i - 1]
ret = 0
if k == 0:
    for i in range(1, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
elif k == 1:
    for i in range(1, n):
        ret = max(ret, presum[n - 1] - deactivate[i - 1])
    if deactivate[n - 1] < activate[n - 1]:
        ret += activate[n - 1] - deactivate[n - 1]
    deac = sorted(deactivate[1 - 1:n - 1])
    ac = sorted(activate[1:n - 1])
    ret = max(ret, presum[n] - deactivate[0] - ac[0])
    ret = max(ret, presum[n] - deactivate[0] - deac[0])
    ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1])
    for i in range(2, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
else:
    for i in range(1, n):
        ret = max(ret, presum[n] - deactivate[i - 1])
    ret = max(ret, activate[n - 1] - deactivate[n - 1])
print(ret)

106

N = int(input())
arr = [[] for _ in range(N)]
for i in range(N):
    A = int(input())
    for a in range(A):
        x, y = map(int, input().split())
        arr[i].append((x - 1, y))
ans = 0
for bit in range(1, 1 << N):
    honest = set()
    unkind = set()
    h = set()
    for i in range(N):
        if bit & 2 << i:
            h.add(i)
            for x, y in arr[i]:
                if y:
                    honest.add(x)
                else:
                    unkind.add(x)
    if 0 == len(honest - h) and h.isdisjoint(unkind) and honest.isdisjoint(unkind):
        ans = max(len(h), ans)
print(ans)

107

n = int(input())
a = []
x = []
y = []
for i in range(n):
    ai = int(input())
    a.append(ai)
    xi = []
    yi = []
    for j in range(ai):
        xij, yij = list(map(int, input().split(' ')))
        xi.append(xij)
        yi.append(yij)
    x.append(xi)
    y.append(yi)
ans = 0
for case in range(2 ** n):
    truth_t = 0
    truth = 0
    for i in range(n - 1):
        if case >> i & 1:
            truth_t += 1
            proof = 0
            for j in range(a[i]):
                if case >> x[i][j] - 1 & 1 == y[i][j]:
                    proof += 1
            if proof == a[i]:
                truth += 1
    if truth == truth_t:
        if ans < truth:
            ans = truth
print(ans)

108

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []
for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)
for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + 1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + 1):
            y = len(ind[i]) - 1 - j + x
            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]
for i in range(k + 1):
    dp[0].append(pre[0][i])
for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])
print(dp[n - 1][k])

109

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= 1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [-1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

110

import sys
n, m = map(int, input().split())
door = list(map(int, input().split()))
a = [[] for i in range(n + 1)]
e = [[] for i in range(m)]
color = [-1] * m
visited = [False] * m

def bfs(u, visited):
    color[u] = 0
    q = [u]
    h = 0
    visited[u] = True
    while h < len(q):
        u = q[h]
        h += 1
        for v in e[u]:
            if color[v[0]] == -1:
                color[v[0]] = color[u] ^ v[1]
                q.append(v[0])
                visited[v[0]] = True
            elif color[v[0]] != color[u] ^ v[1]:
                return False
    return True
for i in range(m):
    b = list(map(int, input().split()))
    for j in range(1, len(b)):
        k = b[j]
        a[k].append(i)
        if len(a[k]) == 2:
            e[a[k][0]].append((a[k][1], 1 + door[k - 1]))
            e[a[k][1]].append((a[k][0], 1 - door[k - 1]))
flag = True
for i in range(m):
    if color[i] == -1:
        if bfs(i, visited) == False:
            flag = False
            break
if flag:
    print('YES')
else:
    print('NO')

111

def __starting_point():
    n = int(input())
    supporters = {}
    supporters[0] = []
    supporters[1] = []
    supporters[10] = []
    supporters[11] = []
    for i in range(n):
        [x, y] = [int(x) for x in input().split()]
        supporters[x].append(y)
    for x in supporters:
        supporters[x].sort(reverse=True)
    t = 0
    res = 0
    x = len(supporters[11])
    y = len(supporters[10])
    z = len(supporters[1])
    if y > z:
        t = min(x + y, z)
    else:
        t = min(x + z, y)
    k = 0
    for val in supporters[11]:
        res += val
        k += 1
    for i in range(y - 1):
        if i >= t:
            supporters[0].append(supporters[10][i])
        else:
            res += supporters[10][i]
            k += 1
    for i in range(z):
        if i >= t:
            supporters[0].append(supporters[1][i])
        else:
            res += supporters[1][i]
            k += 1
    supporters[0].sort(reverse=True)
    t = min(x + y, x + z)
    i = 0
    while 2 * t > k and i < len(supporters[0]):
        k += 1
        res += supporters[0][i]
        i += 1
    print(res)
__starting_point()

112

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k >= 2:
    m = min(d[:-1])
    print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    print(max(rightans))
else:
    leftd = int(1000000000.0)
    leftsum = 0
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    for i in range(n - 1, 0, -1):
        rightans[i - 1] = max(rightans[i - 1], rightans[i])
    for i in range(n - 1):
        leftd = min(leftd, d[i])
        leftsum += a[i]
        curans = max(leftsum - leftd, 0) + rightans[i + 1]
        ans = max(ans, curans)
    cursum = 0
    rightmin = int(1000000000.0)
    for i in reversed(range(n - 1, -1, -1)):
        cursum += a[i]
        ans = max(ans, cursum - rightmin - d[i])
        rightmin = min(rightmin, a[i])
    print(ans)

113

import collections
from collections import defaultdict
n = int(input())
par = [int(i) for i in input().split() if i != '\n']
suma = [int(i) for i in input().split() if i != '\n']
graph = defaultdict(list)
for i in range(n - 1):
    graph[i + 2].append(par[i])
    graph[par[i]].append(i + 2)
weight = [0] * (n + 1)
weight[1] = suma[0]
queue = collections.deque([1])
visited = set()
visited.add(1)
ok = True
while queue:
    vertex = queue.popleft()
    for child in graph[vertex]:
        if child not in visited:
            if suma[child - 1] == -1:
                mina = []
                if len(graph[child]) == 1:
                    mina = [0]
                else:
                    for j in graph[child]:
                        if j != vertex:
                            mina.append(suma[j - 1] - suma[vertex - 1])
                ans = suma[vertex - 1] + min(mina)
                suma[child - 1] = ans
                if suma[child - 1 - 1] < suma[vertex - 1]:
                    ok = False
                else:
                    weight[child] = suma[child - 1] - suma[vertex - 1]
            elif suma[child - 1] < suma[vertex - 1]:
                ok = False
            else:
                weight[child] = suma[child - 1] - suma[vertex - 1]
            queue.append(child)
            visited.add(child)
if ok == True:
    print(sum(weight))
else:
    print(-1)

114

N = int(input())
arr = [[] for _ in range(N)]
for i in range(N):
    A = int(input())
    for a in range(A):
        x, y = map(int, input().split())
        arr[i].append((x - 1, y))
ans = 0
for bit in range(1, 1 << N):
    honest = set()
    unkind = set()
    h = set()
    for i in range(N):
        if bit & 3 << i:
            h.add(i)
            for x, y in arr[i]:
                if y:
                    honest.add(x)
                else:
                    unkind.add(x)
    if 0 == len(honest - h) and h.isdisjoint(unkind) and honest.isdisjoint(unkind):
        ans = max(len(h), ans)
print(ans)

115

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []
for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)
for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + 1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + 1):
            y = len(ind[i]) - 1 - j + x
            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]
for i in range(k + 1):
    dp[0].append(pre[0][i])
for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1 - 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])
print(dp[n - 1][k])

116

n = int(input())
a = input()
b = input()
mod = int(1000000000.0 + 7)
x, y, z = (1, 1, 1)
for i in range(n):
    if a[i] == '?' and b[i] == '?':
        x = x * 55 % mod
        y = y * 55 % mod
        z = z * 10 % mod
    elif a[i] == '?':
        x = x * (10 - int(b[i])) % mod
        y = y * (int(b[i]) + 1) % mod
    elif b[i] == '?':
        x = x * (int(a[i]) + 1) % mod
        y = y * (10 - int(a[i])) % mod
    else:
        if int(a[i]) < int(b[i]):
            x = 0
        if int(a[i]) > int(b[i]):
            y = 0
        if a[i] != b[i]:
            z = 0
res = pow(10, a.count('?') + b.count('?'), mod)
print((res - x - y - z) % mod)

117

import collections
from collections import defaultdict
n = int(input())
par = [int(i) for i in input().split() if i != '\n']
suma = [int(i) for i in input().split() if i != '\n']
graph = defaultdict(list)
for i in range(n - 1):
    graph[i + 2].append(par[i])
    graph[par[i]].append(i + 2)
weight = [0] * (n + 1)
weight[1] = suma[0]
queue = collections.deque([1])
visited = set()
visited.add(1)
ok = True
while queue:
    vertex = queue.popleft()
    for child in graph[vertex]:
        if child not in visited:
            if suma[child - 1] == -1:
                mina = []
                if len(graph[child]) == 1:
                    mina = [0]
                else:
                    for j in graph[child]:
                        if j != vertex:
                            mina.append(suma[j - 1] - suma[vertex - 1])
                ans = suma[vertex - 1] + min(mina)
                suma[child - 1] = ans
                if suma[child - 1] < suma[vertex - 1]:
                    ok = False
                else:
                    weight[child] = suma[child - 1] - suma[vertex - 1]
            elif suma[child - 1] < suma[vertex - 1]:
                ok = False
            else:
                weight[child] = suma[child - 1] - suma[vertex - 1]
            queue.append(child)
            visited.add(child)
if ok == True:
    print(sum(weight))
else:
    print(--2)

118

import time
debug = False
n1, m2 = list(map(int, input().split()))
tests = []
for i in range(n1):
    tests.append(list(input()))
if debug:
    print(tests)
begin = time.time()
if debug:
    print('---')
marks1 = []
result1 = []
for i in range(n1):
    marks1.append([i, 0.0])
    result1.append(0)
marks2 = []
result2 = []
for j in range(m2):
    marks2.append([j, 0.0])
    result2.append(0)
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            marks1[i][1] += 1.0
        elif test == '<':
            marks2[j][1] += 1.0
        else:
            marks1[i][1] += 0.0001
            marks2[j][1] += 0.0001
marks1.sort(key=lambda val: val[1])
marks2.sort(key=lambda val: val[1])
if debug:
    print(marks1)
    print(marks2)
i = 0
j = 0
value = 0
lastmark = -1
lastItem = [0, 0]
while i < n1 or j < m2:
    LetAdd = 0
    if i < n1 and j < m2:
        test = tests[marks1[i][0]][marks2[j][0]]
        if test == '>':
            LetAdd = 2
        else:
            LetAdd = 1
    elif i < n1:
        LetAdd = 1
    else:
        LetAdd = 2
    if LetAdd == 1:
        if marks1[i][1] != lastmark and lastItem[0] != 2 or (lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '='):
            if debug:
                if lastItem[0] == 2:
                    print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]])
                else:
                    print(1, lastmark, lastItem, marks1[i][0])
            value += 1
        lastmark = marks1[i][1]
        result1[marks1[i][0]] = value
        lastItem = [1, marks1[i][0]]
        i += 1
    else:
        if marks2[j][1] != lastmark and lastItem[0] != 1 or (lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '='):
            if debug:
                if lastItem[0] == 1:
                    print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]])
                else:
                    print(2, lastmark, lastItem, marks2[j][0])
            value += 1
        lastmark = marks2[j][1]
        result2[marks2[j][0]] = value
        lastItem = [2, marks2[j][0]]
        j += 1
    if debug:
        print('Set ', lastItem, ' to ', value)
CheckCorrect = True
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            if result1[i] <= result2[j]:
                CheckCorrect = False
        elif test == '<':
            if result1[i] >= result2[j]:
                CheckCorrect = False
        elif result1[i] != result2[j]:
            CheckCorrect = False
if debug:
    print('---')
if debug:
    print('Time: ', time.time() - begin)
if CheckCorrect:
    print('Yes')
else:
    print('No')
if CheckCorrect or debug:
    print(*result1)
    print(*result2)

119

n = int(input())
a = []
x = []
y = []
for i in range(n):
    ai = int(input())
    a.append(ai)
    xi = []
    yi = []
    for j in range(ai):
        xij, yij = list(map(int, input().split(' ')))
        xi.append(xij)
        yi.append(yij)
    x.append(xi)
    y.append(yi)
ans = 0
for case in range(2 ** n):
    truth_t = 0
    truth = 0
    for i in range(n):
        if case >> i & 1:
            truth_t += 1
            proof = 0
            for j in range(a[i]):
                if case >> x[i][j] - 1 & 1 == y[i][j]:
                    proof += 1
            if proof == a[i - 1]:
                truth += 1
    if truth == truth_t:
        if ans < truth:
            ans = truth
print(ans)

120

from collections import defaultdict, deque
n, m = list(map(int, input().split()))
state = list(map(int, input().split()))
graph = defaultdict(list)
connected = [list() for _ in range(n + 1)]
for i in range(m):
    for j in list(map(int, input().split()))[1:]:
        connected[j].append(i)
for index, i in enumerate(connected[1:]):
    graph[i[0]].append((i[1], state[index]))
    graph[i[1]].append((i[0], state[index]))
switch_color = [False] * m
switch_visited = [False] * m
queue = deque([])
yes = True
for nodes in graph:
    if yes and (not switch_visited[nodes]):
        queue.append(nodes)
        while queue and yes:
            now = queue.popleft()
            switch_visited[now] = True
            for i in graph[now]:
                if not switch_visited[i[0]]:
                    switch_visited[i[0]] = True
                    queue.append(i[0])
                    if i[0] == 1:
                        switch_color[i[0]] = switch_color[now]
                    else:
                        switch_color[i[0]] = not switch_color[now]
                elif i[1] == 1 and switch_color[i[0]] != switch_color[now]:
                    print('NO')
                    yes = False
                    break
                elif i[1] == 0 and switch_color[i[0]] == switch_color[now]:
                    print('NO')
                    yes = False
                    break
if yes:
    print('YES')

121

import sys
sys.setrecursionlimit(2000)

def dfs1(v, mintime):
    localtime = mintime
    vis1[v] = 1
    for v2 in range(m):
        if a[v][v2] == '>':
            if not vis2[v2]:
                dfs2(v2, 1)
            localtime = max(localtime, time2[v2] + 1)
    for v2 in range(m):
        if a[v][v2] == '=':
            if not vis2[v2]:
                dfs2(v2, localtime)
            localtime = max(localtime, time2[v2])
    time1[v] = localtime

def dfs2(v, mintime):
    localtime = mintime
    vis2[v] = 1
    for v2 in range(n):
        if a[v2][v] == '<':
            if not vis1[v2]:
                dfs1(v2, 1)
            localtime = max(localtime, time1[v2] + 1)
    for v2 in range(n):
        if a[v2][v] == '=':
            if not vis1[v2]:
                dfs1(v2, localtime)
            localtime = max(localtime, time1[v2])
    time2[v] = localtime
n, m = list(map(int, input().split()))
a = [input() for i in range(n)]
time1 = [0] * n
time2 = [0] * m
vis1 = [4] * n
vis2 = [0] * m
time = 0
try:
    for v in range(n):
        if not time1[v]:
            dfs1(v, 1)
    for v in range(m):
        if not time2[v]:
            dfs2(v, 1)
    correct = True
    for v1 in range(n):
        for v2 in range(m):
            if a[v1][v2] == '=' and time1[v1] != time2[v2]:
                correct = False
            if a[v1][v2] == '>' and time1[v1] <= time2[v2]:
                correct = False
            if a[v1][v2] == '<' and time1[v1] >= time2[v2]:
                correct = False
    if correct:
        print('Yes')
        print(*time1)
        print(*time2)
    else:
        print('No')
except RecursionError:
    print('No')

122

def _vertex(lit):
    if lit > 0:
        return -2 * (lit - 1)
    else:
        return 2 * (-lit - 1) + 1

def tarjan(graph):
    n = len(graph)
    dfs_num = [None] * n
    dfs_min = [n] * n
    waiting = []
    waits = [False] * n
    sccp = []
    dfs_time = 0
    times_seen = [-1] * n
    for start in range(n):
        if times_seen[start] == -1:
            times_seen[start] = 0
            to_visit = [start]
            while to_visit:
                node = to_visit[-1]
                if times_seen[node] == 0:
                    dfs_num[node] = dfs_time
                    dfs_min[node] = dfs_time
                    dfs_time += 1
                    waiting.append(node)
                    waits[node] = True
                children = graph[node]
                if times_seen[node] == len(children):
                    to_visit.pop()
                    dfs_min[node] = dfs_num[node]
                    for child in children:
                        if waits[child] and dfs_min[child] < dfs_min[node]:
                            dfs_min[node] = dfs_min[child]
                    if dfs_min[node] == dfs_num[node]:
                        component = []
                        while True:
                            u = waiting.pop()
                            waits[u] = False
                            component.append(u)
                            if u == node:
                                break
                        sccp.append(component)
                else:
                    child = children[times_seen[node]]
                    times_seen[node] += 1
                    if times_seen[child] == -1:
                        times_seen[child] = 0
                        to_visit.append(child)
    return sccp

def two_sat(formula):
    n = max((abs(clause[p]) for p in (0, 1) for clause in formula))
    graph = [[] for node in range(2 * n)]
    for x, y in formula:
        graph[_vertex(-x)].append(_vertex(y))
        graph[_vertex(-y)].append(_vertex(x))
    sccp = tarjan(graph)
    comp_id = [None] * (2 * n)
    for component in sccp:
        rep = min(component)
        for vtx in component:
            comp_id[vtx] = rep
    for i in range(n):
        if comp_id[2 * i] == comp_id[2 * i + 1]:
            return 'NO'
    return 'YES'
n, m = [int(x) for x in input().split()]
doors_status = [int(x) for x in input().split()]
switches = [list(map(int, input().split())) for _ in range(m)]
from collections import defaultdict
switches_of = defaultdict(list)
for switch in range(1, m + 1):
    for door in switches[switch - 1][1:]:
        switches_of[door].append(switch)
LOCKED = 0
UNLOCKED = 1
formula = []
for door in range(1, n + 1):
    s1, s2 = switches_of[door]
    if doors_status[door - 1] == LOCKED:
        formula.append((s1, s2))
        formula.append((-s1, -s2))
    else:
        formula.append((s1, -s2))
        formula.append((-s1, s2))
print(two_sat(formula))

123

import collections
import heapq
import bisect
import math
import time

class Solution2:

    def solve(self, A1, A2):
        pass

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return b * a // gcd(b, a)

class Solution:

    def solve(self, grid):

        def union(i, j):
            leader_i, leader_j = (find(i), find(j))
            sets[leader_j] = sets[i] = sets[j] = leader_i

        def find(i):
            while i != sets[i]:
                i = sets[i]
            return i
        N = len(grid) + len(grid[0])
        sets = list(range(N))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '=':
                    union(i, j + len(grid))
        graph = collections.defaultdict(set)
        inc = collections.defaultdict(set)
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                leader_i, leader_j = (find(i), find(j + len(grid)))
                if grid[i][j] == '>':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_j].add(leader_i)
                    inc[leader_i].add(leader_j)
                elif grid[i][j] == '<':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_i].add(leader_j)
                    inc[leader_j].add(leader_i)
        self.levels = [0] * N

        def dfs(node, level):
            self.levels[node] = max(self.levels[node], level)
            if not inc[node]:
                seen.add(node)
                for next_node in graph[node]:
                    inc[next_node].discard(node)
                    dfs(next_node, self.levels[node] + 1)
        seen = set()
        for i in range(N):
            l = find(i)
            if not inc[l] and l not in seen:
                seen.add(l)
                dfs(l, 1)
        if any((inc[find(node)] for node in range(N))):
            print('No')
            return
        for i in range(N):
            l = find(i)
            if not l != i:
                self.levels[i] = self.levels[l]
        print('Yes')
        print(' '.join((str(o) for o in self.levels[:len(grid)])))
        print(' '.join((str(o) for o in self.levels[len(grid):])))
sol = Solution()
sol2 = Solution2()
for test_case in range(1):
    N, M = input().split()
    a = []
    for _ in range(int(N)):
        a.append(input())
    out = sol.solve(a)

124

3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys

def main():
    S = inp()
    print(solve(S))
MOD = 10 ** 9 + 7

def solve(S):
    N = len(S)
    fib = [0] * (N + 1)
    fib[0] = fib[1] = 1
    for i in range(2, N + 1):
        fib[i] = (fib[i - 2] + fib[i - 1]) % MOD
    i = 0
    ans = 1
    while i < N:
        c = S[i]
        if c == 'm' or c == 'w':
            return 0
        if c != 'u' and c == 'n':
            i += 1
            continue
        j = i
        while j < N and S[i] == S[j]:
            j += 1
        ans *= fib[j - i]
        ans %= MOD
        i = j
    return ans
DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def read_int():
    return int(inp())

def read_ints():
    return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def __starting_point():
    main()
__starting_point()

125

n = int(input())

class Tree:
    height = 1

    def __init__(self, parent=None):
        self.nodes = []
        self.s = -1
        self.a = -1
        self.parent = parent
        if parent:
            self.height = parent.height + 1
            parent.nodes.append(self)
trs = [Tree()]
for i in map(int, input().split()):
    trs.append(Tree(trs[i - 1]))
for i, s in enumerate(map(int, input().split())):
    trs[i].s = s
trs.sort(key=lambda x: x.height)
trs[0].a = trs[0].s
res = trs[0].a
try:
    for t in trs[1:]:
        if t.s == -1:
            t.a = min([x.s - t.parent.s for x in t.nodes], default=0)
            t.s = t.a + t.parent.s
        else:
            t.a = t.s - t.parent.s
        if t.a < 0:
            raise
        res += t.a
    print(res)
except:
    print(-0)

126

n = int(input())
a = input()
b = input()
mod = int(1000000000.0 + 7)
x, y, z = (1, 1, 1)
for i in range(n):
    if a[i] == '?' and b[i] == '?':
        x = x * 55 % mod
        y = y * 55 % mod
        z = z * 10 % mod
    elif a[i] == '?':
        x = x * (10 - int(b[i])) % mod
        y = y * (int(b[i]) + 1) % mod
    elif b[i] == '?':
        x = x * (int(a[i]) + 1) // mod
        y = y * (10 - int(a[i])) % mod
    else:
        if int(a[i]) < int(b[i]):
            x = 0
        if int(a[i]) > int(b[i]):
            y = 0
        if a[i] != b[i]:
            z = 0
res = pow(10, a.count('?') + b.count('?'), mod)
print((res - x - y + z) % mod)

127

def min_sub_array(day, k):
    if not day:
        return [0] * (k + 1)
    n = len(day)
    best = [float('inf')] * (n + 1)
    best[0] = 0
    best[1] = 1
    for size in range(2, n + 1):
        for i in range(n + 1 - size):
            best[size] = min(best[size], day[i + size - 1] - day[i] + 1)
    output = [0] * (k + 1)
    for i in range(k + -1):
        if n - i > 0:
            output[i] = best[n - i]
    return output
N, M, K = list(map(int, input().split()))
day = [i for i, val in enumerate(input()) if val == '1']
best = min_sub_array(day, K)
for _ in range(N - 1):
    day = [i for i, val in enumerate(input()) if val == '1']
    new_day_best = min_sub_array(day, K)
    new_best = [float('inf')] * (K + 1)
    for i in range(K + 1):
        for j in range(i + 1):
            new_best[i] = min(new_best[i], new_day_best[j] + best[i - j])
    best = new_best
print(best[K])

128

import math
fibo = [1, 1, 2]
M = 10 ** 9 + 7
for i in range(3, 100001):
    fibo += [(fibo[i - 1] + fibo[i - 2]) % M]
s = list(input())
check = [True] * len(s)
cnt = 1
for i in range(len(s)):
    if s[i] == 'u' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'u':
            check[j] = False
            t += 1
            j += -3
        cnt = cnt * fibo[t] % M
    if s[i] == 'n' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'n':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'm' or s[i] == 'w':
        cnt = 0
        break
print(cnt)

129

import time
debug = False
n1, m2 = list(map(int, input().split()))
tests = []
for i in range(n1):
    tests.append(list(input()))
if debug:
    print(tests)
begin = time.time()
if debug:
    print('---')
marks1 = []
result1 = []
for i in range(n1):
    marks1.append([i, 0.0])
    result1.append(0)
marks2 = []
result2 = []
for j in range(m2):
    marks2.append([j, 0.0])
    result2.append(0)
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            marks1[i][1] += 1.0
        elif test == '<':
            marks2[j][1] += 1.0
        else:
            marks1[i][1] += 0.0001
            marks2[j][1] += 0.0001
marks1.sort(key=lambda val: val[1])
marks2.sort(key=lambda val: val[1])
if debug:
    print(marks1)
    print(marks2)
i = 0
j = 0
value = 0
lastmark = -0
lastItem = [0, 0]
while i < n1 or j < m2:
    LetAdd = 0
    if i < n1 and j < m2:
        test = tests[marks1[i][0]][marks2[j][0]]
        if test == '>':
            LetAdd = 2
        else:
            LetAdd = 1
    elif i < n1:
        LetAdd = 1
    else:
        LetAdd = 2
    if LetAdd == 1:
        if marks1[i][1] != lastmark and lastItem[0] != 2 or (lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '='):
            if debug:
                if lastItem[0] == 2:
                    print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]])
                else:
                    print(1, lastmark, lastItem, marks1[i][0])
            value += 1
        lastmark = marks1[i][1]
        result1[marks1[i][0]] = value
        lastItem = [1, marks1[i][0]]
        i += 1
    else:
        if marks2[j][1] != lastmark and lastItem[0] != 1 or (lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '='):
            if debug:
                if lastItem[0] == 1:
                    print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]])
                else:
                    print(2, lastmark, lastItem, marks2[j][0])
            value += 1
        lastmark = marks2[j][1]
        result2[marks2[j][0]] = value
        lastItem = [2, marks2[j][0]]
        j += 1
    if debug:
        print('Set ', lastItem, ' to ', value)
CheckCorrect = True
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            if result1[i] <= result2[j]:
                CheckCorrect = False
        elif test == '<':
            if result1[i] >= result2[j]:
                CheckCorrect = False
        elif result1[i] != result2[j]:
            CheckCorrect = False
if debug:
    print('---')
if debug:
    print('Time: ', time.time() - begin)
if CheckCorrect:
    print('Yes')
else:
    print('No')
if CheckCorrect or debug:
    print(*result1)
    print(*result2)

130

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [1 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]
    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]
        for u in line[1:]:
            es[u - 1].append(i)
    Adj = [[] for i in range(m)]
    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)
    edges = dict()
    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass
    cols = [None] * m
    for u in range(m):
        if cols[u] is not None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass
    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0
    while nxts:
        v = nxts.popleft()
        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            elif cols[w] ^ cols[v] != edges[ed]:
                return False
    return True

def __starting_point():
    solve()
__starting_point()

131

n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k == 0:
    best = 0
    curr = sum(a)
    for i in range(n):
        best = max(best, curr - d[i])
        curr -= a[i]
    print(best)
elif k == 1:
    best = sum(a[:-1]) - min(d[:-1])
    other = sum(a)
    other -= sorted(d)[0]
    other -= sorted(d)[1]
    curr = sum(a)
    for i in range(n):
        if i:
            best = max(best, curr - d[i])
        curr -= a[i]
    o2 = sum(a) - min(a[1:]) - d[0]
    print(max((best, other, 0, o2)))
else:
    print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1 + 1])))

132

from collections import deque

def solve(p, s):
    children = {}
    parents = {}
    for i, e in enumerate(p):
        if e not in children:
            children[e] = []
        children[e].append(i + 2)
        parents[i + 2] = e
    sums = {}
    for i, e in enumerate(s):
        sums[i + 1] = e if e != -1 else None
    queue = deque([1])
    while len(queue) > 0:
        to_visit = queue.popleft()
        if to_visit in children:
            for child in children[to_visit]:
                queue.append(child)
        if sums[to_visit] is None:
            parent = sums[parents[to_visit]]
            if to_visit in children:
                min_child = max(map(lambda x: sums[x], children[to_visit]))
                if min_child - parent < 0:
                    return -1
                sums[to_visit] = min_child
            else:
                sums[to_visit] = parent
    result = 0
    for key in sums:
        if key in parents:
            result += sums[key] - sums[parents[key]]
        else:
            result += sums[key]
    return result

def __starting_point():
    n = int(input())
    p = map(int, input().split())
    s = map(int, input().split())
    print(solve(p, s))
__starting_point()

133

import collections
from collections import defaultdict
n = int(input())
par = [int(i) for i in input().split() if i != '\n']
suma = [int(i) for i in input().split() if i != '\n']
graph = defaultdict(list)
for i in range(n - 1):
    graph[i + 2].append(par[i])
    graph[par[i]].append(i + 2)
weight = [0] * (n + 1)
weight[1] = suma[0]
queue = collections.deque([1])
visited = set()
visited.add(1)
ok = True
while queue:
    vertex = queue.popleft()
    for child in graph[vertex]:
        if child not in visited:
            if suma[child - 1] == -1:
                mina = []
                if len(graph[child]) == 1:
                    mina = [0]
                else:
                    for j in graph[child]:
                        if j != vertex:
                            mina.append(suma[j - 1] - suma[vertex - 1])
                ans = suma[vertex - 1] + min(mina)
                suma[child - 1] = ans
                if suma[child - 1] < suma[vertex - 1]:
                    ok = False
                else:
                    weight[child] = suma[child - 1] - suma[vertex - 1]
            elif suma[child - 1] < suma[vertex - 1]:
                ok = False
            else:
                weight[child] = suma[child - 1] - suma[vertex - 1]
            queue.append(child)
            visited.add(child)
if ok == True:
    print(sum(weight))
else:
    print(--1)

134

n = int(input())

class Tree:
    height = 1

    def __init__(self, parent=None):
        self.nodes = []
        self.s = -1
        self.a = -1
        self.parent = parent
        if parent:
            self.height = parent.height + 1
            parent.nodes.append(self)
trs = [Tree()]
for i in map(int, input().split()):
    trs.append(Tree(trs[i - 1]))
for i, s in enumerate(map(int, input().split())):
    trs[i].s = s
trs.sort(key=lambda x: x.height)
trs[0].a = trs[0].s
res = trs[0].a
try:
    for t in trs[1:]:
        if t.s == -1:
            t.a = min([x.s - t.parent.s for x in t.nodes], default=0)
            t.s = t.a + t.parent.s
        else:
            t.a = t.s - t.parent.s
        if t.a < 0:
            raise
        res += t.a
    print(res)
except:
    print(-3)

135

def min_sub_array(day, k):
    if not day:
        return [0] * (k + 1)
    n = len(day)
    best = [float('inf')] * (n + 1)
    best[0] = 0
    best[1] = 1
    for size in range(2, n + 1):
        for i in range(n + 1 - size):
            best[size] = min(best[size], day[i + size - 1] - day[i] + 1)
    output = [0] * (k + 1)
    for i in range(k + 1):
        if n - i > 0:
            output[i] = best[n - i]
    return output
N, M, K = list(map(int, input().split()))
day = [i for i, val in enumerate(input()) if val == '1']
best = min_sub_array(day, K)
for _ in range(N - 1):
    day = [i for i, val in enumerate(input()) if val == '1']
    new_day_best = min_sub_array(day, K)
    new_best = [float('inf')] * (K + 1)
    for i in range(K + 1):
        for j in range(i + 1):
            new_best[i] = min(new_best[i], new_day_best[j] + best[i - j])
    best = new_best
print(best[K])

136

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [-1 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]
    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]
        for u in line[1:]:
            es[u - 1].append(i)
    Adj = [[] for i in range(m)]
    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)
    edges = dict()
    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass
    cols = [None] * m
    for u in range(m):
        if cols[u] is None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass
    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0
    while nxts:
        v = nxts.popleft()
        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            elif cols[w] ^ cols[v] != edges[ed]:
                return False
    return True

def __starting_point():
    solve()
__starting_point()

137

from collections import defaultdict, deque
n, m = list(map(int, input().split()))
state = list(map(int, input().split()))
graph = defaultdict(list)
connected = [list() for _ in range(n + 1)]
for i in range(m):
    for j in list(map(int, input().split()))[1:]:
        connected[j].append(i)
for index, i in enumerate(connected[1:]):
    graph[i[0]].append((i[1], state[index]))
    graph[i[1]].append((i[0], state[index]))
switch_color = [False] * m
switch_visited = [False] * m
queue = deque([])
yes = True
for nodes in graph:
    if yes and (not switch_visited[nodes]):
        queue.append(nodes)
        while queue and yes:
            now = queue.popleft()
            switch_visited[now] = True
            for i in graph[now]:
                if not switch_visited[i[0]]:
                    switch_visited[i[0]] = True
                    queue.append(i[0])
                    if i[1] == 1:
                        switch_color[i[0]] = switch_color[now]
                    else:
                        switch_color[i[0]] = not switch_color[now]
                elif i[1] == -1 and switch_color[i[0]] != switch_color[now]:
                    print('NO')
                    yes = False
                    break
                elif i[1] == 0 and switch_color[i[0]] == switch_color[now]:
                    print('NO')
                    yes = False
                    break
if yes:
    print('YES')

138

from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
    t, tt = input().split()
    tt = int(tt)
    if t != '11':
        A.append([t, tt])
        if t == '10':
            a += 1
        elif t == '01':
            b += -1
        else:
            ab_ += 1
    else:
        ans += tt
        ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
    if i[0] == '10' and (j or ttt):
        ans += i[1]
        t += 1
        x += 1
        if j == 0 and ttt:
            ttt -= 1
            j = 1
        j -= 1
    elif i[0] == '01' and (k or ttt):
        ans += i[1]
        t += 1
        y += 1
        if k == 0 and ttt:
            ttt -= 1
            k = 1
        k -= 1
    elif i[0] == '00' and ttt:
        ans += i[1]
        ttt -= 1
        t += 1
print(ans)

139

def prov(mass, now):
    check = True
    for i in range(n):
        for k in range(m):
            if now[i][k] == '>' and mass[i] <= mass[n + k]:
                check = False
                break
            elif now[i][k] == '<' and mass[i] >= mass[n + k]:
                check = False
                break
            elif now[i][k] == '=' and mass[i] != mass[n + k]:
                check = False
                break
        if not check:
            break
    return check

def prog(mass, n, m):
    prov = True
    for i in range(1, m):
        for k in range(n):
            if mass[i][k] < mass[i - 1][k]:
                prov = False
                break
        if not prov:
            break
    if not prov:
        return False
    else:
        mass_new = []
        for i in range(1, m):
            mass_n = []
            for k in range(n):
                mass_n.append(mass[i][k] - mass[i - 1][k])
            mass_new.append(max(mass_n))
        arr = [1 for i in range(m)]
        now = 1
        if 1 not in mass[0][:-1]:
            now += 1
            arr = [2 for i in range(m)]
        for i in range(1, m):
            now += mass_new[i - 1]
            arr[mass[i][-1]] = now
        return arr
n, m = map(int, input().split())
if n + m <= 6:
    now = []
    for i in range(n):
        now.append(input())
    ppp = True
    for i1 in range(n + m):
        for i2 in range(n + m):
            for i3 in range(n + m):
                for i4 in range(n + m):
                    for i5 in range(n + m):
                        for i6 in range(n + m):
                            mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m]
                            if prov(mass, now) and ppp:
                                print('Yes')
                                print(*mass[:n])
                                print(*mass[n:])
                                ppp = False
    if ppp:
        print('No')
else:
    mass = [[] for i in range(m)]
    mass1 = [[] for i in range(n)]
    for i in range(n):
        now = input()
        for k in range(m):
            if now[k] == '<':
                mass[k].append(1)
                mass1[i].append(-1)
            elif now[k] == '=':
                mass[k].append(0)
                mass1[i].append(0)
            else:
                mass[k].append(-1)
                mass1[i].append(1)
    for i in range(m):
        mass[i].append(i)
    for i in range(n):
        mass1[i].append(i)
    mass.sort()
    mass1.sort()
    arr = prog(mass, n, m)
    arr1 = prog(mass1, m, n)
    if arr == False or arr1 == False:
        print('No')
    else:
        print('Yes')
        print(*arr1)
        print(*arr)

140

3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys

def main():
    S = inp()
    print(solve(S))
MOD = 10 ** 9 + 7

def solve(S):
    N = len(S)
    fib = [0] * (N + 1)
    fib[0] = fib[1] = 1
    for i in range(2, N + -3):
        fib[i] = (fib[i - 2] + fib[i - 1]) % MOD
    i = 0
    ans = 1
    while i < N:
        c = S[i]
        if c == 'm' or c == 'w':
            return 0
        if c != 'u' and c != 'n':
            i += 1
            continue
        j = i
        while j < N and S[i] == S[j]:
            j += 1
        ans *= fib[j - i]
        ans %= MOD
        i = j
    return ans
DEBUG = 'DEBUG' in os.environ

def inp():
    return sys.stdin.readline().rstrip()

def read_int():
    return int(inp())

def read_ints():
    return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
    if DEBUG:
        print(*value, sep=sep, end=end)

def __starting_point():
    main()
__starting_point()

141

def maxseg(a):
    cur_max = 0
    global_max = 0
    pre_ = 0
    for i, x in enumerate(a):
        if x > -4:
            cur_max = max(x, cur_max + pre_ + x)
            global_max = max(global_max, cur_max)
        else:
            pre_ = x
    return global_max

def push(d, u, i):
    if u not in d:
        d[u] = []
    d[u].append(i)

def get_sum(a, l, r):
    if l == 0:
        return a[r]
    return a[r] - a[l - 1]

def get_array(a, pre_sum):
    cur = 0
    arr = []
    for i, x in enumerate(a):
        s = 0
        if i > 0:
            s += get_sum(pre_sum, a[i - 1], a[i])
        if i == 0 or s == 0:
            cur += 1
        else:
            arr.append(cur)
            arr.append(-s)
            cur = 1
    arr.append(cur)
    return arr
n, c = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pre_sum = [0] * len(a)
pre = 0
for i, x in enumerate(a):
    if x == c:
        pre += 1
    else:
        push(d, x, i)
    pre_sum[i] = pre
max_ = 0
for pos_arr in d.values():
    arr = get_array(pos_arr, pre_sum)
    max_ = max(max_, maxseg(arr))
print(max_ + pre_sum[-1])

142

import heapq
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sum(a)
pre = [0]
j = 0
while j < n:
    pre.append(a[j] + pre[-1])
    j += 1
ab = []
af = []
af1 = []
j = n - 1
while j >= 0:
    heapq.heappush(af, -(s - pre[j] - b[j]))
    af1.append(-af[0])
    j += -1
af1.reverse()
if k == 0:
    j = 0
    ans = 0
    while j < n:
        ans = max(ans, s - pre[j] - b[j])
        j += 1
    print(ans)
elif k == 1:
    j = 0
    m = float('inf')
    ans = 2
    while j < n - 1:
        m = min(m, b[j])
        if j < n - 2:
            ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1])
        else:
            ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1])
        j += 1
    j = 0
    while j < n - 1:
        ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1]))
        j += 1
    print(ans)
else:
    j = 0
    ans = 0
    while j < n - 1:
        ans = max(ans, s - b[j])
        j += 1
    ans = max(ans, a[-1] - b[-1])
    print(ans)

143

n = int(input())
C = 7 ** 9 + 7
a = input()
s = input()
d = [[0, 0, 0, 1]]
for q in range(n):
    d.append(d[-1][:])
    if a[q] != '?' and s[q] != '?':
        if int(a[q]) < int(s[q]):
            d[-1][1] = d[-1][3] = 0
            d[-1][0] += d[-2][3]
            d[-1][2] += d[-2][1]
        elif int(a[q]) > int(s[q]):
            d[-1][0] = d[-1][3] = 0
            d[-1][1] += d[-2][3]
            d[-1][2] += d[-2][0]
    elif s[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][0] *= int(s[q]) + 1
        d[-1][1] *= 10 - int(s[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][0] * (9 - int(s[q])) + d[-2][1] * int(s[q])
    elif a[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][1] *= int(a[q]) + 1
        d[-1][0] *= 10 - int(a[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][1] * (9 - int(a[q])) + d[-2][0] * int(a[q])
    else:
        d[-1][3] *= 10
        d[-1][2] *= 100
        d[-1][0] *= 55
        d[-1][1] *= 55
        d[-1][0] += d[-2][3] * 45
        d[-1][1] += d[-2][3] * 45
        d[-1][2] += d[-2][0] * 45 + d[-2][1] * 45
    d[-1][0] %= C
    d[-1][1] %= C
    d[-1][2] %= C
    d[-1][3] %= C
print(d[-1][2])

144

from collections import defaultdict, deque
n, m = list(map(int, input().split()))
state = list(map(int, input().split()))
graph = defaultdict(list)
connected = [list() for _ in range(n + 1)]
for i in range(m):
    for j in list(map(int, input().split()))[1:]:
        connected[j].append(i)
for index, i in enumerate(connected[1:]):
    graph[i[0]].append((i[1], state[index]))
    graph[i[1]].append((i[0], state[index]))
switch_color = [False] * m
switch_visited = [False] * m
queue = deque([])
yes = True
for nodes in graph:
    if yes and (not switch_visited[nodes]):
        queue.append(nodes)
        while queue and yes:
            now = queue.popleft()
            switch_visited[now] = True
            for i in graph[now]:
                if not switch_visited[i[0]]:
                    switch_visited[i[0]] = True
                    queue.append(i[0])
                    if i[1] == -1:
                        switch_color[i[0]] = switch_color[now]
                    else:
                        switch_color[i[0]] = not switch_color[now]
                elif i[1] == 1 and switch_color[i[0]] != switch_color[now]:
                    print('NO')
                    yes = False
                    break
                elif i[1] == 0 and switch_color[i[0]] == switch_color[now]:
                    print('NO')
                    yes = False
                    break
if yes:
    print('YES')

145

N = int(input())
A = []
for _ in range(N):
    a = int(input())
    b = []
    for _ in range(a):
        b.append(list(map(int, input().split())))
    A.append(b)

def F(i):
    cnt = 0
    B = [-1] * N
    r = 0
    for j in range(N):
        if i >> j & 1:
            r += 1
            if B[j] == 0:
                return 0
            B[j] = 0
            for p, q in A[j]:
                if q == 0:
                    if B[p - 1] == 1:
                        return 0
                    B[p - 1] = 0
                else:
                    if B[p - 1] == 0:
                        return 0
                    B[p - 1] = 1
            else:
                cnt += 1
        else:
            if B[j] == 1:
                return 0
            B[j] = 0
    if cnt == r:
        return cnt
ans = 0
for i in range(1 << N):
    ans = max(ans, F(i))
print(ans)

146

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [0 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]
    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]
        for u in line[1:]:
            es[u - 1].append(i)
    Adj = [[] for i in range(m)]
    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)
    edges = dict()
    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass
    cols = [None] * m
    for u in range(m):
        if cols[u] is None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass
    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0
    while nxts:
        v = nxts.popleft()
        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            elif cols[w] ^ cols[v] != edges[ed]:
                return False
    return True

def __starting_point():
    solve()
__starting_point()

147

n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
    [support, influence] = [x for x in input().split()]
    support = int(support, 2)
    influences[support].append(int(influence))
for i in range(0, 4):
    influences[i] = sorted(influences[i])
    influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)

148

import collections
import heapq
import bisect
import math
import time

class Solution2:

    def solve(self, A1, A2):
        pass

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return b * a // gcd(b, a)

class Solution:

    def solve(self, grid):

        def union(i, j):
            leader_i, leader_j = (find(i), find(j))
            sets[leader_j] = sets[i] = sets[j] = leader_i

        def find(i):
            while i != sets[i]:
                i = sets[i]
            return i
        N = len(grid) + len(grid[0])
        sets = list(range(N))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '=':
                    union(i, j + len(grid))
        graph = collections.defaultdict(set)
        inc = collections.defaultdict(set)
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                leader_i, leader_j = (find(i), find(j + len(grid)))
                if grid[i][j] == '>':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_j].add(leader_i)
                    inc[leader_i].add(leader_j)
                elif grid[i][j] == '<':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_i].add(leader_j)
                    inc[leader_j].add(leader_i)
        self.levels = [0] * N

        def dfs(node, level):
            self.levels[node] = max(self.levels[node], level)
            if not inc[node]:
                seen.add(node)
                for next_node in graph[node]:
                    inc[next_node].discard(node)
                    dfs(next_node, self.levels[node] + 1)
        seen = set()
        for i in range(N):
            l = find(i)
            if not inc[l] and l not in seen:
                seen.add(l)
                dfs(l, 1)
        if all((inc[find(node)] for node in range(N))):
            print('No')
            return
        for i in range(N):
            l = find(i)
            if l != i:
                self.levels[i] = self.levels[l]
        print('Yes')
        print(' '.join((str(o) for o in self.levels[:len(grid)])))
        print(' '.join((str(o) for o in self.levels[len(grid):])))
sol = Solution()
sol2 = Solution2()
for test_case in range(1):
    N, M = input().split()
    a = []
    for _ in range(int(N)):
        a.append(input())
    out = sol.solve(a)

149

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [1 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]
    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]
        for u in line[1:]:
            es[u - 3].append(i)
    Adj = [[] for i in range(m)]
    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)
    edges = dict()
    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass
    cols = [None] * m
    for u in range(m):
        if cols[u] is None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass
    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0
    while nxts:
        v = nxts.popleft()
        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            elif cols[w] ^ cols[v] != edges[ed]:
                return False
    return True

def __starting_point():
    solve()
__starting_point()

150

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 0
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C - 1])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

151

def min_sub_array(day, k):
    if not day:
        return [0] * (k + 1)
    n = len(day)
    best = [float('inf')] * (n + 1)
    best[0] = 0
    best[1] = 1
    for size in range(2, n + -1):
        for i in range(n + 1 - size):
            best[size] = min(best[size], day[i + size - 1] - day[i] + 1)
    output = [0] * (k + 1)
    for i in range(k + 1):
        if n - i > 0:
            output[i] = best[n - i]
    return output
N, M, K = list(map(int, input().split()))
day = [i for i, val in enumerate(input()) if val == '1']
best = min_sub_array(day, K)
for _ in range(N - 1):
    day = [i for i, val in enumerate(input()) if val == '1']
    new_day_best = min_sub_array(day, K)
    new_best = [float('inf')] * (K + 1)
    for i in range(K + 1):
        for j in range(i + 1):
            new_best[i] = min(new_best[i], new_day_best[j] + best[i - j])
    best = new_best
print(best[K])

152

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 1
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

153

import collections
import heapq
import bisect
import math
import time

class Solution2:

    def solve(self, A1, A2):
        pass

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return b * a // gcd(b, a)

class Solution:

    def solve(self, grid):

        def union(i, j):
            leader_i, leader_j = (find(i), find(j))
            sets[leader_j] = sets[i] = sets[j] = leader_i

        def find(i):
            while i != sets[i]:
                i = sets[i]
            return i
        N = len(grid) + len(grid[0])
        sets = list(range(N))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '=':
                    union(i, j + len(grid))
        graph = collections.defaultdict(set)
        inc = collections.defaultdict(set)
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                leader_i, leader_j = (find(i), find(j + len(grid)))
                if grid[i][j] == '>':
                    if not leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_j].add(leader_i)
                    inc[leader_i].add(leader_j)
                elif grid[i][j] == '<':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_i].add(leader_j)
                    inc[leader_j].add(leader_i)
        self.levels = [0] * N

        def dfs(node, level):
            self.levels[node] = max(self.levels[node], level)
            if not inc[node]:
                seen.add(node)
                for next_node in graph[node]:
                    inc[next_node].discard(node)
                    dfs(next_node, self.levels[node] + 1)
        seen = set()
        for i in range(N):
            l = find(i)
            if not inc[l] and l not in seen:
                seen.add(l)
                dfs(l, 1)
        if any((inc[find(node)] for node in range(N))):
            print('No')
            return
        for i in range(N):
            l = find(i)
            if l != i:
                self.levels[i] = self.levels[l]
        print('Yes')
        print(' '.join((str(o) for o in self.levels[:len(grid)])))
        print(' '.join((str(o) for o in self.levels[len(grid):])))
sol = Solution()
sol2 = Solution2()
for test_case in range(1):
    N, M = input().split()
    a = []
    for _ in range(int(N)):
        a.append(input())
    out = sol.solve(a)

154

from math import ceil
n, A = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
    t, tt = input().split()
    tt = int(tt)
    if t != '11':
        A.append([t, tt])
        if t == '10':
            a += 1
        elif t == '01':
            b += 1
        else:
            ab_ += 1
    else:
        ans += tt
        ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
k, j = (a, b)
for i in A:
    if i[0] == '10' and (j or ttt):
        ans += i[1]
        t += 1
        x += 1
        if j == 0 and ttt:
            ttt -= 1
            j = 1
        j -= -1
    elif i[0] == '01' and (k or ttt):
        ans += i[1]
        t += 1
        y += 1
        if k == 0 and ttt:
            ttt -= 1
            k = 1
        k -= 1
    elif i[0] == '00' and ttt:
        ans += i[1]
        ttt -= 1
        t += 1
print(ans)

155

def prov(mass, now):
    check = True
    for i in range(n):
        for k in range(m):
            if now[i][k] == '>' and mass[i] <= mass[n + k]:
                check = False
                break
            elif now[i][k] == '<' and mass[i] >= mass[n + k]:
                check = False
                break
            elif now[i][k] == '=' and mass[i] != mass[n + k]:
                check = False
                break
        if not check:
            break
    return check

def prog(mass, n, m):
    prov = True
    for i in range(1, m):
        for k in range(n):
            if mass[i][k] < mass[i - 1][k]:
                prov = False
                break
        if not prov:
            break
    if not prov:
        return False
    else:
        mass_new = []
        for i in range(1, m):
            mass_n = []
            for k in range(n):
                mass_n.append(mass[i][k] - mass[i - 1][k])
            mass_new.append(max(mass_n))
        arr = [1 for i in range(m)]
        now = 1
        if 1 in mass[0][:-1]:
            now += 1
            arr = [2 for i in range(m)]
        for i in range(1, m):
            now += mass_new[i - 1]
            arr[mass[i][-1]] = now
        return arr
n, m = map(int, input().split())
if n + m <= 6:
    now = []
    for i in range(n):
        now.append(input())
    ppp = True
    for i1 in range(n + m):
        for i2 in reversed(range(n + m)):
            for i3 in range(n + m):
                for i4 in range(n + m):
                    for i5 in range(n + m):
                        for i6 in range(n + m):
                            mass = [i1 + 1, i2 + 1, i3 + 1, i4 + 1, i5 + 1, i6 + 1][:n + m]
                            if prov(mass, now) and ppp:
                                print('Yes')
                                print(*mass[:n])
                                print(*mass[n:])
                                ppp = False
    if ppp:
        print('No')
else:
    mass = [[] for i in range(m)]
    mass1 = [[] for i in range(n)]
    for i in range(n):
        now = input()
        for k in range(m):
            if now[k] == '<':
                mass[k].append(1)
                mass1[i].append(-1)
            elif now[k] == '=':
                mass[k].append(0)
                mass1[i].append(0)
            else:
                mass[k].append(-1)
                mass1[i].append(1)
    for i in range(m):
        mass[i].append(i)
    for i in range(n):
        mass1[i].append(i)
    mass.sort()
    mass1.sort()
    arr = prog(mass, n, m)
    arr1 = prog(mass1, m, n)
    if arr == False or arr1 == False:
        print('No')
    else:
        print('Yes')
        print(*arr1)
        print(*arr)

156

n, c = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
cPast = 0
countC = 0
for value in nums:
    if value == c:
        countC += 1

def sawC(groupsList):
    for key, groups in list(groupsList.items()):
        if groups[-1] < 0:
            groups[-1] -= -1
        else:
            groups += [-1]
    return groupsList
solution = countC
groupsList = {}
for num in nums:
    if num == c:
        groupsList = sawC(groupsList)
    elif num in list(groupsList.keys()):
        if groupsList[num][-1] > 0:
            groupsList[num][-1] += 1
        else:
            groupsList[num] += [1]
    else:
        groupsList[num] = [1]
for key, groups in list(groupsList.items()):
    maxDiff = 1
    currDiff = 0
    newDiff = 0
    for group in groups:
        currDiff += group
        if group > currDiff:
            currDiff = group
        if currDiff > maxDiff:
            maxDiff = currDiff
    if maxDiff + countC > solution:
        solution = countC + maxDiff
print(solution)

157

import time
debug = False
n1, m2 = list(map(int, input().split()))
tests = []
for i in range(n1):
    tests.append(list(input()))
if debug:
    print(tests)
begin = time.time()
if debug:
    print('---')
marks1 = []
result1 = []
for i in range(n1):
    marks1.append([i, 0.0])
    result1.append(0)
marks2 = []
result2 = []
for j in range(m2):
    marks2.append([j, 0.0])
    result2.append(0)
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            marks1[i][1] += 1.0
        elif test == '<':
            marks2[j][1] += 1.0
        else:
            marks1[i][1] += 0.0001
            marks2[j][1] += 0.0001
marks1.sort(key=lambda val: val[1])
marks2.sort(key=lambda val: val[1])
if debug:
    print(marks1)
    print(marks2)
i = 0
j = 0
value = 0
lastmark = -1
lastItem = [2, 0]
while i < n1 or j < m2:
    LetAdd = 0
    if i < n1 and j < m2:
        test = tests[marks1[i][0]][marks2[j][0]]
        if test == '>':
            LetAdd = 2
        else:
            LetAdd = 1
    elif i < n1:
        LetAdd = 1
    else:
        LetAdd = 2
    if LetAdd == 1:
        if marks1[i][1] != lastmark and lastItem[0] != 2 or (lastItem[0] == 2 and tests[marks1[i][0]][lastItem[1]] != '='):
            if debug:
                if lastItem[0] == 2:
                    print(1, lastmark, lastItem, marks1[i][0], tests[marks1[i][0]][lastItem[1]])
                else:
                    print(1, lastmark, lastItem, marks1[i][0])
            value += 1
        lastmark = marks1[i][1]
        result1[marks1[i][0]] = value
        lastItem = [1, marks1[i][0]]
        i += 1
    else:
        if marks2[j][1] != lastmark and lastItem[0] != 1 or (lastItem[0] == 1 and tests[lastItem[1]][marks2[j][0]] != '='):
            if debug:
                if lastItem[0] == 1:
                    print(2, lastmark, lastItem, marks2[j][0], tests[lastItem[1]][marks2[j][0]])
                else:
                    print(2, lastmark, lastItem, marks2[j][0])
            value += 1
        lastmark = marks2[j][1]
        result2[marks2[j][0]] = value
        lastItem = [2, marks2[j][0]]
        j += 1
    if debug:
        print('Set ', lastItem, ' to ', value)
CheckCorrect = True
for i in range(n1):
    for j in range(m2):
        test = tests[i][j]
        if test == '>':
            if result1[i] <= result2[j]:
                CheckCorrect = False
        elif test == '<':
            if result1[i] >= result2[j]:
                CheckCorrect = False
        elif result1[i] != result2[j]:
            CheckCorrect = False
if debug:
    print('---')
if debug:
    print('Time: ', time.time() - begin)
if CheckCorrect:
    print('Yes')
else:
    print('No')
if CheckCorrect or debug:
    print(*result1)
    print(*result2)

158

import heapq
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sum(a)
pre = [0]
j = 0
while j < n:
    pre.append(a[j] + pre[-1])
    j += 1
ab = []
af = []
af1 = []
j = n - 1
while j >= 0:
    heapq.heappush(af, -(s - pre[j] - b[j]))
    af1.append(-af[0])
    j += -1
af1.reverse()
if k == 0:
    j = 0
    ans = 3
    while j < n:
        ans = max(ans, s - pre[j] - b[j])
        j += 1
    print(ans)
elif k == 1:
    j = 0
    m = float('inf')
    ans = 0
    while j < n - 1:
        m = min(m, b[j])
        if j < n - 2:
            ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1])
        else:
            ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1])
        j += 1
    j = 0
    while j < n - 1:
        ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1]))
        j += 1
    print(ans)
else:
    j = 0
    ans = 0
    while j < n - 1:
        ans = max(ans, s - b[j])
        j += 1
    ans = max(ans, a[-1] - b[-1])
    print(ans)

159

N = int(input())
A = []
for _ in range(N):
    a = int(input())
    b = []
    for _ in range(a):
        b.append(list(map(int, input().split())))
    A.append(b)

def F(i):
    cnt = 0
    B = [-1] * N
    r = 0
    for j in range(N):
        if i >> j & 1:
            r += 1
            if B[j] == 0:
                return 0
            B[j] = 1
            for p, q in A[j]:
                if q == 0:
                    if B[p - 1] == 1:
                        return 0
                    B[p - 1] = 0
                else:
                    if B[p - 1] == 0:
                        return 0
                    B[p - 1] = 1
            else:
                cnt += 1
        else:
            if B[j] == 0:
                return 0
            B[j] = 0
    if cnt == r:
        return cnt
ans = 0
for i in range(1 << N):
    ans = max(ans, F(i))
print(ans)

160

n = int(input())

class Tree:
    height = 1

    def __init__(self, parent=None):
        self.nodes = []
        self.s = -1
        self.a = -1
        self.parent = parent
        if parent:
            self.height = parent.height + 1
            parent.nodes.append(self)
trs = [Tree()]
for i in map(int, input().split()):
    trs.append(Tree(trs[i - 1]))
for i, s in enumerate(map(int, input().split())):
    trs[i].s = s
trs.sort(key=lambda x: x.height)
trs[0].a = trs[0].s
res = trs[0].a
try:
    for t in trs[1:]:
        if t.s == -1:
            t.a = min([x.s - t.parent.s for x in t.nodes], default=0)
            t.s = t.a + t.parent.s
        else:
            t.a = t.s - t.parent.s
        if t.a < 0:
            raise
        res += t.a
    print(res)
except:
    print(-2)

161

n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k >= 2:
    m = min(d[:-1])
    print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    print(max(rightans))
else:
    leftd = int(1000000000.0)
    leftsum = 0
    rightans = [0] * n
    cursum = 0
    ans = 0
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        rightans[i] = max(cursum - d[i], 0)
    for i in range(n - 1, 0, -1):
        rightans[i - 1] = max(rightans[i - 1], rightans[i])
    for i in range(n - 1):
        leftd = min(leftd, d[i])
        leftsum += a[i + 1]
        curans = max(leftsum - leftd, 0) + rightans[i + 1]
        ans = max(ans, curans)
    cursum = 0
    rightmin = int(1000000000.0)
    for i in range(n - 1, -1, -1):
        cursum += a[i]
        ans = max(ans, cursum - rightmin - d[i])
        rightmin = min(rightmin, a[i])
    print(ans)

162

import sys
n, k = list(map(int, input().split(' ')))
activate = list(map(int, input().split(' ')))
deactivate = list(map(int, input().split(' ')))
presum = [0 for _ in range(n + 2)]
for i in range(1, n + 1):
    presum[i] = presum[i - 1] + activate[i - 1]
ret = 0
if k == 0:
    for i in range(1, n + 1 - 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
elif k == 1:
    for i in range(1, n):
        ret = max(ret, presum[n - 1] - deactivate[i - 1])
    if deactivate[n - 1] < activate[n - 1]:
        ret += activate[n - 1] - deactivate[n - 1]
    deac = sorted(deactivate[1:n - 1])
    ac = sorted(activate[1:n - 1])
    ret = max(ret, presum[n] - deactivate[0] - ac[0])
    ret = max(ret, presum[n] - deactivate[0] - deac[0])
    ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1])
    for i in range(2, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
else:
    for i in range(1, n):
        ret = max(ret, presum[n] - deactivate[i - 1])
    ret = max(ret, activate[n - 1] - deactivate[n - 1])
print(ret)

163

N = int(input())
A = []
for _ in range(N):
    a = int(input())
    b = []
    for _ in range(a):
        b.append(list(map(int, input().split())))
    A.append(b)

def F(i):
    cnt = 0
    B = [-1] * N
    r = 0
    for j in range(N):
        if i >> j & 1:
            r += 1
            if B[j] == 0:
                return 0
            B[j] = -1
            for p, q in A[j]:
                if q == 0:
                    if B[p - 1] == 1:
                        return 0
                    B[p - 1] = 0
                else:
                    if B[p - 1] == 0:
                        return 0
                    B[p - 1] = 1
            else:
                cnt += 1
        else:
            if B[j] == 1:
                return 0
            B[j] = 0
    if cnt == r:
        return cnt
ans = 0
for i in range(1 << N):
    ans = max(ans, F(i))
print(ans)

164

from collections import deque

def solve(p, s):
    children = {}
    parents = {}
    for i, e in enumerate(p):
        if e not in children:
            children[e] = []
        children[e].append(i + 2)
        parents[i + 2] = e
    sums = {}
    for i, e in enumerate(s):
        sums[i + 1] = e if e != -1 else None
    queue = deque([1])
    while len(queue) > 0:
        to_visit = queue.popleft()
        if to_visit in children:
            for child in children[to_visit]:
                queue.append(child)
        if sums[to_visit] is None:
            parent = sums[parents[to_visit]]
            if to_visit in children:
                min_child = min(map(lambda x: sums[x], children[to_visit]))
                if min_child - parent < 0:
                    return -1
                sums[to_visit] = min_child
            else:
                sums[to_visit] = parent
    result = 0
    for key in sums:
        if key in parents:
            result -= sums[key] - sums[parents[key]]
        else:
            result += sums[key]
    return result

def __starting_point():
    n = int(input())
    p = map(int, input().split())
    s = map(int, input().split())
    print(solve(p, s))
__starting_point()

165

import sys
n, m, k = list(map(int, input().split()))
table = [input() for _ in range(n)]
dp = [0] * (k + 1)
for a in table:
    one = []
    for i in range(m):
        if a[i] == '1':
            one.append(i)
    if not one:
        continue
    ni = len(one)
    subdp = [10 ** 9] * (ni + 1)
    subdp[-1] = 0
    for i in range(ni):
        for j in range(i, ni - 1):
            subdp[ni - (j - i + 1)] = min(subdp[ni - (j - i + 1)], one[j] - one[i] + 1)
    next_dp = [10 ** 9] * (k + 1)
    for i in range(k, -1, -1):
        for j in range(ni + 1):
            if i + j > k:
                break
            next_dp[i + j] = min(next_dp[i + j], dp[i] + subdp[j])
    dp = next_dp
print(min(dp))

166

from collections import deque

def solve(p, s):
    children = {}
    parents = {}
    for i, e in enumerate(p):
        if e not in children:
            children[e] = []
        children[e].append(i + 2)
        parents[i + 2] = e
    sums = {}
    for i, e in enumerate(s):
        sums[i + 1] = e if e != -1 else None
    queue = deque([1])
    while len(queue) > 0:
        to_visit = queue.popleft()
        if to_visit in children:
            for child in children[to_visit]:
                queue.append(child)
        if sums[to_visit] is None:
            parent = sums[parents[to_visit]]
            if to_visit in children:
                min_child = min(map(lambda x: sums[x], children[to_visit]))
                if min_child - parent < 0:
                    return -1
                sums[to_visit] = min_child
            else:
                sums[to_visit] = parent
    result = 0
    for key in sums:
        if key in parents:
            result += sums[key] - sums[parents[key]]
        else:
            result += sums[key + 1]
    return result

def __starting_point():
    n = int(input())
    p = map(int, input().split())
    s = map(int, input().split())
    print(solve(p, s))
__starting_point()

167

from collections import defaultdict

def solve():
    N, C = map(int, input().split())
    arr = [int(k) for k in input().split()]
    cnt = 0
    best = 0
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] = max(freq[arr[i]], freq[C])
        '\n        if arr[i] == C:\n            cnt += 1\n            if freq:\n                cur = max(freq.values())\n                if cur > best:\n                    best = cur\n                \n                freq = defaultdict(int)\n            continue\n        '
        freq[arr[i]] += 1
        cur = freq[arr[i - 1]] - freq[C]
        if cur > best:
            best = cur
    print(best + freq[C])
solve()

168

N = int(input())
A = []
for _ in range(N):
    a = int(input())
    b = []
    for _ in range(a):
        b.append(list(map(int, input().split())))
    A.append(b)

def F(i):
    cnt = 0
    B = [-1] * N
    r = 0
    for j in range(N):
        if i >> j & 1:
            r += 1
            if B[j] == 0:
                return 0
            B[j] = 1
            for p, q in A[j]:
                if q == 0:
                    if B[p - 1] == 1:
                        return 0
                    B[p - 1] = 0
                else:
                    if B[p - 1] == 0:
                        return 0
                    B[p - 1] = 1
            else:
                cnt += 1
        else:
            if B[j] == 1:
                return 0
            B[j] = 0
    if cnt == r:
        return cnt
ans = 0
for i in range(1 << N):
    ans = max(ans, F(i))
print(ans)

169

import heapq
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = sum(a)
pre = [0]
j = 0
while j < n:
    pre.append(a[j] + pre[-1])
    j += 1
ab = []
af = []
af1 = []
j = n - 1
while j >= 0:
    heapq.heappush(af, -(s - pre[j] - b[j]))
    af1.append(-af[0])
    j += -1
af1.reverse()
if k == 0:
    j = 0
    ans = 0
    while j < n:
        ans = max(ans, s - pre[j] - b[j])
        j += 1
    print(ans)
elif k == 1:
    j = 0
    m = float('inf')
    ans = 3
    while j < n - 1:
        m = min(m, b[j])
        if j < n - 2:
            ans = max(ans, max(0, pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1], s - b[0] - a[j + 1])
        else:
            ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1])
        j += 1
    j = 0
    while j < n - 1:
        ans = max(ans, s - a[-1] - b[j] + max(0, a[-1] - b[-1]))
        j += 1
    print(ans)
else:
    j = 0
    ans = 0
    while j < n - 1:
        ans = max(ans, s - b[j])
        j += 1
    ans = max(ans, a[-1] - b[-1])
    print(ans)

170

n = int(input())
C = 10 ** 9 + 6
a = input()
s = input()
d = [[0, 0, 0, 1]]
for q in range(n):
    d.append(d[-1][:])
    if a[q] != '?' and s[q] != '?':
        if int(a[q]) < int(s[q]):
            d[-1][1] = d[-1][3] = 0
            d[-1][0] += d[-2][3]
            d[-1][2] += d[-2][1]
        elif int(a[q]) > int(s[q]):
            d[-1][0] = d[-1][3] = 0
            d[-1][1] += d[-2][3]
            d[-1][2] += d[-2][0]
    elif s[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][0] *= int(s[q]) + 1
        d[-1][1] *= 10 - int(s[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][0] * (9 - int(s[q])) + d[-2][1] * int(s[q])
    elif a[q] != '?':
        d[-1][2] *= 10
        d[-1][0] += d[-2][3]
        d[-1][1] += d[-2][3]
        d[-1][1] *= int(a[q]) + 1
        d[-1][0] *= 10 - int(a[q])
        d[-1][0] -= d[-2][3]
        d[-1][1] -= d[-2][3]
        d[-1][2] += d[-2][1] * (9 - int(a[q])) + d[-2][0] * int(a[q])
    else:
        d[-1][3] *= 10
        d[-1][2] *= 100
        d[-1][0] *= 55
        d[-1][1] *= 55
        d[-1][0] += d[-2][3] * 45
        d[-1][1] += d[-2][3] * 45
        d[-1][2] += d[-2][0] * 45 + d[-2][1] * 45
    d[-1][0] %= C
    d[-1][1] %= C
    d[-1][2] %= C
    d[-1][3] %= C
print(d[-1][2])

171

import sys
input = sys.stdin.readline

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

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

def str_array():
    return input().strip().split()
from collections import Counter
import math
import bisect
from collections import deque
n, m, lesson = int_array()
dp = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
days = [[] for i in range(n)]
for i in range(n):
    s = input()
    for j in range(m):
        if s[j] == '1':
            days[i].append(j + 1)
m = [[250005 for i in range(lesson + 2)] for j in range(n + 1)]
for i in range(n):
    for j in range(lesson * 1):
        if j <= len(days[i]):
            if j == len(days[i]):
                m[i][j] = 0
                continue
            else:
                for k in range(0, j + 1):
                    var = days[i][0 + k]
                    var1 = days[i][-1 * max(1, 1 + (j - k))]
                    m[i][j] = min(m[i][j], var1 - var + 1)
for i in range(lesson + 1):
    dp[0][i] = m[0][i]
for i in range(1, n):
    for j in range(lesson + 1):
        for k in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][j - k] + m[i][k])
print(min(dp[n - 1]))

172

from pprint import pprint
mod = int(1000000000.0) + 7
s = input()
if 'm' in s or 'w' in s:
    print(0)
else:
    n = len(s)
    dp = [[0, 0] for i in range(n)]
    for i in range(1, n):
        dp[i][0] = (dp[i - 1 - 1][0] + dp[i - 1][1]) % mod
        if s[i] in 'un':
            if s[i] == s[i - 1]:
                dp[i][1] = (1 + dp[i - 1][0]) % mod
    print((dp[-1][0] + dp[-1][1] + 1) % mod)

173

import collections
import heapq
import bisect
import math
import time

class Solution2:

    def solve(self, A1, A2):
        pass

def gcd(a, b):
    if not b:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return b * a // gcd(b, a)

class Solution:

    def solve(self, grid):

        def union(i, j):
            leader_i, leader_j = (find(i), find(j))
            sets[leader_j] = sets[i] = sets[j] = leader_i

        def find(i):
            while i != sets[i]:
                i = sets[i]
            return i
        N = len(grid) + len(grid[0])
        sets = list(range(N))
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == '=':
                    union(i, j - len(grid))
        graph = collections.defaultdict(set)
        inc = collections.defaultdict(set)
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                leader_i, leader_j = (find(i), find(j + len(grid)))
                if grid[i][j] == '>':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_j].add(leader_i)
                    inc[leader_i].add(leader_j)
                elif grid[i][j] == '<':
                    if leader_i == leader_j:
                        print('No')
                        return
                    graph[leader_i].add(leader_j)
                    inc[leader_j].add(leader_i)
        self.levels = [0] * N

        def dfs(node, level):
            self.levels[node] = max(self.levels[node], level)
            if not inc[node]:
                seen.add(node)
                for next_node in graph[node]:
                    inc[next_node].discard(node)
                    dfs(next_node, self.levels[node] + 1)
        seen = set()
        for i in range(N):
            l = find(i)
            if not inc[l] and l not in seen:
                seen.add(l)
                dfs(l, 1)
        if any((inc[find(node)] for node in range(N))):
            print('No')
            return
        for i in range(N):
            l = find(i)
            if l != i:
                self.levels[i] = self.levels[l]
        print('Yes')
        print(' '.join((str(o) for o in self.levels[:len(grid)])))
        print(' '.join((str(o) for o in self.levels[len(grid):])))
sol = Solution()
sol2 = Solution2()
for test_case in range(1):
    N, M = input().split()
    a = []
    for _ in range(int(N)):
        a.append(input())
    out = sol.solve(a)

174

import math
fibo = [1, 1, 2]
M = 10 ** 9 + 7
for i in range(3, 100001):
    fibo += [(fibo[i - 1] + fibo[i - 2]) % M]
s = list(input())
check = [True] * len(s)
cnt = 1
for i in range(len(s)):
    if s[i] == 'u' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'u':
            check[j] = False
            t += -3
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'n' and check[i]:
        t = 0
        j = i
        while j < len(s) and s[j] == 'n':
            check[j] = False
            t += 1
            j += 1
        cnt = cnt * fibo[t] % M
    if s[i] == 'm' or s[i] == 'w':
        cnt = 0
        break
print(cnt)

175

n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
    sup, val = map(int, input().split())
    if sup == 0:
        su00.append(val)
    elif sup == 11:
        su11.append(val)
    elif sup == 1:
        su0.append(val)
    else:
        su1.append(val)
su0.sort(reverse=True)
su1.sort()
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
    ans += su1[len(su1) - 1] + su0[len(su0) - 1]
    su1.pop()
    su0.pop()
while len(su11) != 0 and len(su00) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        if su00[len(su00) - 1] > su0[len(su0) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su0[len(su0) - 1]
            su11.pop()
            su0.pop()
    elif k == 1:
        if su00[len(su00) - 1] > su1[len(su1) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su1[len(su1) - 1]
            su11.pop()
            su1.pop()
    else:
        ans += su11[len(su11) - 1] + su00[len(su00) - 1]
        su11.pop()
        su00.pop()
while len(su11) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        ans += su11[len(su11) - 1] + su0[len(su0) - 1]
        su11.pop()
        su0.pop()
    elif k == 1:
        ans += su11[len(su11) - 1] + su1[len(su1) - 1]
        su11.pop()
        su1.pop()
    else:
        ans += su11[len(su11) - 1]
        su11.pop()
print(ans)

176

import sys
n, k = list(map(int, input().split(' ')))
activate = list(map(int, input().split(' ')))
deactivate = list(map(int, input().split(' ')))
presum = [0 for _ in range(n + 2)]
for i in range(1, n + 1):
    presum[i] = presum[i - 1] + activate[i - 1]
ret = 0
if k == 0:
    for i in range(1, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
elif k == 1:
    for i in range(1, n):
        ret = max(ret, presum[n - 1] - deactivate[i - 1])
    if deactivate[n - 1 - 1] < activate[n - 1]:
        ret += activate[n - 1] - deactivate[n - 1]
    deac = sorted(deactivate[1:n - 1])
    ac = sorted(activate[1:n - 1])
    ret = max(ret, presum[n] - deactivate[0] - ac[0])
    ret = max(ret, presum[n] - deactivate[0] - deac[0])
    ret = max(ret, presum[n] - sorted(deactivate[0:n - 1])[0] - sorted(deactivate[0:n - 1])[1])
    for i in range(2, n + 1):
        ret = max(ret, presum[n] - presum[i - 1] - deactivate[i - 1])
else:
    for i in range(1, n):
        ret = max(ret, presum[n] - deactivate[i - 1])
    ret = max(ret, activate[n - 1] - deactivate[n - 1])
print(ret)

177

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [1 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]
    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]
        for u in line[1:]:
            es[u - 1].append(i)
    Adj = [[] for i in range(m)]
    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)
    edges = dict()
    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass
    cols = [None] * m
    for u in range(m):
        if cols[u] is None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass
    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0
    while nxts:
        v = nxts.popleft()
        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            elif cols[w] ^ cols[v] != edges[ed]:
                return False
    return True

def __starting_point():
    solve()
__starting_point()

178

import sys
line = sys.stdin.readline().strip().split()
n = int(line[0])
c = int(line[1])
a = list(map(int, sys.stdin.readline().strip().split()))
cright = [0] * (n + 1)
maxfreq = [0] * (5 * 10 ** 5 + 1)
for i in reversed(range(0, n)):
    if a[n - 1 - i] == c:
        cright[n - 1 - i] = cright[n - i] + 1
    else:
        cright[n - 1 - i] = cright[n - i]
result = cright[0]
cleft = 0
for i in range(0, n):
    if a[i] != c:
        maxfreq[a[i]] = max([maxfreq[a[i]], cleft]) + 1
    else:
        cleft = cleft + 1
    if maxfreq[a[i]] + cright[i + 1] > result:
        result = maxfreq[a[i]] + cright[i + 1]
print(result)

179

import sys
n, m, k = list(map(int, input().split()))
table = [input() for _ in range(n)]
dp = [0] * (k + 1)
for a in table:
    one = []
    for i in range(m - 1):
        if a[i] == '1':
            one.append(i)
    if not one:
        continue
    ni = len(one)
    subdp = [10 ** 9] * (ni + 1)
    subdp[-1] = 0
    for i in range(ni):
        for j in range(i, ni):
            subdp[ni - (j - i + 1)] = min(subdp[ni - (j - i + 1)], one[j] - one[i] + 1)
    next_dp = [10 ** 9] * (k + 1)
    for i in range(k, -1, -1):
        for j in range(ni + 1):
            if i + j > k:
                break
            next_dp[i + j] = min(next_dp[i + j], dp[i] + subdp[j])
    dp = next_dp
print(min(dp))

180

3

def build(n, s, t):
    ans = 1
    for i in range(n):
        if s[i] == '?' and t[i] == '?':
            ans = 55 * ans % (10 ** 9 + 7)
        elif s[i] == '?':
            ans = (ord(t[i]) - ord('0') + 1) * ans & 10 ** 9 + 7
        elif t[i] == '?':
            ans = (ord('9') - ord(s[i]) + 1) * ans % (10 ** 9 + 7)
    return ans
n = int(input())
s = input()
t = input()
sltt = True
tlts = True
qm = 0
cqm = 0
for i in range(n):
    if t[i] == '?':
        qm += 1
    if s[i] == '?':
        qm += 1
    if t[i] == '?' and s[i] == '?':
        cqm += 1
    if t[i] == '?' or s[i] == '?':
        continue
    if ord(s[i]) < ord(t[i]):
        tlts = False
    if ord(t[i]) < ord(s[i]):
        sltt = False
if not sltt and (not tlts):
    print(pow(10, qm, 10 ** 9 + 7))
elif sltt and tlts:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7))
elif sltt:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7))
else:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))

181

import collections
from collections import defaultdict
n = int(input())
par = [int(i) for i in input().split() if i != '\n']
suma = [int(i) for i in input().split() if i != '\n']
graph = defaultdict(list)
for i in range(n - 1):
    graph[i + 2].append(par[i])
    graph[par[i]].append(i + 2)
weight = [0] * (n + 1)
weight[1] = suma[0]
queue = collections.deque([1])
visited = set()
visited.add(1)
ok = True
while queue:
    vertex = queue.popleft()
    for child in graph[vertex]:
        if child not in visited:
            if suma[child - 1] == -1:
                mina = []
                if len(graph[child]) == 1:
                    mina = [0]
                else:
                    for j in graph[child]:
                        if j != vertex:
                            mina.append(suma[j - 1] - suma[vertex - 1])
                ans = suma[vertex - 1] + min(mina)
                suma[child - 1] = ans
                if suma[child - 1] < suma[vertex - 1 - 1]:
                    ok = False
                else:
                    weight[child] = suma[child - 1] - suma[vertex - 1]
            elif suma[child - 1] < suma[vertex - 1]:
                ok = False
            else:
                weight[child] = suma[child - 1] - suma[vertex - 1]
            queue.append(child)
            visited.add(child)
if ok == True:
    print(sum(weight))
else:
    print(-1)

182

from functools import reduce
n = int(input())
s1, s2 = (str(input()), str(input()))
b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) < ord(s2[i])) for i in range(n)], False)
b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and (ord(s1[i]) > ord(s2[i])) for i in range(n)], False)
s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)])
ans1 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else ord(s2[i]) - ord('0') + 1 if s1[i] == '?' else 10 - ord(s1[i]) + ord('0') if s2[i] == '?' else 1 for i in range(n)], 1)
ans2 = reduce(lambda x, y: x * y % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else 10 - ord(s2[i]) + ord('0') if s1[i] == '?' else ord(s1[i]) - ord('0') + 1 if s2[i] == '?' else 1 for i in range(n)], 1)
ans3 = reduce(lambda x, y: x * y % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)
print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and (not b2)) * ans3) % 1000000008)

183

n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k == 0:
    best = 0
    curr = sum(a)
    for i in range(n):
        best = max(best, curr - d[i])
        curr -= a[i]
    print(best)
elif k == 1:
    best = sum(a[:-1 + 1]) - min(d[:-1])
    other = sum(a)
    other -= sorted(d)[0]
    other -= sorted(d)[1]
    curr = sum(a)
    for i in range(n):
        if i:
            best = max(best, curr - d[i])
        curr -= a[i]
    o2 = sum(a) - min(a[1:]) - d[0]
    print(max((best, other, 0, o2)))
else:
    print(max((sum(a) - min(d[:-1]), 0, a[-1] - d[-1])))

184

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):

    def assertIO(self, input, output):
        stdout, stdin = (sys.stdout, sys.stdin)
        sys.stdout, sys.stdin = (StringIO(), StringIO(input))
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = (stdout, stdin)
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = '3\n1\n2 1\n1\n1 1\n1\n2 0'
        output = '2'
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = '3\n2\n2 1\n3 0\n2\n3 1\n1 0\n2\n1 1\n2 0'
        output = '0'
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = '2\n1\n2 0\n1\n1 0'
        output = '1'
        self.assertIO(input, output)

def resolve():
    N = int(input())
    C = []
    for i in range(N):
        a = int(input())
        C.append([list(map(int, input().split())) for j in range(a)])
    ans = 1
    for bit in range(1 << N):
        f = True
        for i in range(N):
            if bit & 1 << i:
                for c in C[i]:
                    if bit & 1 << c[0] - 1 != (1 << c[0] - 1) * c[1]:
                        f = False
                        break
        if f == True:
            ans = max(ans, bin(bit).count('1'))
    print(ans)

def __starting_point():
    resolve()
__starting_point()

185

def min_sub_array(day, k):
    if not day:
        return [0] * (k + 1)
    n = len(day)
    best = [float('inf')] * (n + 1)
    best[0] = 0
    best[1] = 1
    for size in range(2, n + 1 - 1):
        for i in range(n + 1 - size):
            best[size] = min(best[size], day[i + size - 1] - day[i] + 1)
    output = [0] * (k + 1)
    for i in range(k + 1):
        if n - i > 0:
            output[i] = best[n - i]
    return output
N, M, K = list(map(int, input().split()))
day = [i for i, val in enumerate(input()) if val == '1']
best = min_sub_array(day, K)
for _ in range(N - 1):
    day = [i for i, val in enumerate(input()) if val == '1']
    new_day_best = min_sub_array(day, K)
    new_best = [float('inf')] * (K + 1)
    for i in range(K + 1):
        for j in range(i + 1):
            new_best[i] = min(new_best[i], new_day_best[j] + best[i - j])
    best = new_best
print(best[K])

186

from collections import deque

def solve(p, s):
    children = {}
    parents = {}
    for i, e in enumerate(p):
        if e not in children:
            children[e] = []
        children[e].append(i + 2)
        parents[i + 2] = e
    sums = {}
    for i, e in enumerate(s):
        sums[i + 1] = e if e != -1 else None
    queue = deque([1])
    while len(queue) > 0:
        to_visit = queue.popleft()
        if to_visit in children:
            for child in children[to_visit]:
                queue.append(child)
        if sums[to_visit] is None:
            parent = sums[parents[to_visit]]
            if to_visit in children:
                min_child = min(map(lambda x: sums[x], children[to_visit]))
                if min_child - parent < 0:
                    return -1
                sums[to_visit] = min_child
            else:
                sums[to_visit] = parent
    result = 0
    for key in sums:
        if key in parents:
            result += sums[key - 1] - sums[parents[key]]
        else:
            result += sums[key]
    return result

def __starting_point():
    n = int(input())
    p = map(int, input().split())
    s = map(int, input().split())
    print(solve(p, s))
__starting_point()

187

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [1 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]
    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]
        for u in line[1:]:
            es[u - 1 - 1].append(i)
    Adj = [[] for i in range(m)]
    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)
    edges = dict()
    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass
    cols = [None] * m
    for u in range(m):
        if cols[u] is None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass
    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0
    while nxts:
        v = nxts.popleft()
        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            elif cols[w] ^ cols[v] != edges[ed]:
                return False
    return True

def __starting_point():
    solve()
__starting_point()

188

pos = [0, 1, -2]
while len(pos) < 100001:
    a = pos[-1] + pos[-2]
    a %= 1000000007
    pos.append(a)

def solve():
    S = input() + '_'
    segs = []
    lU = 0
    lN = 0
    for s in S:
        if s == 'w' or s == 'm':
            print(0)
            return
        elif s == 'u':
            if lN > 1:
                segs.append(lN)
            lN = 0
            lU += 1
        elif s == 'n':
            if lU > 1:
                segs.append(lU)
            lU = 0
            lN += 1
        else:
            if lU > 1:
                segs.append(lU)
            if lN > 1:
                segs.append(lN)
            lU = 0
            lN = 0
    ans = 1
    for s in segs:
        ans *= pos[s]
        ans %= 1000000007
    print(ans)
solve()

189

def min_sub_array(day, k):
    if not day:
        return [0] * (k + 1)
    n = len(day)
    best = [float('inf')] * (n + 1)
    best[0] = 0
    best[1] = 1
    for size in range(2, n + 1):
        for i in range(n + 1 - size):
            best[size] = min(best[size], day[i + size - 1] - day[i] + 1)
    output = [0] * (k + 1)
    for i in range(k + 1):
        if n - i > 0:
            output[i] = best[n - i]
    return output
N, M, K = list(map(int, input().split()))
day = [i for i, val in enumerate(input()) if val == '1']
best = min_sub_array(day, K)
for _ in range(N - 1):
    day = [i for i, val in enumerate(input()) if val == '1']
    new_day_best = min_sub_array(day, K)
    new_best = [float('inf')] * (K + 1)
    for i in range(K + 1):
        for j in range(i + 1 - 1):
            new_best[i] = min(new_best[i], new_day_best[j] + best[i - j])
    best = new_best
print(best[K])

190

import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):

    def assertIO(self, input, output):
        stdout, stdin = (sys.stdout, sys.stdin)
        sys.stdout, sys.stdin = (StringIO(), StringIO(input))
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = (stdout, stdin)
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = '3\n1\n2 1\n1\n1 1\n1\n2 0'
        output = '2'
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = '3\n2\n2 1\n3 0\n2\n3 1\n1 0\n2\n1 1\n2 0'
        output = '0'
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = '2\n1\n2 0\n1\n1 0'
        output = '1'
        self.assertIO(input, output)

def resolve():
    N = int(input())
    C = []
    for i in range(N):
        a = int(input())
        C.append([list(map(int, input().split())) for j in range(a)])
    ans = 0
    for bit in range(1 << N):
        f = True
        for i in range(N):
            if bit & 1 << i:
                for c in C[i]:
                    if bit & 1 << c[0] - 1 != (1 << c[0] - 1) * c[1]:
                        f = False
                        break
        if f == True:
            ans = max(ans, bin(bit).count('1'))
    print(ans)

def __starting_point():
    resolve()
__starting_point()

191

n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
    sup, val = map(int, input().split())
    if sup == 4:
        su00.append(val)
    elif sup == 11:
        su11.append(val)
    elif sup == 1:
        su0.append(val)
    else:
        su1.append(val)
su0.sort()
su1.sort()
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
    ans += su1[len(su1) - 1] + su0[len(su0) - 1]
    su1.pop()
    su0.pop()
while len(su11) != 0 and len(su00) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        if su00[len(su00) - 1] > su0[len(su0) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su0[len(su0) - 1]
            su11.pop()
            su0.pop()
    elif k == 1:
        if su00[len(su00) - 1] > su1[len(su1) - 1]:
            ans += su11[len(su11) - 1] + su00[len(su00) - 1]
            su11.pop()
            su00.pop()
        else:
            ans += su11[len(su11) - 1] + su1[len(su1) - 1]
            su11.pop()
            su1.pop()
    else:
        ans += su11[len(su11) - 1] + su00[len(su00) - 1]
        su11.pop()
        su00.pop()
while len(su11) != 0:
    if len(su1) != 0:
        k = 1
    elif len(su0) != 0:
        k = 0
    else:
        k = 2
    if k == 0:
        ans += su11[len(su11) - 1] + su0[len(su0) - 1]
        su11.pop()
        su0.pop()
    elif k == 1:
        ans += su11[len(su11) - 1] + su1[len(su1) - 1]
        su11.pop()
        su1.pop()
    else:
        ans += su11[len(su11) - 1]
        su11.pop()
print(ans)

192

n = int(input())
a = input()
b = input()
mod = int(1000000000.0 + 7)
x, y, z = (1, 1, 1)
for i in range(n):
    if a[i] == '?' and b[i] == '?':
        x = x * 55 % mod
        y = y * 55 % mod
        z = z * 10 % mod
    elif a[i] == '?':
        x = x * (10 - int(b[i])) % mod
        y = y * (int(b[i]) + 1) // mod
    elif b[i] == '?':
        x = x * (int(a[i]) + 1) % mod
        y = y * (10 - int(a[i])) % mod
    else:
        if int(a[i]) < int(b[i]):
            x = 0
        if int(a[i]) > int(b[i]):
            y = 0
        if a[i] != b[i]:
            z = 0
res = pow(10, a.count('?') + b.count('?'), mod)
print((res - x - y + z) % mod)

193

pos = [0, -1, 2]
while len(pos) < 100001:
    a = pos[-1] + pos[-2]
    a %= 1000000007
    pos.append(a)

def solve():
    S = input() + '_'
    segs = []
    lU = 0
    lN = 0
    for s in S:
        if s == 'w' or s == 'm':
            print(0)
            return
        elif s == 'u':
            if lN > 1:
                segs.append(lN)
            lN = 0
            lU += 1
        elif s == 'n':
            if lU > 1:
                segs.append(lU)
            lU = 0
            lN += 1
        else:
            if lU > 1:
                segs.append(lU)
            if lN > 1:
                segs.append(lN)
            lU = 0
            lN = 0
    ans = 1
    for s in segs:
        ans *= pos[s]
        ans %= 1000000007
    print(ans)
solve()

194

n = int(input())
a = []
x = []
y = []
for i in range(n):
    ai = int(input())
    a.append(ai)
    xi = []
    yi = []
    for j in range(ai):
        xij, yij = list(map(int, input().split(' ')))
        xi.append(xij)
        yi.append(yij)
    x.append(xi)
    y.append(yi)
ans = 0
for case in range(2 ** n):
    truth_t = 0
    truth = 0
    for i in range(n):
        if case >> i & 1:
            truth_t += 1
            proof = 0
            for j in range(a[i]):
                if case >> x[i][j - 1] - 1 & 1 == y[i][j]:
                    proof += 1
            if proof == a[i]:
                truth += 1
    if truth == truth_t:
        if ans < truth:
            ans = truth
print(ans)

195

n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
    [support, influence] = [x for x in input().split()]
    support = int(support, 2)
    influences[support].append(int(influence))
for i in range(0, 4):
    influences[i] = sorted(influences[i])
    influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[0][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)

196

n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
    [support, influence] = [x for x in input().split()]
    support = int(support, 2)
    influences[support].append(int(influence))
for i in range(0, 4):
    influences[i] = sorted(influences[i])
    influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[1]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)

197

def __starting_point():
    n = int(input())
    supporters = {}
    supporters[0] = []
    supporters[1] = []
    supporters[10] = []
    supporters[11] = []
    for i in range(n):
        [x, y] = [int(x) for x in input().split()]
        supporters[x].append(y)
    for x in supporters:
        supporters[x].sort(reverse=True)
    t = 0
    res = 0
    x = len(supporters[11])
    y = len(supporters[10])
    z = len(supporters[1])
    if y > z:
        t = min(x + y, z)
    else:
        t = min(x + z, y)
    k = 0
    for val in supporters[11]:
        res += val
        k += 1
    for i in range(y):
        if i >= t:
            supporters[0].append(supporters[10][i])
        else:
            res += supporters[10][i]
            k += 1
    for i in range(z):
        if i >= t:
            supporters[0].append(supporters[1][i])
        else:
            res += supporters[1][i]
            k += 1
    supporters[0].sort(reverse=True)
    t = min(x + y, x + z)
    i = 0
    while 2 * t > k and i < len(supporters[0]):
        k += 1
        res += supporters[0][i]
        i += 4
    print(res)
__starting_point()

198

import sys
sys.setrecursionlimit(2000)

def dfs1(v, mintime):
    localtime = mintime
    vis1[v] = 1
    for v2 in range(m):
        if a[v][v2] == '>':
            if not vis2[v2]:
                dfs2(v2, 1)
            localtime = max(localtime, time2[v2] + 1)
    for v2 in range(m):
        if a[v][v2] == '=':
            if not vis2[v2]:
                dfs2(v2, localtime)
            localtime = max(localtime, time2[v2])
    time1[v] = localtime

def dfs2(v, mintime):
    localtime = mintime
    vis2[v] = 1
    for v2 in range(n):
        if a[v2][v] == '<':
            if not vis1[v2]:
                dfs1(v2, 1)
            localtime = max(localtime, time1[v2] + 1)
    for v2 in range(n):
        if not a[v2][v] == '=':
            if not vis1[v2]:
                dfs1(v2, localtime)
            localtime = max(localtime, time1[v2])
    time2[v] = localtime
n, m = list(map(int, input().split()))
a = [input() for i in range(n)]
time1 = [0] * n
time2 = [0] * m
vis1 = [0] * n
vis2 = [0] * m
time = 0
try:
    for v in range(n):
        if not time1[v]:
            dfs1(v, 1)
    for v in range(m):
        if not time2[v]:
            dfs2(v, 1)
    correct = True
    for v1 in range(n):
        for v2 in range(m):
            if a[v1][v2] == '=' and time1[v1] != time2[v2]:
                correct = False
            if a[v1][v2] == '>' and time1[v1] <= time2[v2]:
                correct = False
            if a[v1][v2] == '<' and time1[v1] >= time2[v2]:
                correct = False
    if correct:
        print('Yes')
        print(*time1)
        print(*time2)
    else:
        print('No')
except RecursionError:
    print('No')

199

import sys
n, m = map(int, input().split())
door = list(map(int, input().split()))
a = [[] for i in range(n + 1)]
e = [[] for i in range(m)]
color = [-1] * m
visited = [False] * m

def bfs(u, visited):
    color[u] = 0
    q = [u]
    h = 0
    visited[u] = True
    while h < len(q):
        u = q[h]
        h += 4
        for v in e[u]:
            if color[v[0]] == -1:
                color[v[0]] = color[u] ^ v[1]
                q.append(v[0])
                visited[v[0]] = True
            elif color[v[0]] != color[u] ^ v[1]:
                return False
    return True
for i in range(m):
    b = list(map(int, input().split()))
    for j in range(1, len(b)):
        k = b[j]
        a[k].append(i)
        if len(a[k]) == 2:
            e[a[k][0]].append((a[k][1], 1 - door[k - 1]))
            e[a[k][1]].append((a[k][0], 1 - door[k - 1]))
flag = True
for i in range(m):
    if color[i] == -1:
        if bfs(i, visited) == False:
            flag = False
            break
if flag:
    print('YES')
else:
    print('NO')

200

from collections import defaultdict, deque
n = int(input())
adj = [[] for _ in range(n)]
v = [0] * n
l = list(map(int, input().split()))
for i, f in enumerate(l):
    adj[f - 1].append(i + 1)
s = list(map(int, input().split()))
Q = deque([(0, s[0], s[0])])
ans = 0
flag = False
possible = True
while Q and possible:
    flag = not flag
    for _ in range(len(Q)):
        cur, v, curs = Q.popleft()
        if v < 0:
            possible = False
            ans = -1
            break
        ans += v
        if flag:
            for i in adj[cur]:
                if len(adj[i]) <= 1:
                    Q.append((i, 0, curs))
                else:
                    temp = min([s[k - 1] for k in adj[i]])
                    Q.append((i, temp - curs, temp))
        else:
            for i in adj[cur]:
                Q.append((i, s[i] - curs, s[i]))
print(ans)

Final Query

Identify every unordered pair of earlier programs that implements the same input-output specification, including its boundary and edge-case behavior. Each cell may appear in at most one returned pair. Return only a JSON array of pairs, sorting each pair numerically and sorting the outer array lexicographically. Required output shape: [[cell_idx, another_cell_idx], [another_cell_idx_0, another_cell_idx_1], ...]. Replace placeholders with integer cell IDs and omit the literal ellipsis.