import random
import sys
from math import inf

from typing import List

# sys.setrecursionlimit(10**8)è®¾ç½®æå¤§éå½æ¬¡æ°

class FastIO:
    def __init__(self):
        self.random_seed = random.randint(0, 10 ** 9 + 7)
        return

    @staticmethod
    def read_int():
        return int(sys.stdin.readline().strip())

    @staticmethod
    def read_float():
        return float(sys.stdin.readline().strip())

    @staticmethod
    def read_list_ints():
        return list(map(int, sys.stdin.readline().strip().split()))

    @staticmethod
    def read_list_floats():
        return list(map(float, sys.stdin.readline().strip().split()))

    @staticmethod
    def read_list_ints_minus_one():
        return list(map(lambda x: int(x) - 1, sys.stdin.readline().strip().split()))

    @staticmethod
    def read_str():
        return sys.stdin.readline().strip()

    @staticmethod
    def read_list_strs():
        return sys.stdin.readline().strip().split()

    @staticmethod
    def read_list_str():
        return list(sys.stdin.readline().strip())

    @staticmethod
    def st(x):
        return print(x)

    @staticmethod
    def lst(x):
        return print(*x)

    @staticmethod
    def round_5(f):
        res = int(f)
        if f - res >= 0.5:
            res += 1
        return res

    @staticmethod
    def max(a, b):
        return a if a > b else b

    @staticmethod
    def min(a, b):
        return a if a < b else b

    @staticmethod
    def ceil(a, b):
        return a // b + int(a % b != 0)

    def hash_num(self, x):
        return x ^ self.random_seed

    @staticmethod
    def accumulate(nums):
        n = len(nums)
        pre = [0] * (n + 1)
        for i in range(n):
            pre[i + 1] = pre[i] + nums[i]
        return pre

    def inter_ask(self, lst):
        # CFäº¤äºé¢è¾åºè¯¢é®å¹¶è¯»åç»æ
        self.st(lst)
        sys.stdout.flush()
        res = self.read_int()
        # è®°å¾ä»»ä½ä¸ä¸ªè¾åºä¹åé½è¦ sys.stdout.flush() å·æ°
        return res

    def inter_out(self, lst):
        # CFäº¤äºé¢è¾åºæç»çæ¡
        self.st(lst)
        sys.stdout.flush()
        return

class SegmentTreeUpdateQueryMin:
    # æ¨¡æ¿ï¼çº¿æ®µæ åºé´æ´æ°ãæç»åå°æå°å¼
    def __init__(self, n):
        self.height = [inf]*(4*n)
        self.lazy = [inf]*(4*n)
        self.n = n

    def build(self, nums: List[int]):
        # ä½¿ç¨æ°ç»åå§åçº¿æ®µæ
        stack = [[0, self.n - 1, 1]]
        while stack:
            s, t, ind = stack.pop()
            if ind >= 0:
                if s == t:
                    self.make_tag(ind, nums[s])
                else:
                    stack.append([s, t, ~ind])
                    m = s + (t - s) // 2
                    stack.append([s, m, 2 * ind])
                    stack.append([m + 1, t, 2 * ind + 1])
            else:
                ind = ~ind
                self.push_up(ind)
        return

    def get(self):
        # æ¥è¯¢åºé´çææå¼
        stack = [[0, self.n-1, 1]]
        nums = [inf]*self.n
        while stack:
            s, t, i = stack.pop()
            if s == t:
                nums[s] = self.height[i]
                continue
            m = s + (t - s) // 2
            self.push_down(i)
            stack.append([s, m, 2 * i])
            stack.append([m + 1, t, 2 * i + 1])
        return nums

    @staticmethod
    def min(a, b):
        return a if a < b else b

    def push_down(self, i):
        # ææ è®°ä¸æ¾ï¼æ³¨æåæå°å¼
        if self.lazy[i] != inf:
            self.height[2 * i] = self.min(self.height[2 * i], self.lazy[i])
            self.height[2 * i + 1] = self.min(self.height[2 * i + 1], self.lazy[i])

            self.lazy[2 * i] = self.min(self.lazy[2 * i], self.lazy[i])
            self.lazy[2 * i + 1] = self.min(self.lazy[2 * i + 1], self.lazy[i])

            self.lazy[i] = inf
        return

    def make_tag(self, i, val):
        self.height[i] = self.min(self.height[i], val)
        self.lazy[i] = self.min(self.lazy[i], val)
        return

    def push_up(self, i):
        self.height[i] = self.min(self.height[2 * i], self.height[2 * i + 1])
        return

    def update_range(self, left, right, s, t, val, i):
        # æ´æ°åºé´æå°å¼
        stack = [[s, t, i]]
        while stack:
            a, b, i = stack.pop()
            if i >= 0:
                if left <= a and b <= right:
                    self.make_tag(i, val)
                    continue

                self.push_down(i)
                stack.append([a, b, ~i])
                m = a + (b - a) // 2
                if left <= m:  # æ³¨æå·¦å³åæ çè¾¹çä¸èå´
                    stack.append([a, m, 2 * i])
                if right > m:
                    stack.append([m + 1, b, 2 * i + 1])
            else:
                i = ~i
                self.push_up(i)
        return

    def update_point(self, left, right, s, t, val, i):
        # æ´æ°åç¹æå°å¼
        while True:
            if left <= s and t <= right:
                self.make_tag(i, val)
                break
            self.push_down(i)
            m = s + (t - s) // 2
            if left <= m:  # æ³¨æå·¦å³åæ çè¾¹çä¸èå´
                s, t, i = s, m, 2 * i
            if right > m:
                s, t, i = m + 1, t, 2 * i + 1

        while i > 1:
            i //= 2
            self.push_up(i)
        return

    def query_range(self, left, right, s, t, i):
        # æ¥è¯¢åºé´çæå°å¼
        stack = [[s, t, i]]
        floor = inf
        while stack:
            a, b, i = stack.pop()
            if left <= a and b <= right:
                floor = self.min(floor, self.height[i])
                continue
            self.push_down(i)
            m = a + (b - a) // 2
            if left <= m:
                stack.append([a, m, 2*i])
            if right > m:
                stack.append([m+1, b, 2*i + 1])
        return floor

    def query_point(self, left, right, s, t, i):
        # æ¥è¯¢åç¹çæå°å¼
        a, b, i = s, t, i
        while True:
            if left <= a and b <= right:
                ans = self.height[i]
                break
            self.push_down(i)
            m = a + (b - a) // 2
            if left <= m:
                a, b, i = a, m, 2 * i
            if right > m:
                a, b, i = m + 1, b, 2 * i + 1
        return ans

class Solution:
    def __init__(self):
        return

    @staticmethod
    def main(ac=FastIO()):
        n, k = ac.read_list_ints()
        s = ac.read_str()
        tree = SegmentTreeUpdateQueryMin(n)
        one = -1
        for i in range(n):
            if s[i] == "1":
                left = ac.max(0, i-k)
                right = ac.min(n-1, i+k)
                if left < one:
                    left = one+k+1
                if left > i:
                    left = i
                pre = tree.query_range(left-1, left-1, 0, n-1, 1) if left else 0
                cur = pre + i+1
                tree.update_range(i, right, 0, n-1, cur, 1)
                one = i
            else:
                pre = tree.query_point(i-1, i-1, 0, n-1, 1) if i else 0
                cur = pre + i+1
                tree.update_point(i, i, 0, n-1, cur, 1)
        ac.st(tree.query_point(n-1, n-1, 0, n-1, 1))
        return

Solution().main()

You work as a system administrator in a dormitory, which has $$$n$$$ rooms one after another along a straight hallway. Rooms are numbered from $$$1$$$ to $$$n$$$.You have to connect all $$$n$$$ rooms to the Internet.You can connect each room to the Internet directly, the cost of such connection for the $$$i$$$-th room is $$$i$$$ coins. Some rooms also have a spot for a router. The cost of placing a router in the $$$i$$$-th room is also $$$i$$$ coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room $$$i$$$, you connect all rooms with the numbers from $$$max(1,~i - k)$$$ to $$$min(n,~i + k)$$$ inclusive to the Internet, where $$$k$$$ is the range of router. The value of $$$k$$$ is the same for all routers. Calculate the minimum total cost of connecting all $$$n$$$ rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — the number of rooms and the range of each router.
The second line of the input contains one string $$$s$$$ of length $$$n$$$, consisting only of zeros and ones. If the $$$i$$$-th character of the string equals to '1' then there is a spot for a router in the $$$i$$$-th room. If the $$$i$$$-th character of the string equals to '0' then you cannot place a router in the $$$i$$$-th room.

Print one integer — the minimum total cost of connecting all $$$n$$$ rooms to the Internet.

import sys

input = lambda: sys.stdin.buffer.readline().decode().strip()
n, m = map(int, input().split())
mem, dp, le = [10 ** 18] * (n + 1), [0] * (n + 1), [0] * (n + 1)

for i, j in enumerate(input(), 1):
    if j == '1':
        l, r = max(i - m, 1), min(i + m, n)
        k = i
        while k >= l and mem[k] == 10 ** 18:
            mem[k], le[k] = i, l - 1
            k -= 1

        k = r
        while k >= l and mem[k] == 10 ** 18:
            mem[k], le[k] = i, l - 1
            k -= 1

for i in range(1, n + 1):
    dp[i] = dp[i - 1] + i
    if mem[i]:
        dp[i] = min(dp[i], dp[le[i]] + mem[i])

print(dp[-1])


import os
import sys
from atexit import register
from io import BytesIO

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))

input = lambda: sys.stdin.readline().rstrip('\r\n')
def make(size):
    rank = [0]*size
    same = range(size)
    return same,rank

def find(x,same):

    if x != same[x]:
        same[x] = find(same[x],same)
    return same[x]

def union( x,y,same,rank):
    x = find(x,same)
    y = find(y,same)
    if x == y :
        return
    if rank[x] > rank[y]:
        same[y] = x
    else:
        same[x] = y
    if rank[x] == rank[y]:
        rank[y] += 1

def add(dic,k,v):
	if not dic.has_key(k):
		dic[k] = v
	else:
		dic[k]+= v
n,m = map(int,input().split(" "))
ws = map(int,input().split(" "))
same,rank = make(n+1)
edges = []
degrees = [0]*(n+1)
for i in range(m):
	a,b = map(int,input().split(" "))
	edges.append((a,b))
	degrees[a] += 1
	degrees[b] += 1

s = int(input())
for a,b in edges:
	if a!=s and b!=s:
		union(a,b,same,rank)

for i in range(n+1):
	same[i]=find(i,same)
dic = {}

for i,v in enumerate(same):
	add(dic,v,[i])

ret = 0
for k,v in dic.items():
	ans = 0
	maxv = 0
	for i in v:
		if degrees[i] >= 2 or i == s:
			ans += ws[i-1]
		else:
			maxv = max(maxv,ws[i-1])
	ret  = max(ret,maxv+ans)
print ret+ws[s-1]

Alex decided to go on a touristic trip over the country.For simplicity let's assume that the country has $$$n$$$ cities and $$$m$$$ bidirectional roads connecting them. Alex lives in city $$$s$$$ and initially located in it. To compare different cities Alex assigned each city a score $$$w_i$$$ which is as high as interesting city seems to Alex.Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $$$v$$$ from city $$$u$$$, he may choose as the next city in the trip any city connected with $$$v$$$ by the road, except for the city $$$u$$$.Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.

First line of input contains two integers $$$n$$$ and $$$m$$$, ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) which are numbers of cities and roads in the country.
Second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$) which are scores of all cities.
The following $$$m$$$ lines contain description of the roads. Each of these $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$) which are cities connected by this road.
It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads.
The last line contains single integer $$$s$$$ ($$$1 \le s \le n$$$), which is the number of the initial city.

Output single integer which is the maximum possible sum of scores of visited cities.

import sys
input = sys.stdin.buffer.readline

def process(A, G, s):
    n = len(A)
    m = len(G)
    g = [[] for i in range(n+1)]
    riskfree = [0 for i in range(n+1)]
    parent = [None for i in range(n+1)]
    visited = [0 for i in range(n+1)]
    values = [0 for i in range(n+1)]
    for i in range(m):
        u, v = G[i]
        g[u].append(v)
        g[v].append(u)
  #  def dfs(g, x, parent):
  #      visited[x] = 1
   #     for y in g[x]:
   #         if y != parent[x]:
   #             if visited[y]==1:
   ##                 x1 = x
    #                while riskfree[x1]==0:
    #                    riskfree[x1] = 1
    #                    x1 = parent[x1]
    ##            else:
     #               parent[y] = x
     #               dfs(g, y, parent)
    start = [s]
    riskfree[s] = 1
    while len(start) > 0:
        x = start.pop()
        visited[x] = 1
        for y in g[x]:
            if y != parent[x]:
                if visited[y]==1:
                    x1 = x
                    while riskfree[x1]==0:
                        riskfree[x1] = 1
                        x1 = parent[x1]
                else:
                    parent[y] = x
                    start.append(y)

    answer = sum([A[i-1] for i in range(1, n+1) if riskfree[i]==1])
    start = [s]
    leaf_max = 0
    while len(start) > 0:
        next_s = []
        for x in start:
            for y in g[x]:
                if riskfree[y] != 2:
                    next_s.append(y)
                    if riskfree[y]==0:
                        values[y] = values[x]+A[y-1]
                        leaf_max = max(leaf_max, values[y])
                    riskfree[y] = 2
        start = next_s
    answer+=leaf_max
    return answer

n, m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
G = []
for i in range(m):
    u, v = [int(x) for x in input().split()]
    G.append([u, v])
s = int(input())
print(process(A, G, s))


(n , m) = map(int,raw_input().split())

arr = []

for i in range (n):
    arr.append(map(int,raw_input().split())[1:])

seq = map(int,raw_input().split())

def gao(x):
    ans = - 2 ** 64
    now = 0
    for i in range (len(x)):
        now += x[i]
        ans = max(ans,now)
    return ans;
def gao2(x):
    now = x[0]
    ans = now
    for i in range(1,len(x)):
        now = max(x[i] , now + x[i])
        ans = max(ans,now)
    return ans
def doit(x):
    ans = - 2 ** 64
    now = 0
    for i in range (len(x) - 1, -1 , -1):
        now += x[i]
        ans = max(ans,now)
    return ans;

dp = []
pre = []
s = []
af = []

for i in range (n):
    pre.append(doit(arr[i]))
    s.append(sum(arr[i]))
    af.append(gao(arr[i]))

dp.append([sum(arr[seq[0] - 1]),pre[seq[0] - 1]])

for i in range (1,m):
    add = max(dp[-1][0],pre[seq[i-1] - 1])
    dp.append([ add + s[seq[i] - 1] , add + af[seq[i] - 1]  ]  )

ans = - 2 ** 64

for i in range (len(seq)):
    ans = max(ans,gao2(arr[seq[i] - 1]))

for i in range (len(dp)):
    ans = max(ans,dp[i][0])
    ans = max(ans,dp[i][1])

print ans

Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?

The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n. The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.

Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).

(n , m) = map(int,raw_input().split())

arr = []

for i in range (n):
    arr.append(map(int,raw_input().split())[1:])

seq = map(int,raw_input().split())

def gao(x):
    ans = - 2 ** 64
    now = 0
    for i in range (len(x)):
        now += x[i]
        ans = max(ans,now)
    return ans;
def gao2(x):
    now = x[0]
    ans = now
    for i in range(1,len(x)):
        now = max(x[i] , now + x[i])
        ans = max(ans,now)
    return ans
def doit(x):
    ans = - 2 ** 64
    now = 0
    for i in range (len(x) - 1, -1 , -1):
        now += x[i]
        ans = max(ans,now)
    return ans;

dp = []
pre = []
s = []
af = []
bak = []

for i in range (n):
    pre.append(doit(arr[i]))
    s.append(sum(arr[i]))
    af.append(gao(arr[i]))
    bak.append(gao2(arr[i]))
dp.append([sum(arr[seq[0] - 1]),pre[seq[0] - 1]])

for i in range (1,m):
    add = max(dp[-1][0],pre[seq[i-1] - 1])
    dp.append([ add + s[seq[i] - 1] , add + af[seq[i] - 1]  ]  )

ans = - 2 ** 64

for i in range (len(seq)):
    ans = max(ans,bak[seq[i] - 1])

for i in range (len(dp)):
    ans = max(ans,dp[i][0])
    ans = max(ans,dp[i][1])

print ans


import sys; R = sys.stdin.readline
for _ in range(int(R())):
    n,m,x1,y1,x2,y2 = map(int,R().split())
    a,b = abs(x1-x2),abs(y1-y2)
    print(n*m-2*abs(x1-x2)*abs(y1-y2)+(2*a-n if 2*a>n else 0)*(2*b-n if 2*b>n else 0))

Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n×m cells and a robotic arm. Each cell of the field is a 1×1 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized — if you move one of the lasers by a vector, another one moves by the same vector.The following facts about the experiment are known:   initially the whole field is covered with a chocolate bar of the size n×m, both lasers are located above the field and are active;  the chocolate melts within one cell of the field at which the laser is pointed;  all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells;  at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman. You are given n, m and the cells (x1,y1) and (x2,y2), where the lasers are initially pointed at (xi is a column number, yi is a row number). Rows are numbered from 1 to m from top to bottom and columns are numbered from 1 to n from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions.

The first line contains one integer number t (1≤t≤10000) — the number of test sets. Each of the following t lines describes one test set. Each line contains integer numbers n, m, x1, y1, x2, y2, separated by a space (2≤n,m≤10^9, 1≤x1,x2≤n, 1≤y1,y2≤m). Cells (x1,y1) and (x2,y2) are distinct.

Each of the t lines of the output should contain the answer to the corresponding input test set.

def main():
    t = int(input())
    for _ in range(t):
        n, m, x1, y1, x2, y2 = map(int, input().split())
        rect_x, rect_y = n - abs(x2 - x1), m - abs(y2 - y1)
        area = n * m - 2 * rect_x * rect_y + max(0, rect_x * 2 - n) * max(0, rect_y * 2 - m)
        print(area)

if __name__ == "__main__":
    main()


import sys
n=int(input())
a=list(map(int,input().split()))
M=10**9+1
g={}
for i in range(n):
    g[a[i]]=g.get(a[i],[])+[i]
p=[1]
for i in range(n):
    p+=[hash(M*p[-1])]
h=[0]*(n+1)
for i in range(n):
    h[i+1]=hash(h[i]*M+a[i])

gh=lambda k,l:hash(h[k+l]-h[k]*p[l])%sys.hash_info.modulus
i,t=0,0

for i in range(n):
    for j in g[a[i]]:
        if j <= i:
            continue
        w=j-i
        if j+w<=n and gh(i,w)==gh(j,w):
            i=j-1
            t=max(t,j)
            break

r=a[t:]
print(len(r))
print(*r)

Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat.You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.

The first input line contains integer n (1≤n≤10^5) — length of the string. The following line contains n space-separated integer numbers from 0 to 10^9 inclusive — numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times.

In the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way.

import sys
n=int(input())
a=list(map(int,input().split()))
M=10**9+1
g={}
for i in range(n):
    g[a[i]]=g.get(a[i],[])+[i]
p=[1]
for i in range(n):
    p+=[hash(M*p[-1])]
h=[0]*(n+1)
for i in range(n):
    h[i+1]=hash(h[i]*M+a[i])

gh=lambda k,l:hash(h[k+l]-h[k]*p[l])%sys.hash_info.modulus
i,t=0,0

while i < n:
    for j in g[a[i]]:
        if j <= i:
            continue
        w=j-i
        if j+w<=n and gh(i,w)==gh(j,w):
            i=j-1
            t=max(t,j)
            break
    i += 1

r=a[t:]
print(len(r))
print(*r)


You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?

The first line of the input contains single integer number n (1≤n≤1000) — amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.

The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.

n = int(input())
segments = []

for _ in range(n):
    l, r = sorted(map(int, input().split()))
    segments.append([l, r])

segments.sort(key = lambda s: s[1])

pinz = []

for l, r in segments:
    if len(pinz) == 0 or l > pinz[-1]:
        pinz.append(r)

print(len(pinz))
print(*pinz)


import random
import sys
import os
import math
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
from itertools import accumulate, combinations, permutations
from heapq import nsmallest, nlargest, heapify, heappop, heappush
from io import BytesIO, IOBase
from copy import deepcopy
import threading
import bisect
BUFSIZE = 4096

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def I():
    return input()

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

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

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

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

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

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

n = II()
if n <= 4: print(n)
elif n % 3 == 0: print(pow(3, n // 3))
elif n % 3 == 1: print(pow(3, (n - 4) // 3) * 4)
else: print(pow(3, (n - 2) // 3) * 2)

Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.

The first input line contains integer number n (1≤n≤700) — amount of vertices in the tree. The following n-1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, ai, bi (1≤ai,bi≤n). It's guaranteed that the graph described in the input is a tree.

Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges.

import sys

N = 1500
ne = [0 for i in range(N)]
he = [0 for i in range(N)]
to = [0 for i in range(N)]
tot = 0
f = [[0 for i in range(N)] for i in range(N)]
sz = [0 for i in range(N)]

def add(u, v):
    global tot
    tot += 1
    ne[tot] = he[u]
    to[tot] = v
    he[u] = tot

def dfs(u, fa):
    t = he[u]
    sz[u] = 1
    f[u][1] = 1
    while t > 0:
        v = to[t]
        if v != fa:
            dfs(v, u)
            i = sz[u]
            while i >= 0:
                j = sz[v]
                while j >= 0:
                    f[u][i + j] = max(f[u][i + j], f[u][i] * f[v][j])
                    j -= 1
                i -= 1
            sz[u] = sz[u] + sz[v]
        t = ne[t]
    for i in range(1, sz[u] + 1):
        f[u][0] = max(f[u][0], f[u][i] * i)

n = int(input())
for i in range(n - 1):
    x, y = list(map(int, input().split()))
    add(x, y)
    add(y, x)
dfs(1, 0)
print(f[1][0])


Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.

The single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105).

Print three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range.  Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.

import sys
import math

def dist(x1, y1, x2, y2):
  return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)

def solve(io):
  R, c_x, c_y, mate_x, mate_y = io.readInt(), io.readInt(), io.readInt(), io.readInt(), io.readInt()
  # is asshole in the room?
  distance = dist(c_x, c_y, mate_x, mate_y)
  if(distance >= R):
    io.print(c_x)
    io.print(" ")
    io.print(c_y)
    io.print(" ")
    io.print(R)
    return
  if(distance == 0):
    c_x = c_x + R/2.0
    R = R/2.0
    io.print(c_x)
    io.print(" ")
    io.print(c_y)
    io.print(" ")
    io.print(R)
    return

  distance = dist(c_x, c_y, mate_x, mate_y)
  remain = distance + R
  new_radius = remain / 2.0

  #slope = (mate_y - c_y) / (mate_x - c_x + 0.0)
  vector = ((c_x - mate_x) / distance * new_radius, (c_y - mate_y) / distance * new_radius)

  center = mate_x + vector[0], mate_y + vector[1]

  io.print(center[0])
  io.print(" ")
  io.print(center[1])
  io.print(" ")
  io.print(new_radius)

# +---------------------+
# | TEMPLATE CODE BELOW |
# |    DO NOT MODIFY    |
# +---------------------+

# TODO: maybe reading byte-by-byte is faster than reading and parsing tokens.
class IO:
  input = None
  output = None
  raw = ""
  buf = []
  pos = 0

  def __init__(self, inputStream, outputStream):
    self.input = inputStream
    self.output = outputStream

  def readToBuffer(self):
    self.raw = self.input.readline().rstrip('\n')
    self.buf = self.raw.split()
    self.pos = 0

  def readString(self):
    while self.pos == len(self.buf):
      self.readToBuffer()
    ans = self.buf[self.pos]
    self.pos += 1
    return ans

  def readInt(self):
    return int(self.readString())

  def readFloat(self):
    return float(self.readString())

  def readStringArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readString())
    return arr

  def readIntArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readInt())
    return arr

  def readFloatArray(self, N, offset = 0):
    arr = [ None ] * offset
    for _ in range(0, N):
      arr.append(self.readFloat())
    return arr

  def readLine(self):
    while self.pos == len(self.buf):
      self.readToBuffer()
    if self.pos > 0:
      raise ValueError("Cannot call readline in the middle of a line.")
    return self.raw

  def print(self, s):
    self.output.write(str(s))

  def println(self, s):
    self.print(s)
    self.print('\n')

  def flushOutput(self):
    self.output.flush()

pythonIO = IO(sys.stdin, sys.stdout)
solve(pythonIO)
pythonIO.flushOutput()


C=lambda c:10-c if c else 0
def s(v,c):
	n=C(c)
	if v[c]*v[n]<1:return 0
	a=v[:];b=v[:];a[c]-=1;b[n]-=1
	x=max(0,(b[0]-a[9]));a[0]-=x;b[0]-=x
	return(x+1+sum(min(v[i],b[9-i])for i in range(10)),x)
a=raw_input()
v=[a.count(`i`)for i in range(10)]
b=d=0
for c in range(6):
	t=s(v,c)
	if t>b:b=t;d=c
if b==0:print a;print a;exit()
z=b[1]
v[0]-=z
n=C(d)
X=`d`;x=v[:];x[d]-=1
Y=`n`;y=v[:];y[n]-=1
for i in range(10):m=min(x[i],y[9-i]);X=`i`*m+X;Y=`9-i`*m+Y;x[i]-=m;y[9-i]-=m;
Z=lambda v:"".join(`i`*n for i,n in enumerate(v))
print Z(x)+X+"0"*z
print Z(y)+Y+"0"*z

Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.Given number n, can you find the two digit permutations that have this property?

The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.

Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.

num = [0] * 10
line = list(raw_input())
for i in line:
  num[ord(i) - ord('0')] += 1
ans = 0
retstr1 = retstr2 = ''.join(sorted(line))
for first_i in range(1, 10):
  first_j = (10 - first_i) % 10
  cntx = [0] * 10
  cnty = [0] * 10
  cntx[first_i] += 1
  cnty[first_j] += 1
  if cntx[first_i] > num[first_i] or cnty[first_j] > num[first_j]:
    continue
  tmpstr1 = chr(ord('0') + first_i)
  tmpstr2 = chr(ord('0') + first_j)
  tmp = 1
  for i in range(10):
    l = min(num[i] - cntx[i], num[9-i] - cnty[9-i])
    cntx[i] += l
    cnty[9-i] += l
    tmp += l
    tmpstr1 += chr(ord('0') + i) * l
    tmpstr2 += chr(ord('0') + 9 - i) * l
  l = min(num[0] - cntx[0], num[0] - cnty[0])
  cntx[0] += l
  cnty[0] += l
  tmp += l
  tmpstr1 = chr(ord('0')) * l + tmpstr1
  tmpstr2 = chr(ord('0')) * l + tmpstr2
  for i in range(10):
    tmpstr1 += chr(ord('0') + i) * (num[i] - cntx[i])
    tmpstr2 += chr(ord('0') + i) * (num[i] - cnty[i])
  if ans < tmp:
    ans = tmp
    retstr1 = tmpstr1
    retstr2 = tmpstr2
print retstr1[::-1]
print retstr2[::-1]


x = 0
p = [x := x + i ** 2 for i in range(1, 2000001)]

def f(a, b):
    return a * a * b - ((a * (a - 1)) // 2) * (a + b) + (p[a - 2] if a >= 2 else 0)

def ff(a, x):
    C = 0 if a < 2 else p[a - 2]
    nom = 2 * x - 2 * C - a * a * a + a * a
    denom = 3 * a * a - a
    if nom % denom == 0:
        return nom // denom
    return -1

def binary_search(a, x):
    l = a
    r = x + 1
    while l < r:
        mid = (l + r) // 2
        v = f(a, mid)
        if v < x:
            l = mid + 1
        elif v > x:
            r = mid
        else:
            return mid
    return l

def __main__():
    x = int(input())
    res = []

    for a in range(1, 2000000):
        b = ff(a, x)
        if b != -1:
            res.append((a, b))

    if res[-1][0] == res[-1][1]:
        print(2 * len(res) - 1)
    else:
        print(2 * len(res))

    for r in res:
        print(r[0], r[1])

    for r in reversed(res):
        if r[0] != r[1]:
            print(r[1], r[0])

    return

__main__()

Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3×5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3×5 table is 15+8+3=26.

The first line of the input contains a single integer x (1≤x≤10^18) — the number of squares inside the tables Spongebob is interested in.

First print a single integer k — the number of tables with exactly x distinct squares inside.
Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality — in the order of increasing m.

In a 1×2 table there are 2 1×1 squares. So, 2 distinct squares in total.

In a 2×3 table there are 6 1×1 squares and 2 2×2 squares. That is equal to 8 squares in total.


n, m, k = [int(x) for x in input().split()]
canwin = False
for i in range(k):
  x, y = [int(x) for x in input().split()]
  canwin |= x < 8 or n - x < 7
  canwin |= y < 8 or m - y < 7
print("YES" if canwin else "NO")

Volodya and Vlad play the following game. There are k pies at the cells of n  ×  m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.

First line contains 3 integers, separated by space: 1 ≤ n, m ≤ 100 — dimensions of the board and 0 ≤ k ≤ 100 — the number of pies. Each of the next k lines contains 2 integers, separated by space: 1 ≤ x ≤ n, 1 ≤ y ≤ m — coordinates of the corresponding pie. There could be more than one pie at a cell.

Output only one word: "YES" — if Volodya wins, "NO" — otherwise.

n, m, k = map(int, input().split())
win = False
for i in range(k):
    x, y = map(int, input().split())
    if abs(x - 1) <= 4 or abs(y - 1) <= 4 or \
            abs(n - x) <= 4 or abs(m - y) <= 4:
        win = True

print('YES' if win else 'NO')


SUSPICIOUS = -128
NIL = 0
ADD = 1
SUB = 2
MUL = 4
DIV = 8
ALL = 15

op_value = {'+': ADD, '-': SUB, '*': MUL, '/': DIV}
invalid = {NIL: (NIL,        NIL),
           ADD: (NIL,        NIL),
           SUB: (NIL,        ADD | SUB),
           MUL: (ADD | SUB,  ADD | SUB),
           DIV: (ADD | SUB,  ALL)}

def validate(expr):
    global definitions

    ## Initialize validation variables
    last_op = 0
    operators = 0
    last_token = 0

    ## Initialize parsing variables
    token = ""
    paren_depth = 0

    ## Iterate the expression
    for c in expr:

        ## Handle sub-expressions
        if c == '(':
            paren_depth += 1

        elif c == ')':
            paren_depth -= 1

            ## No validation necessary
            ## (besides non-suspiciousness)
            if paren_depth == 0:
                if validate(token) == SUSPICIOUS:
                    return SUSPICIOUS

                token = ""

        ## Perform validation
        elif paren_depth == 0 and c in '*/+-':
            ## Validate last_op + last_token
            if token != "":
                last_token = definitions.get(token, 0)
                #print 1, last_token, last_op, invalid[last_op][1]
                if last_token == SUSPICIOUS or last_token & invalid[last_op][1]:
                    #print bin(SUSPICIOUS)[2:]
                    return SUSPICIOUS

                token = ""

            ## Update validation variables
            last_op = op_value[c]
            operators |= last_op

            ## Validate last_token + last_op
            #print 2, last_token, last_op, invalid[last_op][0]
            if last_token & invalid[last_op][0]:
                #print bin(SUSPICIOUS)[2:]
                return SUSPICIOUS

        else:
            token += c

    if token != "":
        last_token = definitions.get(token, 0)
        #print 1, last_token, last_op, invalid[last_op][1]
        if last_token == SUSPICIOUS or last_token & invalid[last_op][1]:
            #print bin(SUSPICIOUS)[2:]
            return SUSPICIOUS

    return operators

definitions = {}

n = input()

for i in range(n):
    line = raw_input().split()

    if line[0] == '#':
        head = line[2]
        line = line[3:]
    else:
        head = line[1]
        line = line[2:]

    definitions[head] = validate("".join(line))

    #print head, bin(definitions[head])[2:]

expr = validate("".join(raw_input().split()))
print "Suspicious"    if expr == SUSPICIOUS else    "OK"

Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".

The first line contains the only number n (0≤n≤100) — the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
  name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 10^9. All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.

Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".

4
#define sum  x + y
#define mul  a * b
#define div  a / b
#define expr sum + mul * div * mul
expr

3
#define SumSafe   (a+b)
#define DivUnsafe  a/b
#define DenominatorUnsafe  a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)

class Macro:
    def __init__(self, level):
        self.level = level

    def __add__(self, other):
        return Macro('+0'[self.level == '0' or other.level == '0'])

    def __sub__(self, other):
        return Macro('+0'[self.level == '0' or other.level in '0+'])

    def __mul__(self, other):
        return Macro('*0'[self.level in '0+' or other.level in '0+'])

    def __truediv__(self, other):
        return Macro('*0'[self.level in '0+' or other.level in '0+*'])

def create_macro(c):
    return 'Macro("' + c + '")'

def evaluate_expression(expression, variables):
    stack, current_token = [''], ''
    for char in ''.join(expression):
        if char in '+-*/()':
            if current_token != '':
                stack[-1] += create_macro(variables.get(current_token, '1'))
                current_token = ''
            if char == '(':
                stack.append('')
            elif char == ')':
                macro = create_macro('10'[eval(stack.pop()).level == '0'])
                stack[-1] += macro
            else:
                stack[-1] += char
        else:
            current_token += char
    if current_token != '':
        stack[0] += create_macro(variables.get(current_token, '1'))
    return eval(stack[0]).level

variables = {}
for _ in range(int(input())):
    line = input().split()
    if line[0] == '#':
        line.pop(0)
    variables[line[1]] = evaluate_expression(line[2:], variables)

result = evaluate_expression(input().split(), variables)
print('Suspicious' if result == '0' else 'OK')

[{'input': ['1\r\n#define sum x + y\r\n1 * sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum  (x + y)\r\nsum - sum\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define sum  x + y\r\n#define mul  a * b\r\n#define div  a / b\r\n#define expr sum + mul * div * mul\r\nexpr\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define SumSafe   (a+b)\r\n#define DivUnsafe  a/b\r\n#define DenominatorUnsafe  a*b\r\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['0\r\naa + b - c * (ddd * eee / fff * a / b * c + d - b + c - (a + b)) - d\r\n'], 'output': ['OK\r\n']}, {'input': ['2\r\n#define a b\r\n#define c d\r\na + b + c + d + 1234567 -10*(2-2+1000*1000*1000*1000*1000)\r\n'], 'output': ['OK\r\n']}, {'input': ['2\r\n  #  define  macros    (  x  +  y  ) \r\n # define  Macros (x+y)\r\nmacros/Macros\r\n'], 'output': ['OK\r\n']}, {'input': ['2\r\n#define A v\r\n#define a v/v/v\r\nv/A\r\n'], 'output': ['OK\r\n']}, {'input': ['2\r\n#define A v\r\n#define a v/v/v\r\nv/a\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['2\r\n#define A v\r\n#define a v/v/v\r\nv/(a)\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define a x*y\r\nc/a\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define a b*c\r\na/a*a\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['3\r\n#define mul  x*y\r\n#define bad  x/mul\r\n#define good x/(mul)\r\ngood\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define mult   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum+difference+(sum)*(difference)-mult+mult*division+division*mult+division/(mult+sum-(difference))\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference/division)+sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference)*sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(sum)/multiplication\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum/(multiplication)\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['5\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n#define res (0-difference)\r\nsum+res*multiplication\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\ndivision/(multiplication/(division)/DIVISION/(sum-division-multiplication-(difference)))\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define sum  x + y\r\n#define SomeBad  (2 * sum)\r\n#define SomePossiblyGood  0 * SomeBad + (x + x - 2*x) * SomeBad\r\nSomePossiblyGood\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['2\r\n#define a  0\r\n#define b  (a-a)*(x/x-1)\r\nb-b/b*b\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['2\r\n#define fkdsjfslkjfsdk x/0\r\n#define fkdsjfslkjfsdksdds 0/(0-0)\r\nfkdsjfslkjfsdk + fkdsjfslkjfsdks + fkdsjfslkjfsdkssds\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define null x/0\r\n#define some x/x\r\n#define bad 1/x\r\nbad/0+0/bad+0/0*bad\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['3\r\n#define MWjGY x+x*53 *x\r\n#define ovqZ 2/926+x/A\r\n#define uU 55-qRj*A*2\r\nx*A/x-A\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define zz 5+7/x*x*9\r\n#define mlTL 6+x/7+x/x\r\n#define DUO 7*7-x+zz\r\n#define IH 6*4-x+x\r\n67/(5)-IH\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['5\r\n#define Oc 9/51+65+vN\r\n#define gga 53/ 94/x/x\r\n#define ArB x/x/9-77-8\r\n#define j 76-6/93+vN\r\n#define cALNN Oc+60499\r\n8*6-66/x*x\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define fSdvwOj (W)*W+73\r\n#define NAZjc 7695*55-x\r\n#define AHGGglVwch (6-a-W)\r\n((5))+W+W\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define m bJJD +x \r\n#define yYkQNzjR (x*19)-892\r\n#define MNvfxqfbq (x-6*x/8)\r\n#define nJZdvO 8/4 *m/m\r\n 9+m/x+x\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['5\r\n#define Sl x*7-(x)/O\r\n#define srAOHccTln 3+x*2*O\r\n#define OFAZk 239751817\r\n#define JYWrOEgazV (x-O/4)-x\r\n#define XsOZvalgOh 89905879/7\r\nx/Sl-(Sl)\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['3\r\n#define uYdw ((9-x-3) )\r\n#define fy (((x+21)))\r\n#define nY ((2+x)-46)\r\n141141432\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define GCvqH (58 )-(x)\r\n#define g ((x/x+x))\r\n#define spst hQTJ\r\n#define i GCvqH\r\n(((x+6)))\r\n'], 'output': ['OK\r\n']}, {'input': ['5\r\n#define rg (67)+((x))\r\n#define ya x-(6/x)*rg\r\n#define anTxe 10*ya*(x)\r\n#define xcmo ((x)*(vT))\r\n#define eg ((vT)) -ya\r\n((x*(Ii)))\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define T ((b/1 +1))\r\n#define pm (s)-43-(s)\r\n#define jkNBpvDZl ((x ))/65\r\n(((58*7)))\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define cJitUt 21/(4)+4+4\r\n#define zHwBOLIvF 4*((41/x))\r\n#define GbtYVo (E)+(x+3)\r\n#define zTcZBaby (58)+x-x+x\r\n(E+E)/8 *4\r\n'], 'output': ['OK\r\n']}, {'input': ['5\r\n#define mBURKdeKvy 266693986\r\n#define nWi ( ((x))-4)\r\n#define iYreeOt ((7/x+42))\r\n#define laLzP ((aB/35)) \r\n#define dXjRJ (((B*hX)))\r\n(1*2+(67))\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define UVMQLGvEqOxaAgRkvJH tBd\r\n#define QoAsBMaUcJzXai x/x-hm/83+8*8/5/hm /x/hm\r\n#define QtxtzEHCmidm 75 +491928441\r\n((x)/VUpYoEdDUtLFanGyqfQR  )\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define efemx 2/1*3*69+81+10/690445104\r\n#define AyjrEzAjMKZpRPfCOaO 21*9+( j*40+3*4)*ND+w-j*j+x*55\r\n#define YkJkHcNhXcci 85*3215/40/365819568\r\n#define MUzvOZSXJujI 9-4/j*j-7-w*23*5+j+9-9*ND*2/37\r\nND/j*28 -1* ND+22889023/j/j/j\r\n'], 'output': ['OK\r\n']}, {'input': ['5\r\n#define QNUkjqPcGWF 6*4/908975666-7/10-x*7\r\n#define xqwhNWiiMaZOcmgiXYY 3936*(e*5*H+2)-TsA+(e)/1-25\r\n#define tRsSqfqJt ((uT*82/e)+e/(23+(45)-9)+(50))\r\n#define DtIOWRkYe (8*3/9)*e*x *60041512*2-(e)\r\n#define qgPgxja (4/x+e/uT*16358009- 6/13*5)\r\ne+x*e/84/x+uT*H\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define lTCUUO JQmj\r\n#define oUeQMB (12*x+x+x)-75-(79/1)-(7)*1/mr\r\n#define LAQu xwvBtky\r\n8654 *1*5-mr-3*J/oUeQMB/x/6/9\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define VLuQIO 1-x/33+ Fk+wS/35-wS-(x*iz )\r\n#define BCIsIR 5*(wS)/x/iz/1+x-x-4-x/68/x/8*x\r\n#define QPUpmTiB 21-x/895912506+2\r\n#define wcZLUIqJS 7/65-x*61-(24+iz)+x+315670+x/x\r\nBCIsIR/VLuQIO\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['5\r\n#define FDmMYOENCOKmYwYlOl 6-(L)/((((ud/x))/ud-26*8-5))\r\n#define QkopKBjKdJxhc (6)*4/7-L/781844832  \r\n#define UjgTieUBXTSTbiLFAhkV 3*1*(52)/6-6*65/x+((L-56))+x+x\r\n#define yWVYDuqliezpKLwnI 8/4+1+88+97946+(1)-((68))-L/L\r\n#define AvvED 719901121+95/2/78/1-10+37\r\n(1*x+ 528176190+17/ud)\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define e x *R/5+(x)+4/18/x*R/x-8+1+R\r\n#define GgGqGYjXoJjIezAVu (( 491563947*R))*9-e-3/4\r\n#define XgznGUWMxQwh (8/R+4*(e)+10/4*x+24*R+21)-224\r\n (82493582)\r\n'], 'output': ['OK\r\n']}, {'input': ['4\r\n#define MrKSTrKhPLeJqOcEPvv (x+x/x)/Qdf-x-x-(2/23)+9442-x\r\n#define zPHUgmIYE 10- 7*x/x+VwRUuIRezDR*80\r\n#define OsfThxasHeFZCEZTfD 271456028-(x*x)-8+2*x*x*x+(x)\r\n#define zVYasB x/x -x-(51)-x*x*((x))  /x \r\n(x/64-x*( (5+x+x)-(37)/3*22))\r\n'], 'output': ['OK\r\n']}, {'input': ['5\r\n#define WREol (fcdGZaLzhiFpVQmhHO)\r\n#define lDTNxcMqPPP 3+(57)/x/91540-x*71-x*6-((1))\r\n#define afFJVBkr ((12*x-8+9 *lDlx+7+lDlx))\r\n#define mYEizEWrNtRSQNCcDQrn 732480960+9+x-78-x/1+12*x\r\n#define IZTmjheAahbNSNFa ((x-x*7+407643063 ))\r\nXQvMxLNpQnhpimNhAkfX\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define Mc x+x*55231- x/x/x+35/x*(5*(x)) -5*x*(1-2-(29/1))\r\n#define afSVLCdjvylSu bgqv/6+4*x*((Mc/1318/x-8-4)-Mc/Mc/(9))\r\n#define ZOSV (1+2/x+6* 174806683)-x/x*Mc+52*x-x\r\nbgqv-x-6*x/72/(x )/afSVLCdjvylSu\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define RJIiiGQqn dmpWFcrqQeM+V-o* 55/9*o-o/V*V*o\r\n#define ElDZlrtzDkeKgsX 498718105* 3/(y)/(4)-(5*x)*1\r\n#define qwKl jHqPHX\r\n#define qXzAZkCuchBYR  (qy*qwKl-6+5*1+2)-7-3+(38)-o*4/4-1-V*x/6+1*x/o\r\no*((V))-o+2+((((2*V)/V-o*V/4)))/o*33+y/7  -x+x \r\n'], 'output': ['OK\r\n']}, {'input': ['5\r\n#define WTovyGexUNjGMRJv (MQG*18-6)/x/x*x/x-x*akNyw*x+x-x/2/x*20\r\n#define hpextyhVCa 70*x/67-x*87931-(497612505-7*x-MQG)-x\r\n#define MRkKnCXFt x-5-21962-x/sOmThNSS/x/6-4+(65+57+x+x+7-7+x/x)\r\n#define ajsczBLLklBSqqh nGj-38*9 *x/47/8*5/5-72/x*x-x*x*31  /7-44-3+64\r\n#define jgqfv WTovyGexUNjGMRJv\r\n  4+338/x*x+13 -795*3-74*2/4+563-x/76401438/83025\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define G u+13-35348/2-(u/u)-u/u*u*(OC)-OC -u-u/u*u/9 \r\n#define RNRQ G*G*u+G/755750/G/G +((u-6*G+6)*2)- 5*96+5/u*275-u\r\n#define Zg 94363/u*u-41+Gm*G-81/5-1-G*G*x-(5517*5/4)*21 +75\r\n406690013/WM*G+(u+u)*Zg+2\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define RMWAZhIp x*x+12+94*12*5*1-x-141915293\r\n#define EeguG 9-55+x/29+x+x/E*8*81/x-x*75-4*17-81/x/6+619978*x*x\r\n#define HvUYEvQTyYmBGvqHSb 454574730/644135926*x/23+E-sy/14\r\n#define BqMGcT x/(43)+819897061-x*(7/x)-(x)+sy-E-x*79-E+(x)/6/63\r\n76+3/x/8*x+E-76+sy-sy+9*6/66/sy-77+x-x*sy+E/50/64\r\n'], 'output': ['OK\r\n']}, {'input': ['5\r\n#define cbt ((((d))+9-3+ (d)/d/6*SDDNqj*50/d+d-m+8/d/1)) \r\n#define gLrUE 18+ 70*d/3-d*d-d/35 +33-5/9+d-d*387+d-1\r\n#define AvjmK 9-d-8+(d+m+5/2/x*d+1)/x/d-5-2*(m)+d+17/d+ 4/52/8\r\n#define SjrJ 90/7/5/d+ 254877982+(m) *x-19\r\n#define PlykoqfDbwxR  540304590 +d*x/11-(m+d-d-4)*(d-3-1)/d\r\nd-2+1+46-29620+9-(9*3 /d)*6*m/d+9+(1670)/cbt/d+d\r\n'], 'output': ['OK\r\n']}, {'input': ['3\r\n#define BuAiJLgAlkj x-3+419032556/409023036-(17*84)+x+8+A\r\n#define wU 516506880\r\n#define HeyDGlnaGxBaHjzelvF iRSPqHfgHw/4-(99)*(I)+A+I-9*46*x\r\nI/CRklg-HeyDGlnaGxBaHjzelvF/3+5 \r\n'], 'output': ['Suspicious\r\n']}, {'input': ['4\r\n#define SOlTohcPGckDyF ((D)/G-83+KHGSuJFLHqD/5)\r\n#define KEUXeOYpg 9+x-8-8/x/9-65-6+4+55*x-58/x+84+D*2-7+D/x-x*G/4-2\r\n#define YZl (1/67*x*6/2*G)-D/1595107*D+6/x*1+D+3/9/x/26-6+9 \r\n#define gCatFsZn uBBqilYclMhpVfKKTkGK\r\n(28682537+ YZl*(4*52)  )*x/8- gCatFsZn*x/54/7\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['5\r\n#define iiXEqDYeyVmIYsOaO fj/x-9-6/x*x+ 1/ 7*2-x -x+9+235*23*Ww+x-2*K+2-x/70\r\n#define XVgLzhoTUxoBr ( x+x/x/x*6-x)* x+K/24206-2 /5/8-x-7/Ww/K-x+6 \r\n#define QdfRBaJk 470551685-(  54-x)-30\r\n#define gEJcAGnF x+x-x+(x/x+9)/x-41-1/fj/1157561+x/x -x/26/x+K*x\r\n#define lO 7-1*(x*58 )-K*fj  /722113691/x/K+2\r\n2+4*85/86/x*27 /49252-x*x/6-83-7/x+x+K-lO+8-K-x\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x+y\r\nr-sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x+y\r\nr+sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x+y\r\nr*sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x+y\r\nr/sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x-y\r\nr+sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x-y\r\nr-sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x-y\r\nr*sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x-y\r\nr/sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x*y\r\nr+sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x*y\r\nr-sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x*y\r\nr*sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x*y\r\nr/sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x/y\r\nr+sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nr-sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nr*sum\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nr/sum\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x+y\r\nsum+r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x+y\r\nsum-r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x+y\r\nsum*r\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x+y\r\nsum/r\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x-y\r\nsum+r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x-y\r\nsum-r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x-y\r\nsum*r\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x-y\r\nsum/r\r\n'], 'output': ['Suspicious\r\n']}, {'input': ['1\r\n#define sum x*y\r\nsum+r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x*y\r\nsum-r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x*y\r\nsum*r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x*y\r\nsum/r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nsum+r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nsum-r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nsum*r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define sum x/y\r\nsum/r\r\n'], 'output': ['OK\r\n']}, {'input': ['1\r\n#define x 3/2\r\n2*x\r\n'], 'output': ['OK\r\n']}, {'input': ['2\r\n   #    define     sum     1000000000   +   1000000000       +     1000000000      \r\n    #    define      a    b     +      45    *   sum    \r\n       a       \r\n'], 'output': ['Suspicious\r\n']}]


#!/usr/bin/python
# -*- coding: utf-8 -*-

from itertools import combinations

n = int(raw_input(''))
a,b = [int(x) for x in (raw_input('')).split(' ')]
s = [int(x) for x in (raw_input('')).split(' ')]

maxs = 0.0
res = None
maxst = ''

for c in combinations( xrange(0,n), a ):
    f = [ 0 for x in xrange(0,n) ]
    for t in c:
        f[t] = 1

    sum1 = 0
    sum2 = 0
    for i in xrange(0,n):
        if f[i] == 1:
            sum1 += s[i]
        else:
            sum2 += s[i]

    ss = float(sum1)/float(a) + float(sum2)/float(b)
    st = ''.join( [ str(2-x) for x in f ] )

    if ss == maxs:
        if st < maxst:
            maxst = st
            res = f[:]
    elif ss-1e-8 > maxs:
        maxs = ss
        maxst = st
        res = f[:]

        maxs = ss
r = ''
i = 0
while i < len(res):
    if r != '':
        r += ' '
    r += str(2-res[i])
    i += 1

print r

After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark.Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received a Safety Studies marks and b PE marks (a + b = n). Now Polycarp wants to write a subject's name in front of each mark so that:   there are exactly a Safety Studies marks,  there are exactly b PE marks,  the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the x1 + x2, where x1 is the average score in the first subject (Safety Studies), and x2 is the average score in the second one (Physical Education).

The first line contains an integer n (2 ≤ n ≤ 105), n is the number of marks in Polycarp's Journal. The second line contains two positive integers a, b (1 ≤ a, b ≤ n - 1, a + b = n). The third line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 5), they are Polycarp's marks.

Print the sequence of integers f1, f2, ..., fn, where fi (1 ≤ fi ≤ 2) is the number of a subject to which the i-th mark should be attributed. If there are several possible solutions, then print such that the sequence f1, f2, ..., fn is the smallest lexicographically. The sequence p1, p2, ..., pn is lexicographically less than q1, q2, ..., qn if there exists such j (1 ≤ j ≤ n) that pi = qi for all 1 ≤ i < j, аnd pj < qj.

NoteIn the first sample the average score in the first subject is equal to 4, and in the second one — to 4.5. The total average score is 8.5.

f=lambda:map(int,raw_input().split())
n,(a,b),t=f(),f(),f()
s=[sorted(t,reverse=a<b),t][a==b][:a]
c=[[1]*s.count(i)for i in range(6)]
for x in t:print c[x]and(c[x].pop())or 2,


import heapq
e=raw_input()
c=0
k=0
l=[0]*len(e)
heap=[]
for i in xrange(len(e)):
    if e[i]=="(":
        l[i]="("
        k+=1
    elif e[i]==")":
        l[i]=")"
        k-=1

    else:
        a,b=map(int,raw_input().split())
        c+=b
        heapq.heappush(heap,(a-b,i))
        l[i]=")"
        k-=1

    if k<0 and heap:
          v,ind=heapq.heappop(heap)
          c+=v
          l[ind]="("
          k+=2
if k!=0:
  print -1

else:

 print c
 print "".join(l)

This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.

from heapq import heappush, heappop
from sys import stdin, exit

template = list(next(stdin).strip())

n, cost, balance = len(template), 0, 0

min_heap = []

for i in range(n):
	if template[i] == '(':
		balance += 1
	elif template[i] == ')':
		balance -= 1
	else:
		cost_left, cost_right = map(int, next(stdin).split())
		template[i] = ')'
		cost += cost_right
		balance -= 1
		heappush(min_heap, (cost_left - cost_right, i))
	if balance < 0:
		if not min_heap:
			print(-1)
			exit(0)
		change_cost, index = heappop(min_heap)
		template[index] = '('
		cost += change_cost
		balance += 2

if balance == 0:
	print(cost)
	print(''.join(template))
else:
	print(-1)


P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [[] for _ in range(M+1)]

X[0] = [1]
def calc(L):
    su = sum(L)
    pl = 0
    pd = 0
    RE = []
    for i in range(len(L)):
        a = li + i
        b = di - (len(L) - 1 - i)
        pd = b * L[i] * pow(su*(a+b), P-2, P)
        RE.append((pl+pd)%P)
        pl = a * L[i] * pow(su*(a+b), P-2, P)
    RE.append(pl%P)
    return RE

for i in range(M):
    X[i+1] = calc(X[i])
ne = 0
po = 0
for i in range(M+1):
    po = (po + X[M][i] * (li + i)) % P
    ne = (ne + X[M][i] * (di + i)) % P
for i in range(N):
    print(po * B[i] * pow(li, P-2, P) % P if A[i] else ne * B[i] * pow(di, P-2, P) % P)

The only difference between easy and hard versions is constraints.Nauuo is a girl who loves random picture websites.One day she made a random picture website by herself which includes $$$n$$$ pictures.When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $$$i$$$-th picture has a non-negative weight $$$w_i$$$, and the probability of the $$$i$$$-th picture being displayed is $$$\frac{w_i}{\sum_{j=1}^nw_j}$$$. That is to say, the probability of a picture to be displayed is proportional to its weight.However, Nauuo discovered that some pictures she does not like were displayed too often. To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $$$1$$$ to its weight; otherwise, she would subtract $$$1$$$ from its weight.Nauuo will visit the website $$$m$$$ times. She wants to know the expected weight of each picture after all the $$$m$$$ visits modulo $$$998244353$$$. Can you help her?The expected weight of the $$$i$$$-th picture can be denoted by $$$\frac {q_i} {p_i}$$$ where $$$\gcd(p_i,q_i)=1$$$, you need to print an integer $$$r_i$$$ satisfying $$$0\le r_i<998244353$$$ and $$$r_i\cdot p_i\equiv q_i\pmod{998244353}$$$. It can be proved that such $$$r_i$$$ exists and is unique.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 2\cdot 10^5$$$, $$$1\le m\le 3000$$$) — the number of pictures and the number of visits to the website. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$a_i$$$ is either $$$0$$$ or $$$1$$$) — if $$$a_i=0$$$ , Nauuo does not like the $$$i$$$-th picture; otherwise Nauuo likes the $$$i$$$-th picture. It is guaranteed that there is at least one picture which Nauuo likes. The third line contains $$$n$$$ positive integers $$$w_1,w_2,\ldots,w_n$$$ ($$$w_i \geq 1$$$) — the initial weights of the pictures. It is guaranteed that the sum of all the initial weights does not exceed $$$998244352-m$$$.

The output contains $$$n$$$ integers $$$r_1,r_2,\ldots,r_n$$$ — the expected weights modulo $$$998244353$$$.

NoteIn the first example, if the only visit shows the first picture with a probability of $$$\frac 2 3$$$, the final weights are $$$(1,1)$$$; if the only visit shows the second picture with a probability of $$$\frac1 3$$$, the final weights are $$$(2,2)$$$.So, both expected weights are $$$\frac2 3\cdot 1+\frac 1 3\cdot 2=\frac4 3$$$ .Because $$$332748119\cdot 3\equiv 4\pmod{998244353}$$$, you need to print $$$332748119$$$ instead of $$$\frac4 3$$$ or $$$1.3333333333$$$.In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, $$$w_1$$$ will be increased by $$$1$$$.So, the expected weight is $$$1+2=3$$$.Nauuo is very naughty so she didn't give you any hint of the third example.

P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
    PO[i] = pow((SU+i)%P, P-2, P)

def calc(L):
    su = sum(L)
    pl = 0
    pd = 0
    RE = []
    for i in range(len(L)):
        a = li + i
        b = di - (len(L) - 1 - i)
        pd = b * L[i] * PO[a+b-SU]
        RE.append((pl+pd)%P)
        pl = a * L[i] * PO[a+b-SU]
    RE.append(pl%P)
    return RE

for i in range(M):
    X = calc(X)
ne = 0
po = 0
for i in range(M+1):
    po = (po + X[i] * (li + i)) % P
    ne = (ne + X[i] * (di - M + i)) % P
invli = pow(li, P-2, P)
invdi = pow(di, P-2, P)
for i in range(N):
    print(po * B[i] * invli % P if A[i] else ne * B[i] * invdi % P)


#from collections import deque
n,k=[int(i) for i in input().split()]
books=[int(i) for i in input().split()]
res=[]
M=1
Mcnt=0
for l in range(n) :
    if n-l<M :
        break
    maxt=max(books[l:l+M])
    mint=min(books[l:l+M])
    for r in range(l+M-1,n) :
        maxp=maxt
        minp=mint
        maxt=books[r] if books[r]>maxt else maxt
        mint=books[r] if books[r]<mint else mint
        if (maxt-mint>k):
            if not(maxp-minp<=k) :
                break
            res.append([l+1,r])
            if r-l>M :
                M=r-l
                Mcnt=1
            elif r-l==M :
                Mcnt+=1
            break
print(M,Mcnt)
for i in range(Mcnt) :
    print(res[-Mcnt+i][0],res[-Mcnt+i][1])

There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

from bisect import *
n,k=map(int,input().split())
h=list(map(int,input().split()))
l=[]
q=[]
aa=-1
j=0
for i in range(n):
    l.insert(bisect(l,h[i]),h[i])
    while l[-1]-l[0]>k:
        l.pop(bisect(l,h[j])-1)
        j+=1
    if i-j+1>aa:
        aa=i-j+1
        q=[]
    if i-j+1==aa:
        q.append([j+1,i+1])
print(aa,len(q))
for i in q:
    print(i[0],i[1])


n = int(input())

l = []
for i in range(n):
    l.append(int(input()))

def repair(x, y, r):
    if(r == 0):
        return x

    z = (x % (10 * r)) // r - (y % (10 * r)) // r

    if(z == 0):
        return repair(x, y, r // 10)

    if(x % r >= y % r):
        return x - z * r
    else:
        return x - z * r + r

y = 1000
try:
    for i in range(n):
        l[i] = repair(l[i], y, 1000)
        if(l[i] > 2011):
            raise Exception()
        y = l[i]

    for i in l:
        print(i)
except:
    print("No solution")

The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.

The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999).

Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).

import sys

n = int(input())
d = []
for i in range(n):
    d.append(input())
ans = []

bad = 'No solution'
low = 1000
for date in d:
    lowest = 100500
    for i in range(10):
        for j in range(i == 0, 5):
            changed = date[:j] + str(i) + date[j + 1:]
            if lowest > int(changed) >= low:
                lowest = int(changed)
    if lowest > 2011:
        print(bad)
        sys.exit(0)
    ans.append(str(lowest))
    low = lowest

print('\n'.join(ans))


SUSPICIOUS = -128
NIL = 0
ADD = 1
SUB = 2
MUL = 4
DIV = 8
ALL = 15

op_value = {'+': ADD, '-': SUB, '*': MUL, '/': DIV}
invalid = {NIL: (NIL,        NIL),
           ADD: (NIL,        NIL),
           SUB: (NIL,        ADD | SUB),
           MUL: (ADD | SUB,  ADD | SUB),
           DIV: (ADD | SUB,  ALL)}

def validate(expr):
    global definitions

    ## Initialize validation variables
    last_op = 0
    operators = 0
    last_token = 0

    ## Initialize parsing variables
    token = ""
    paren_depth = 0

    ## Iterate the expression
    for c in expr:

        ## Handle sub-expressions
        if c == '(':
            #if paren_depth > 0:
            token += c
            paren_depth += 1

        elif c == ')':
            paren_depth -= 1

            ## No validation necessary
            ## (besides non-suspiciousness)
            if paren_depth == 0:
                if validate(token) == SUSPICIOUS:
                    return SUSPICIOUS

                token = ""
                last_op = 0
                last_token = 0

            else:
                token += c

        ## Perform validation
        elif paren_depth == 0 and c in '*/+-':
            ## Validate last_op + last_token
            if token != "":
                last_token = definitions.get(token, 0)
                if last_token == SUSPICIOUS or last_token & invalid[last_op][1]:
                    return SUSPICIOUS

                token = ""

                ## Validate last_token + last_op
                if last_token & invalid[op_value[c]][0]:
                    return SUSPICIOUS

                last_token = 0

            ## Update validation variables
            last_op = op_value[c]
            operators |= last_op

        else:
            token += c

    if token != "":
        last_token = definitions.get(token, 0)
        if last_token == SUSPICIOUS or last_token & invalid[last_op][1]:
            return SUSPICIOUS

    return operators

definitions = {}

n = input()

for i in range(n):
    line = raw_input().split()

    if line[0] == '#':
        head = line[2]
        line = line[3:]
    else:
        head = line[1]
        line = line[2:]

    definitions[head] = validate("".join(line))

    #print head, bin(definitions[head])[2:]

expr = validate("".join(raw_input().split()))
print "Suspicious"    if expr == SUSPICIOUS else    "OK"

The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where   name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.  All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol. The length of any line from the input file does not exceed 100 characters.

#!/usr/bin/env python

"""
CodeForces: 7E. Defining Macros

The key for the solution is the naked operators that are not surrounded by
the parentheses in the macro definition.

Suspicious patterns of the operators in the appearance order are:

    o{-}   n{+-}
    o{*}   n{+-}
    o{/}   n{+-*/}
    n{+-}  o{*}
    n{+-}  o{/}

where:
    "o{}": an operator before or after the macro might construct
        a suspicious expression with the operators in "n{}"
    "n{}": a subset of the naked operators in the macro definition
        that might construct a suspicious expression with the operator "o"

If the pair of operators in the "o{}" and "n{}" are matched
in the expression, the entire expression would be suspicious.
"""

# Represent the operator as the bit mask:
# Pseudo operator whose priority is lower than "+",
# Add (+), Subtract (-), Multiply (*) and Division (/)
P, A, S, M, D = 1, 2, 4, 8, 16
ADD = A | S
ANY = A | S | M | D
# Map of the operators (+-*/) to the bit mask
OP_BIT = {"+": A, "-": S, "*": M, "/": D, ")": 0}
# unsafe naked operators against the operator before and after the macro
UNSAFE_BEFORE = {P: 0, A: 0, S: ADD, M: ADD, D: ANY}
UNSAFE_AFTER = {P: 0, A: 0, S: 0, M: ADD, D: ADD}

# Macro definitions:
# a map from the macro name to the set of its naked operators
# Note: the set is represented as a bit pattern
macro = dict()

# Parse expression with checking suspicious expression
def expr(chars,
         # following arguments are the short cut
         pseudo=P,
         expand=macro.get,
         op_bit=OP_BIT,
         unsafe_before=UNSAFE_BEFORE,
         unsafe_after=UNSAFE_AFTER):
    # stack of the operator before the left parenthesis "("
    paren = []
    push = paren.append
    pop = paren.pop
    # list of characters that would be a macro name or a number
    name = []
    keep = name.append
    forget = name.clear

    # last_op: last operator before the macro name or the number
    # retval: set of the naked operators of this expression
    # naked: set of the naked operators of the macro expanded
    last_op = retval = naked = pseudo

    # expand the macro and check the preceding operator
    def safe():
        nonlocal naked
        naked = expand("".join(name), pseudo)
        forget()
        # early exit for a suspicious expression and a value
        if naked <= pseudo:
            return naked
        # safety check against the operator before the macro
        return not (unsafe_before[last_op] & naked)

    # parse the expression
    for c in chars:
        if c == "(":
            push(last_op)
            last_op = pseudo
        elif c not in op_bit:
            keep(c)
        elif not safe():
            return 0
        elif c == ")":
            last_op = pop()
        else:
            # safety check against the operator after the macro
            last_op = op_bit[c]
            if unsafe_after[last_op] & naked:
                return 0
            # record operators not surrounded by the parentheses
            if not paren:
                retval |= last_op

    if name and not safe():
        return 0
    return retval

def main():
    global macro

    def chars(b, t):
        for k in range(b, len(t)):
            yield from t[k]

    for _ in range(int(input())):
        token = input().split()
        s = token[0] == "#"
        macro[token[1 + s]] = expr(chars(2 + s, token))

    print("OK" if expr((c for c in input() if c != " ")) else "Suspicious")

if __name__ == '__main__':
    main()

[{'input': '1\r\n#define sum x + y\r\n1 * sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum  (x + y)\r\nsum - sum\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum  x + y\r\n#define mul  a * b\r\n#define div  a / b\r\n#define expr sum + mul * div * mul\r\nexpr\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define SumSafe   (a+b)\r\n#define DivUnsafe  a/b\r\n#define DenominatorUnsafe  a*b\r\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)\r\n', 'output': ['Suspicious\r\n']}, {'input': '0\r\naa + b - c * (ddd * eee / fff * a / b * c + d - b + c - (a + b)) - d\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define a b\r\n#define c d\r\na + b + c + d + 1234567 -10*(2-2+1000*1000*1000*1000*1000)\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n  #  define  macros    (  x  +  y  ) \r\n # define  Macros (x+y)\r\nmacros/Macros\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/A\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/a\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define A v\r\n#define a v/v/v\r\nv/(a)\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define a x*y\r\nc/a\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define a b*c\r\na/a*a\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define mul  x*y\r\n#define bad  x/mul\r\n#define good x/(mul)\r\ngood\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define mult   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum+difference+(sum)*(difference)-mult+mult*division+division*mult+division/(mult+sum-(difference))\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference/division)+sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(difference)*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n(sum)/multiplication\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nsum/(multiplication)\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n#define res (0-difference)\r\nsum+res*multiplication\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define sum   xx+yy\r\n#define difference  aaaa-bbbBBBB\r\n#define multiplication   a*b\r\n#define division  aaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\ndivision/(multiplication/(division)/DIVISION/(sum-division-multiplication-(difference)))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define sum  x + y\r\n#define SomeBad  (2 * sum)\r\n#define SomePossiblyGood  0 * SomeBad + (x + x - 2*x) * SomeBad\r\nSomePossiblyGood\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define a  0\r\n#define b  (a-a)*(x/x-1)\r\nb-b/b*b\r\n', 'output': ['Suspicious\r\n']}, {'input': '2\r\n#define fkdsjfslkjfsdk x/0\r\n#define fkdsjfslkjfsdksdds 0/(0-0)\r\nfkdsjfslkjfsdk + fkdsjfslkjfsdks + fkdsjfslkjfsdkssds\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define null x/0\r\n#define some x/x\r\n#define bad 1/x\r\nbad/0+0/bad+0/0*bad\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define MWjGY x+x*53 *x\r\n#define ovqZ 2/926+x/A\r\n#define uU 55-qRj*A*2\r\nx*A/x-A\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define zz 5+7/x*x*9\r\n#define mlTL 6+x/7+x/x\r\n#define DUO 7*7-x+zz\r\n#define IH 6*4-x+x\r\n67/(5)-IH\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define Oc 9/51+65+vN\r\n#define gga 53/ 94/x/x\r\n#define ArB x/x/9-77-8\r\n#define j 76-6/93+vN\r\n#define cALNN Oc+60499\r\n8*6-66/x*x\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define fSdvwOj (W)*W+73\r\n#define NAZjc 7695*55-x\r\n#define AHGGglVwch (6-a-W)\r\n((5))+W+W\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define m bJJD +x \r\n#define yYkQNzjR (x*19)-892\r\n#define MNvfxqfbq (x-6*x/8)\r\n#define nJZdvO 8/4 *m/m\r\n 9+m/x+x\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define Sl x*7-(x)/O\r\n#define srAOHccTln 3+x*2*O\r\n#define OFAZk 239751817\r\n#define JYWrOEgazV (x-O/4)-x\r\n#define XsOZvalgOh 89905879/7\r\nx/Sl-(Sl)\r\n', 'output': ['Suspicious\r\n']}, {'input': '3\r\n#define uYdw ((9-x-3) )\r\n#define fy (((x+21)))\r\n#define nY ((2+x)-46)\r\n141141432\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define GCvqH (58 )-(x)\r\n#define g ((x/x+x))\r\n#define spst hQTJ\r\n#define i GCvqH\r\n(((x+6)))\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define rg (67)+((x))\r\n#define ya x-(6/x)*rg\r\n#define anTxe 10*ya*(x)\r\n#define xcmo ((x)*(vT))\r\n#define eg ((vT)) -ya\r\n((x*(Ii)))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define T ((b/1 +1))\r\n#define pm (s)-43-(s)\r\n#define jkNBpvDZl ((x ))/65\r\n(((58*7)))\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define cJitUt 21/(4)+4+4\r\n#define zHwBOLIvF 4*((41/x))\r\n#define GbtYVo (E)+(x+3)\r\n#define zTcZBaby (58)+x-x+x\r\n(E+E)/8 *4\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define mBURKdeKvy 266693986\r\n#define nWi ( ((x))-4)\r\n#define iYreeOt ((7/x+42))\r\n#define laLzP ((aB/35)) \r\n#define dXjRJ (((B*hX)))\r\n(1*2+(67))\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define UVMQLGvEqOxaAgRkvJH tBd\r\n#define QoAsBMaUcJzXai x/x-hm/83+8*8/5/hm /x/hm\r\n#define QtxtzEHCmidm 75 +491928441\r\n((x)/VUpYoEdDUtLFanGyqfQR  )\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define efemx 2/1*3*69+81+10/690445104\r\n#define AyjrEzAjMKZpRPfCOaO 21*9+( j*40+3*4)*ND+w-j*j+x*55\r\n#define YkJkHcNhXcci 85*3215/40/365819568\r\n#define MUzvOZSXJujI 9-4/j*j-7-w*23*5+j+9-9*ND*2/37\r\nND/j*28 -1* ND+22889023/j/j/j\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define QNUkjqPcGWF 6*4/908975666-7/10-x*7\r\n#define xqwhNWiiMaZOcmgiXYY 3936*(e*5*H+2)-TsA+(e)/1-25\r\n#define tRsSqfqJt ((uT*82/e)+e/(23+(45)-9)+(50))\r\n#define DtIOWRkYe (8*3/9)*e*x *60041512*2-(e)\r\n#define qgPgxja (4/x+e/uT*16358009- 6/13*5)\r\ne+x*e/84/x+uT*H\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define lTCUUO JQmj\r\n#define oUeQMB (12*x+x+x)-75-(79/1)-(7)*1/mr\r\n#define LAQu xwvBtky\r\n8654 *1*5-mr-3*J/oUeQMB/x/6/9\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define VLuQIO 1-x/33+ Fk+wS/35-wS-(x*iz )\r\n#define BCIsIR 5*(wS)/x/iz/1+x-x-4-x/68/x/8*x\r\n#define QPUpmTiB 21-x/895912506+2\r\n#define wcZLUIqJS 7/65-x*61-(24+iz)+x+315670+x/x\r\nBCIsIR/VLuQIO\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define FDmMYOENCOKmYwYlOl 6-(L)/((((ud/x))/ud-26*8-5))\r\n#define QkopKBjKdJxhc (6)*4/7-L/781844832  \r\n#define UjgTieUBXTSTbiLFAhkV 3*1*(52)/6-6*65/x+((L-56))+x+x\r\n#define yWVYDuqliezpKLwnI 8/4+1+88+97946+(1)-((68))-L/L\r\n#define AvvED 719901121+95/2/78/1-10+37\r\n(1*x+ 528176190+17/ud)\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define e x *R/5+(x)+4/18/x*R/x-8+1+R\r\n#define GgGqGYjXoJjIezAVu (( 491563947*R))*9-e-3/4\r\n#define XgznGUWMxQwh (8/R+4*(e)+10/4*x+24*R+21)-224\r\n (82493582)\r\n', 'output': ['OK\r\n']}, {'input': '4\r\n#define MrKSTrKhPLeJqOcEPvv (x+x/x)/Qdf-x-x-(2/23)+9442-x\r\n#define zPHUgmIYE 10- 7*x/x+VwRUuIRezDR*80\r\n#define OsfThxasHeFZCEZTfD 271456028-(x*x)-8+2*x*x*x+(x)\r\n#define zVYasB x/x -x-(51)-x*x*((x))  /x \r\n(x/64-x*( (5+x+x)-(37)/3*22))\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define WREol (fcdGZaLzhiFpVQmhHO)\r\n#define lDTNxcMqPPP 3+(57)/x/91540-x*71-x*6-((1))\r\n#define afFJVBkr ((12*x-8+9 *lDlx+7+lDlx))\r\n#define mYEizEWrNtRSQNCcDQrn 732480960+9+x-78-x/1+12*x\r\n#define IZTmjheAahbNSNFa ((x-x*7+407643063 ))\r\nXQvMxLNpQnhpimNhAkfX\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define Mc x+x*55231- x/x/x+35/x*(5*(x)) -5*x*(1-2-(29/1))\r\n#define afSVLCdjvylSu bgqv/6+4*x*((Mc/1318/x-8-4)-Mc/Mc/(9))\r\n#define ZOSV (1+2/x+6* 174806683)-x/x*Mc+52*x-x\r\nbgqv-x-6*x/72/(x )/afSVLCdjvylSu\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define RJIiiGQqn dmpWFcrqQeM+V-o* 55/9*o-o/V*V*o\r\n#define ElDZlrtzDkeKgsX 498718105* 3/(y)/(4)-(5*x)*1\r\n#define qwKl jHqPHX\r\n#define qXzAZkCuchBYR  (qy*qwKl-6+5*1+2)-7-3+(38)-o*4/4-1-V*x/6+1*x/o\r\no*((V))-o+2+((((2*V)/V-o*V/4)))/o*33+y/7  -x+x \r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define WTovyGexUNjGMRJv (MQG*18-6)/x/x*x/x-x*akNyw*x+x-x/2/x*20\r\n#define hpextyhVCa 70*x/67-x*87931-(497612505-7*x-MQG)-x\r\n#define MRkKnCXFt x-5-21962-x/sOmThNSS/x/6-4+(65+57+x+x+7-7+x/x)\r\n#define ajsczBLLklBSqqh nGj-38*9 *x/47/8*5/5-72/x*x-x*x*31  /7-44-3+64\r\n#define jgqfv WTovyGexUNjGMRJv\r\n  4+338/x*x+13 -795*3-74*2/4+563-x/76401438/83025\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define G u+13-35348/2-(u/u)-u/u*u*(OC)-OC -u-u/u*u/9 \r\n#define RNRQ G*G*u+G/755750/G/G +((u-6*G+6)*2)- 5*96+5/u*275-u\r\n#define Zg 94363/u*u-41+Gm*G-81/5-1-G*G*x-(5517*5/4)*21 +75\r\n406690013/WM*G+(u+u)*Zg+2\r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define RMWAZhIp x*x+12+94*12*5*1-x-141915293\r\n#define EeguG 9-55+x/29+x+x/E*8*81/x-x*75-4*17-81/x/6+619978*x*x\r\n#define HvUYEvQTyYmBGvqHSb 454574730/644135926*x/23+E-sy/14\r\n#define BqMGcT x/(43)+819897061-x*(7/x)-(x)+sy-E-x*79-E+(x)/6/63\r\n76+3/x/8*x+E-76+sy-sy+9*6/66/sy-77+x-x*sy+E/50/64\r\n', 'output': ['OK\r\n']}, {'input': '5\r\n#define cbt ((((d))+9-3+ (d)/d/6*SDDNqj*50/d+d-m+8/d/1)) \r\n#define gLrUE 18+ 70*d/3-d*d-d/35 +33-5/9+d-d*387+d-1\r\n#define AvjmK 9-d-8+(d+m+5/2/x*d+1)/x/d-5-2*(m)+d+17/d+ 4/52/8\r\n#define SjrJ 90/7/5/d+ 254877982+(m) *x-19\r\n#define PlykoqfDbwxR  540304590 +d*x/11-(m+d-d-4)*(d-3-1)/d\r\nd-2+1+46-29620+9-(9*3 /d)*6*m/d+9+(1670)/cbt/d+d\r\n', 'output': ['OK\r\n']}, {'input': '3\r\n#define BuAiJLgAlkj x-3+419032556/409023036-(17*84)+x+8+A\r\n#define wU 516506880\r\n#define HeyDGlnaGxBaHjzelvF iRSPqHfgHw/4-(99)*(I)+A+I-9*46*x\r\nI/CRklg-HeyDGlnaGxBaHjzelvF/3+5 \r\n', 'output': ['Suspicious\r\n']}, {'input': '4\r\n#define SOlTohcPGckDyF ((D)/G-83+KHGSuJFLHqD/5)\r\n#define KEUXeOYpg 9+x-8-8/x/9-65-6+4+55*x-58/x+84+D*2-7+D/x-x*G/4-2\r\n#define YZl (1/67*x*6/2*G)-D/1595107*D+6/x*1+D+3/9/x/26-6+9 \r\n#define gCatFsZn uBBqilYclMhpVfKKTkGK\r\n(28682537+ YZl*(4*52)  )*x/8- gCatFsZn*x/54/7\r\n', 'output': ['Suspicious\r\n']}, {'input': '5\r\n#define iiXEqDYeyVmIYsOaO fj/x-9-6/x*x+ 1/ 7*2-x -x+9+235*23*Ww+x-2*K+2-x/70\r\n#define XVgLzhoTUxoBr ( x+x/x/x*6-x)* x+K/24206-2 /5/8-x-7/Ww/K-x+6 \r\n#define QdfRBaJk 470551685-(  54-x)-30\r\n#define gEJcAGnF x+x-x+(x/x+9)/x-41-1/fj/1157561+x/x -x/26/x+K*x\r\n#define lO 7-1*(x*58 )-K*fj  /722113691/x/K+2\r\n2+4*85/86/x*27 /49252-x*x/6-83-7/x+x+K-lO+8-K-x\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr-sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nr*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nr-sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr*sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x*y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr-sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr*sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x/y\r\nr+sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr-sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr*sum\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nr/sum\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum*r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x+y\r\nsum/r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum*r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x-y\r\nsum/r\r\n', 'output': ['Suspicious\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum*r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x*y\r\nsum/r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum+r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum-r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum*r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define sum x/y\r\nsum/r\r\n', 'output': ['OK\r\n']}, {'input': '1\r\n#define x 3/2\r\n2*x\r\n', 'output': ['OK\r\n']}, {'input': '2\r\n   #    define     sum     1000000000   +   1000000000       +     1000000000      \r\n    #    define      a    b     +      45    *   sum    \r\n       a       \r\n', 'output': ['Suspicious\r\n']}]