I found an interesting problem on https://codeforces.com/problemset/problem/1197/D:
You are given an array $a_1, a_2, \dots , a_n$ and two integers $m$ and $k$.

You can choose some subarray $a_l, a_{l+1}, \dots, a_{r-1}, a_r$.

The cost of subarray $a_l, a_{l+1}, \dots, a_{r-1}, a_r$ is equal to $\sum\limits_{i=l}^{r} a_i - k \lceil \frac{r - l + 1}{m} \rceil$, where $\lceil x \rceil$ is the least integer greater than or equal to $x$.

The cost of empty subarray is equal to zero.

For example, if $m = 3$, $k = 10$ and $a = [2, -4, 15, -3, 4, 8, 3]$, then the cost of some subarrays are:  $a_3 \dots a_3: 15 - k \lceil \frac{1}{3} \rceil = 15 - 10 = 5$;  $a_3 \dots a_4: (15 - 3) - k \lceil \frac{2}{3} \rceil = 12 - 10 = 2$;  $a_3 \dots a_5: (15 - 3 + 4) - k \lceil \frac{3}{3} \rceil = 16 - 10 = 6$;  $a_3 \dots a_6: (15 - 3 + 4 + 8) - k \lceil \frac{4}{3} \rceil = 24 - 20 = 4$;  $a_3 \dots a_7: (15 - 3 + 4 + 8 + 3) - k \lceil \frac{5}{3} \rceil = 27 - 20 = 7$.

Your task is to find the maximum cost of some subarray (possibly empty) of array $a$.

-----Input-----

The first line contains three integers $n$, $m$, and $k$ ($1 \le n \le 3 \cdot 10^5, 1 \le m \le 10, 1 \le k \le 10^9$).

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$).

-----Output-----

Print the maximum cost of some subarray of array $a$.

-----Examples-----
Input
7 3 10
2 -4 15 -3 4 8 3

Output
7

Input
5 2 1000
-13 -4 -9 -20 -11

Output
0

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin, stdout, exit

n, m, k = list(map(int, stdin.readline().split()))
a = list(map(int, stdin.readline().split()))

def bf(a):
    best = 0
    best_arg = (-1, -1)
    for i in range(n):
        for j in range(i, n):
            cur = sum(a[i:j+1]) - k*((j - i) // m + 1)
            if cur > best:
                best = max(best, cur)
                best_arg = (i,j)
    return best, best_arg

def max_sum(a):
    if len(a) == 0:
        return 0
    elif len(a) == 1:
        return max(0, a[0] - k)
    mid = len(a) // 2
    l_rec = max_sum(a[:mid])
    r_rec = max_sum(a[mid:])
    l_bests = [0]*m
    r_bests = [0]*m
    l_sum = 0
    for idx in range(1,mid+1):
        l_sum += a[mid-idx]
        if idx % m == 0:
            l_sum -= k
        l_bests[idx%m] = max(l_bests[idx%m], l_sum)
    r_sum = 0
    for idx in range(0, len(a)-mid):
        r_sum += a[idx+mid]
        if (idx+1) % m == 0:
            r_sum -= k
        r_bests[(idx+1)%m] = max(r_bests[(idx+1)%m], r_sum)

 #   print("Array:", a, "mid:", mid)
#    print(l_bests)
  #  print(r_bests)
    best_acr = 0
    for i in range(m):
        for j in range(m):
            best_acr = max(best_acr, l_bests[i] + r_bests[j] - (k if i+j>0 else 0) - (k if i+j>m else 0))
    ans = max(l_rec,r_rec, best_acr)
   # print("Answer:", ans)
    return ans

ans = max_sum(a)
stdout.write(str(ans) + "\n")
#stdout.write(str(bf(a))+"\n")


I found an interesting problem on https://codeforces.com/problemset/problem/1197/E:
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $n$ different matryoshkas. Any matryoshka is a figure of volume $out_i$ with an empty space inside of volume $in_i$ (of course, $out_i > in_i$).

You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka $i$ can be nested inside matryoshka $j$ if $out_i \le in_j$. So only the last doll will take space inside your bag.

Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$, where $i_1$, $i_2$, ..., $i_k$ are the indices of the chosen dolls in the order they are nested in each other.

Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.

You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $i$ such that one of the subsets contains the $i$-th doll, and another subset doesn't.

Since the answer can be large, print it modulo $10^9 + 7$.

-----Input-----

The first line contains a single...

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline
from bisect import bisect_right as br
P = 10**9+7
N = int(input())
X = []
maxinn = 0
for _ in range(N):
    a, b = list(map(int, input().split()))
    maxinn = max(maxinn, b)
    X.append((a, b))
X = sorted(X)
OUT = [0]
VOL = [0]
CNT = [1]

for out, inn in X:
    i = br(OUT, inn) - 1
    vol = VOL[i] + out - inn
    if OUT[-1] != out:
        OUT.append(out)
        VOL.append(VOL[-1])
        CNT.append(CNT[-1])

    if VOL[-1] < vol:
        VOL[-1] = vol
        CNT[-1] = CNT[i]
    elif VOL[-1] == vol:
        CNT[-1] += CNT[i]
        CNT[-1] %= P

mi = min([OUT[i]-VOL[i] for i in range(len(CNT)) if OUT[i] > maxinn])
print(sum([CNT[i] for i in range(len(CNT)) if OUT[i] > maxinn and OUT[i]-VOL[i] == mi])%P)


I found an interesting problem on https://codeforces.com/problemset/problem/1198/A:
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers.

If there are exactly $K$ distinct values in the array, then we need $k = \lceil \log_{2} K \rceil$ bits to store each value. It then takes $nk$ bits to store the whole file.

To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $l \le r$, and after that all intensity values are changed in the following way: if the intensity value is within the range $[l;r]$, we don't change it. If it is less than $l$, we change it to $l$; if it is greater than $r$, we change it to $r$. You can see that we lose some low and some high intensities.

Your task is to apply this compression in such a way that the file fits onto a disk of size $I$ bytes, and the number of changed elements in the array is minimal possible.

We remind you that $1$ byte contains $8$ bits.

$k = \lceil log_{2} K \rceil$ is the smallest integer such that $K \le 2^{k}$. In particular, if $K = 1$, then $k = 0$.

-----Input-----

The first line contains two integers $n$ and $I$ ($1 \le n \le 4 \cdot 10^{5}$, $1 \le I \le 10^{8}$) — the length of the array and the size of the disk in bytes, respectively.

The next line contains $n$ integers $a_{i}$ ($0 \le a_{i} \le 10^{9}$) — the array denoting the sound file.

-----Output-----

Print a single integer — the minimal possible number of changed elements.

-----Examples-----
Input
6 1
2 1 2 3 4 3

Output
2

Input
6 2
2 1 2 3 4 3

Output
0

Input
6 1
1 1 2 2 3 3

Output
2

-----Note-----

In the first example we can choose $l=2, r=3$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $K=2$, and the sound file fits onto the disk. Only two values are changed.

In the second example the disk is larger, so the initial file fits it and no changes are...

I tried it in Python, but could not do it. Can you solve it?

from itertools import groupby as gb

N, I = map(int,input().split())
A = list(map(int,input().split()))
A = sorted(A)
l = []
G = gb(A)
for k, v in G:
    l.append(len(list(v)))

k = 100
while True:
    if N * k > 8 * I:
        k -= 1
    else:
        break
K = 2 ** k

NN = len(l)
if NN <= K:
    print(0)
    return

sm = sum(l[:K])
mx = sm

for i in range(K, NN):
    sm += l[i] - l[i - K]
    mx = max(mx, sm)

print(sum(l) - mx)


I found an interesting problem on https://codeforces.com/problemset/problem/1198/E:
There is a square grid of size $n \times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\min(h, w)$ to color a rectangle of size $h \times w$. You are to make all cells white for minimum total cost.

The square is large, so we give it to you in a compressed way. The set of black cells is the union of $m$ rectangles.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 10^{9}$, $0 \le m \le 50$) — the size of the square grid and the number of black rectangles.

Each of the next $m$ lines contains 4 integers $x_{i1}$ $y_{i1}$ $x_{i2}$ $y_{i2}$ ($1 \le x_{i1} \le x_{i2} \le n$, $1 \le y_{i1} \le y_{i2} \le n$) — the coordinates of the bottom-left and the top-right corner cells of the $i$-th black rectangle.

The rectangles may intersect.

-----Output-----

Print a single integer — the minimum total cost of painting the whole square in white.

-----Examples-----
Input
10 2
4 1 5 10
1 4 10 5

Output
4

Input
7 6
2 1 2 1
4 2 4 3
2 5 2 5
2 3 5 3
1 2 1 2
3 2 5 3

Output
3

-----Note-----

The examples and some of optimal solutions are shown on the pictures below.

 [Image]

I tried it in Python, but could not do it. Can you solve it?

import sys
from collections import defaultdict

class MaxFlow(object):
    def __init__(self):
        self.edges = defaultdict(lambda: defaultdict(lambda: 0))

    def add_edge(self, u, v, capacity=float('inf')):
        self.edges[u][v] = capacity

    def bfs(self, s, t):
        open_q = [s]

        visited = set()
        parent = dict()
        while open_q:
            close_q = []
            for node in open_q:
                for v, capacity in list(self.edges[node].items()):
                    if v not in visited and capacity > 0:
                        close_q.append(v)
                        parent[v] = node
                        visited.add(v)
                        if v == t:
                            result = []
                            n2 = v
                            n1 = node
                            while n1 != s:
                                result.append((n1, n2))
                                n2 = n1
                                n1 = parent[n1]
                            result.append((n1, n2))
                            return result

            open_q = close_q

        return None

    def solve(self, s, t):
        flow = 0
        route = self.bfs(s, t)
        while route is not None:
            new_flow = float('inf')
            for _, (n1, n2) in enumerate(route):
                new_flow = min(new_flow, self.edges[n1][n2])
            for _, (n1, n2) in enumerate(route):
                self.edges[n1][n2] -= new_flow
                self.edges[n2][n1] += new_flow
            flow += new_flow

            route = self.bfs(s, t)

        return flow

    def __str__(self):
        result = "{ "
        for k, v in list(self.edges.items()):
            result += str(k) + ":" + str(dict(v)) + ", "
        result += "}"
        return result

def main():
    (n, m) = tuple([int(x) for x in input().split()])
    r = []
    xs = set()
    ys = set()
    for i in range(m):
        (x1, y1, x2, y2) = tuple(int(x) for x in input().split())
       ...


I found an interesting problem on https://codeforces.com/problemset/problem/1198/F:
You are given an array of $n$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.

The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.

Both groups have to be non-empty.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 10^5$).

The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array.

-----Output-----

In the first line print "YES" (without quotes), if it is possible to split the integers into two groups as required, and "NO" (without quotes) otherwise.

If it is possible to split the integers, in the second line print $n$ integers, where the $i$-th integer is equal to $1$ if the integer $a_i$ should be in the first group, and $2$ otherwise.

If there are multiple solutions, print any.

-----Examples-----
Input
4
2 3 6 7

Output
YES
2 2 1 1

Input
5
6 15 35 77 22

Output
YES
2 1 2 1 1

Input
5
6 10 15 1000 75

Output
NO

I tried it in Python, but could not do it. Can you solve it?

import sys

def gcd(l):
	if len(l)==0:
		return 0
	if len(l)==1:
		return l[0]
	if len(l)==2:
		if l[1]==0:
			return l[0]
		return gcd([l[1],l[0]%l[1]])
	return gcd([gcd(l[:-1]),l[-1]])

def brute_force(l1,l2,l,sol):
	if len(l)==0:
		g1=gcd(l1)
		g2=gcd(l2)
		return g1==1 and g2==1,sol

	res,s=brute_force(l1+[l[0]],l2,l[1:],sol+[1])
	if res:
		return True,s
	return brute_force(l1,l2+[l[0]],l[1:],sol+[2])

def factor(n):
	res=[]
	i=2
	while i*i<=n:
		if n%i==0:
			res.append(i)
		while n%i==0:
			n=int(n/i)
		i+=1

	if n!=1:
		res.append(n)

	return res

def dumpsol(sol):
	for v in sol:
		print(v,end=' ')

n=int(sys.stdin.readline())
l=sys.stdin.readline().strip().split(" ")[0:n]
l=[int(x) for x in l]
if n<12:
	ret,sol=brute_force([],[],l,[])
	if ret:
		print("YES")
		dumpsol(sol)
	else:
		print("NO")
	return

factors={}
for i in range(10):
	for key in factor(l[i]):
		factors[key]=0

flists={}
for f in factors:
	flists[f]=[]
	pos=0
	found=False
	for v in l:
		if v%f!=0:
			found=True
			factors[f]+=1
			flists[f].append(pos)
			if (factors[f]>9):
				break
		pos+=1
	if not found:
		print("NO")
		return

oftf=[]
isoftf={}
for f in factors:
	if factors[f]==0:
		print("NO")
		return

	if factors[f]<10:
		oftf.append(f)
		isoftf[f]=1

#print(oftf)

sol=[1 for i in range(len(l))]
x=l[0]
sol[0]=2
oxf=factor(x)
#print(oxf)
xf=[]
nxf=0
isxoftf={}
for f in oxf:
	if f in isoftf:
		nxf+=1
		isxoftf[f]=1
		xf.append(f)
	else:
		sol[flists[f][0]]=2

nonxf=[]
for f in oftf:
	if not f in isxoftf:
		nonxf.append(f)

masks={}
pos=0

#print(xf)
#print(nonxf)

for f in xf+nonxf:
	for v in flists[f]:
		if not v in masks:
			masks[v]=0
		masks[v]|=1<<pos
	pos+=1

vals=[{} for i in range(len(masks)+1)]
vals[0][0]=0
pos=0
mlist=[]
for mask in masks:
	mlist.append(mask)
	cmask=masks[mask]
	cmask1=cmask<<10
	#print(vals)
	for v in vals[pos]:
		vals[pos+1][v|cmask]=v
		# first number is always in group2
		if...


I found an interesting problem on https://codeforces.com/problemset/problem/1199/A:
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $n$ days of summer. On the $i$-th day, $a_i$ millimeters of rain will fall. All values $a_i$ are distinct.

The mayor knows that citizens will watch the weather $x$ days before the celebration and $y$ days after. Because of that, he says that a day $d$ is not-so-rainy if $a_d$ is smaller than rain amounts at each of $x$ days before day $d$ and and each of $y$ days after day $d$. In other words, $a_d < a_j$ should hold for all $d - x \le j < d$ and $d < j \le d + y$. Citizens only watch the weather during summer, so we only consider such $j$ that $1 \le j \le n$.

Help mayor find the earliest not-so-rainy day of summer.

-----Input-----

The first line contains three integers $n$, $x$ and $y$ ($1 \le n \le 100\,000$, $0 \le x, y \le 7$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.

The second line contains $n$ distinct integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ denotes the rain amount on the $i$-th day.

-----Output-----

Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.

-----Examples-----
Input
10 2 2
10 9 6 7 8 3 2 1 4 5

Output
3

Input
10 2 3
10 9 6 7 8 3 2 1 4 5

Output
8

Input
5 5 5
100000 10000 1000 100 10

Output
5

-----Note-----

In the first example days $3$ and $8$ are not-so-rainy. The $3$-rd day is earlier.

In the second example day $3$ is not not-so-rainy, because $3 + y = 6$ and $a_3 > a_6$. Thus, day $8$ is the answer. Note that $8 + y = 11$, but we don't consider day $11$, because it is not summer.

I tried it in Python, but could not do it. Can you solve it?

n,x,y = list(map(int, input().split()))
a = list(map(int, input().split()))

for i in range(n):
    ans = True
    for j in range(i-x, i):
        if j >= 0 and a[j] < a[i]:
            ans = False
            break
    for j in range(i+1, i+y+1):
        if j < n and a[j] < a[i]:
            ans = False
            break
    if ans:
        print(i+1)
        return


I found an interesting problem on https://codeforces.com/problemset/problem/1199/B:
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $H$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $L$ centimeters. Exactly at this point the flower touched the water surface. [Image]

Suppose that the lily grows at some point $A$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $A$. Also suppose that initially the flower was exactly above the point $A$, i.e. its stem was vertical. Can you determine the depth of the lake at point $A$?

-----Input-----

The only line contains two integers $H$ and $L$ ($1 \le H < L \le 10^{6}$).

-----Output-----

Print a single number — the depth of the lake at point $A$. The absolute or relative error should not exceed $10^{-6}$.

Formally, let your answer be $A$, and the jury's answer be $B$. Your answer is accepted if and only if $\frac{|A - B|}{\max{(1, |B|)}} \le 10^{-6}$.

-----Examples-----
Input
1 2

Output
1.5000000000000

Input
3 5

Output
2.6666666666667

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/1200/A:
Amugae has a hotel consisting of $10$ rooms. The rooms are numbered from $0$ to $9$ from left to right.

The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.

One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.

-----Input-----

The first line consists of an integer $n$ ($1 \le n \le 10^5$), the number of events in Amugae's memory.

The second line consists of a string of length $n$ describing the events in chronological order. Each character represents:   'L': A customer arrives from the left entrance.  'R': A customer arrives from the right entrance.  '0', '1', ..., '9': The customer in room $x$ ($0$, $1$, ..., $9$ respectively) leaves.

It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $x$ when $x$ ($0$, $1$, ..., $9$) is given. Also, all the rooms are initially empty.

-----Output-----

In the only line, output the hotel room's assignment status, from room $0$ to room $9$. Represent an empty room as '0', and an occupied room as '1', without spaces.

-----Examples-----
Input
8
LLRL1RL1

Output
1010000011
Input
9
L0L0LLRR9

Output
1100000010

-----Note-----

In the first example, hotel room's assignment status after each action is as follows.   First of all, all rooms are empty. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  L: one more customer from the left entrance. Assignment status is 1100000000.  R:...

I tried it in Python, but could not do it. Can you solve it?

# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
from sys import stdin, stdout
import math

N = int(input())
s = input()
#N,M = [int(x) for x in stdin.readline().split()]
#arr = [int(x) for x in stdin.readline().split()]

room = [0]*10

for i in range(N):
    letter = s[i]

    if letter=='L':
        for j in range(10):
            if room[j]==0:
                room[j] = 1
                break
    elif letter=='R':
        for j in range(9,-1,-1):
            if room[j]==0:
                room[j] = 1
                break

    else:
        d = int(letter)
        room[d] = 0

print(*room,sep='')


I found an interesting problem on https://codeforces.com/problemset/problem/1200/B:
Gildong is playing a video game called Block Adventure. In Block Adventure, there are $n$ columns of blocks in a row, and the columns are numbered from $1$ to $n$. All blocks have equal heights. The height of the $i$-th column is represented as $h_i$, which is the number of blocks stacked in the $i$-th column.

Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $1$-st column. The goal of the game is to move the character to the top of the $n$-th column.

The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $i$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $i$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $i$-th column;  if $i < n$ and $|h_i - h_{i+1}| \le k$, move the character to the top of the $i+1$-st column. $k$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column.

In actions of the first two types the character remains in the $i$-th column, and the value $h_i$ changes.

The character initially has $m$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

-----Input-----

Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 1000$). Description of the test cases follows.

The first line of each test case contains three integers $n$, $m$, and $k$ ($1 \le n \le 100$, $0 \le m \le 10^6$, $0 \le k \le 10^6$) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $k$ described in the statement.

The second line of each test case contains $n$ integers. The $i$-th integer is $h_i$ ($0...

I tried it in Python, but could not do it. Can you solve it?

for __ in range(int(input())):
    n, m, k = map(int, input().split())
    arr = list(map(int, input().split()))
    flg = True
    for f, nx in zip(arr, arr[1:]):
        tg = max(nx - k, 0)
        m -= tg - f
        if m < 0: flg = False
    print('YES' if flg else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1200/C:
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $n$ sectors, and the outer area is equally divided by $m$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position.

 $0$

The inner area's sectors are denoted as $(1,1), (1,2), \dots, (1,n)$ in clockwise direction. The outer area's sectors are denoted as $(2,1), (2,2), \dots, (2,m)$ in the same manner. For a clear understanding, see the example image above.

Amugae wants to know if he can move from one sector to another sector. He has $q$ questions.

For each question, check if he can move between two given sectors.

-----Input-----

The first line contains three integers $n$, $m$ and $q$ ($1 \le n, m \le 10^{18}$, $1 \le q \le 10^4$) — the number of sectors in the inner area, the number of sectors in the outer area and the number of questions.

Each of the next $q$ lines contains four integers $s_x$, $s_y$, $e_x$, $e_y$ ($1 \le s_x, e_x \le 2$; if $s_x = 1$, then $1 \le s_y \le n$, otherwise $1 \le s_y \le m$; constraints on $e_y$ are similar). Amague wants to know if it is possible to move from sector $(s_x, s_y)$ to sector $(e_x, e_y)$.

-----Output-----

For each question, print "YES" if Amugae can move from $(s_x, s_y)$ to $(e_x, e_y)$, and "NO" otherwise.

You can print each letter in any case (upper or lower).

-----Example-----
Input
4 6 3
1 1 2 3
2 6 1 2
2 6 2 4

Output
YES
NO
YES

-----Note-----

Example is shown on the picture in the statement.

I tried it in Python, but could not do it. Can you solve it?

from math import gcd
n, m, q = list(map(int, input().split()))
kabe = gcd(n, m)
n //= kabe
m //= kabe
for i in range(q):
    sx, sy, ex, ey = list(map(int, input().split()))
    sy -= 1
    ey -= 1
    if sx == 1:
        if ex == 1:
            if sy//n == ey//n:
                print("YES")
            else:
                print("NO")
        else:
            if sy//(n) == ey//(m):
                print("YES")
            else:
                print("NO")
    else:
        if ex == 1:
            if sy//(m) == ey//(n):
                print("YES")
            else:
                print("NO")
        else:
            if sy//(m) == ey//(m):
                print("YES")
            else:
                print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1200/D:
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $n$ rows and $n$ columns of square cells. The rows are numbered from $1$ to $n$, from top to bottom, and the columns are numbered from $1$ to $n$, from left to right. The position of a cell at row $r$ and column $c$ is represented as $(r, c)$. There are only two colors for the cells in cfpaint — black and white.

There is a tool named eraser in cfpaint. The eraser has an integer size $k$ ($1 \le k \le n$). To use the eraser, Gildong needs to click on a cell $(i, j)$ where $1 \le i, j \le n - k + 1$. When a cell $(i, j)$ is clicked, all of the cells $(i', j')$ where $i \le i' \le i + k - 1$ and $j \le j' \le j + k - 1$ become white. In other words, a square with side equal to $k$ cells and top left corner at $(i, j)$ is colored white.

A white line is a row or a column without any black cells.

Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the number of rows and columns, and the size of the eraser.

The next $n$ lines contain $n$ characters each without spaces. The $j$-th character in the $i$-th line represents the cell at $(i,j)$. Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.

-----Output-----

Print one integer: the maximum number of white lines after using the eraser exactly once.

-----Examples-----
Input
4 2
BWWW
WBBW
WBBW
WWWB

Output
4

Input
3 1
BWB
WWB
BWB

Output
2

Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW

Output
2

Input
2 2
BW
WB

Output
4

Input
2 1
WW
WW

Output
4

-----Note-----

In the first example, Gildong can click the cell $(2, 2)$, then the working screen becomes: BWWW

WWWW

WWWW

WWWB

Then there are four white lines — the...

I tried it in Python, but could not do it. Can you solve it?

def main():
  n, k = list(map(int, input().split()))
  ss = []
  tate = [[0 for _ in range(n+1)] for _ in range(n+1)]
  yoko = [[0 for _ in range(n+1)] for _ in range(n+1)]
  for i in range(n):
    s = input().strip()
    for j, _s in enumerate(s):
      tate[i+1][j+1] = tate[i][j+1] + (1 if _s == 'B' else 0)
      yoko[i+1][j+1] = yoko[i+1][j] + (1 if _s == 'B' else 0)
  lc = 0
  for i in range(n):
    if tate[n][i+1] == 0:
      lc += 1
    if yoko[i+1][n] == 0:
      lc += 1
  yans = [[0 for _ in range(n+1)] for _ in range(n+1)]
  tans = [[0 for _ in range(n+1)] for _ in range(n+1)]
  for i in range(n):
    l, r = 0, k
    while r <= n:
      yans[i+1][l+1] = yans[i][l+1]
      if yoko[i+1][n] != 0 and yoko[i+1][r] - yoko[i+1][l] == yoko[i+1][n]:
        yans[i+1][l+1] += 1
      l += 1
      r += 1

  for i in range(n):
    l, r = 0, k
    while r <= n:
      tans[l+1][i+1] = tans[l+1][i]
      if tate[n][i+1] != 0 and tate[r][i+1] - tate[l][i+1] == tate[n][i+1]:
        tans[l+1][i+1] += 1
      l += 1
      r += 1

  ans = lc
  for i in range(n-k+1):
    for j in range(n-k+1):
      ans = max(ans, lc+yans[i+k][j+1]-yans[i][j+1]+tans[i+1][j+k]-tans[i+1][j])
  # print(*tate, sep='\n')
  # print()
  # print(*yoko, sep='\n')
  # print()
  # print(*tans, sep='\n')
  # print()
  # print(*yans, sep='\n')
  # print()
  print(ans)

def __starting_point():
  main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1200/E:
Amugae has a sentence consisting of $n$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".

Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^5$), the number of the words in Amugae's sentence.

The second line contains $n$ words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed $10^6$.

-----Output-----

In the only line output the compressed word after the merging process ends as described in the problem.

-----Examples-----
Input
5
I want to order pizza

Output
Iwantorderpizza
Input
5
sample please ease in out

Output
sampleaseinout

I tried it in Python, but could not do it. Can you solve it?

def prefix_func(s):
    p = [0] * len(s)
    for i in range(1, len(s)):
        j = p[i - 1]
        while j > 0 and s[i] != s[j]:
            j = p[j - 1]

        if s[i] == s[j]:
        	j += 1
        p[i] = j

    return p[-1]

n = int(input())
s = input().split()
ans = [*s[0]]

for i in s[1:]:
    c = [*i] + ['$'] + ans[-min(len(i), len(ans)):]
    j = prefix_func(c)
    for _ in range(j):
        ans.pop()
    ans.extend([*i])

print(''.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1201/A:
A class of students wrote a multiple-choice test.

There are $n$ students in the class. The test had $m$ questions, each of them had $5$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $i$ worth $a_i$ points. Incorrect answers are graded with zero points.

The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.

-----Input-----

The first line contains integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of students in the class and the number of questions in the test.

Each of the next $n$ lines contains string $s_i$ ($|s_i| = m$), describing an answer of the $i$-th student. The $j$-th character represents the student answer (A, B, C, D or E) on the $j$-th question.

The last line contains $m$ integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le 1000$) — the number of points for the correct answer for every question.

-----Output-----

Print a single integer — the maximum possible total score of the class.

-----Examples-----
Input
2 4
ABCD
ABCE
1 2 3 4

Output
16
Input
3 3
ABC
BCD
CDE
5 4 12

Output
21

-----Note-----

In the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $16$.

In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $5 + 4 + 12 = 21$.

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin, stdout, exit

n,m = list(map(int, stdin.readline().split()))
cts = [[0]*5 for i in range(m)]
for i in range(n):
    s = stdin.readline().strip()
    for j,c in enumerate(s):
        cts[j][ord(c)-ord('A')] += 1

a = list(map(int, stdin.readline().split()))
ans = 0
for j in range(m):
    ans += max(cts[j])*a[j]

stdout.write(str(ans) + "\n")


I found an interesting problem on https://codeforces.com/problemset/problem/1201/B:
You are given an array $a_1, a_2, \ldots, a_n$.

In one operation you can choose two elements $a_i$ and $a_j$ ($i \ne j$) and decrease each of them by one.

You need to check whether it is possible to make all the elements equal to zero or not.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the size of the array.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array.

-----Output-----

Print "YES" if it is possible to make all elements zero, otherwise print "NO".

-----Examples-----
Input
4
1 1 2 2

Output
YES
Input
6
1 2 3 4 5 6

Output
NO

-----Note-----

In the first example, you can make all elements equal to zero in $3$ operations:   Decrease $a_1$ and $a_2$,  Decrease $a_3$ and $a_4$,  Decrease $a_3$ and $a_4$

In the second example, one can show that it is impossible to make all elements equal to zero.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
a= list(map(int,input().split()))
#print(sum(a), max(a))
if(sum(a) < 2*max(a) or sum(a)%2 == 1):
    print('NO')
else:
    print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1201/C:
You are given an array $a$ of $n$ integers, where $n$ is odd. You can make the following operation with it:  Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$).

You want to make the median of the array the largest possible using at most $k$ operations.

The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $[1, 5, 2, 3, 5]$ is $3$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $n$ is odd, $1 \le k \le 10^9$) — the number of elements in the array and the largest number of operations you can make.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$).

-----Output-----

Print a single integer — the maximum possible median after the operations.

-----Examples-----
Input
3 2
1 3 5

Output
5
Input
5 5
1 2 1 1 1

Output
3
Input
7 7
4 1 2 4 3 4 4

Output
5

-----Note-----

In the first example, you can increase the second element twice. Than array will be $[1, 5, 5]$ and it's median is $5$.

In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $3$.

In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $[5, 1, 2, 5, 3, 5, 5]$ and the median will be $5$.

I tried it in Python, but could not do it. Can you solve it?

n, k = [int(s) for s in input().split()]
arr = sorted([int(s) for s in input().split()])
arr = arr[::-1]
arr = [pow(10, 11)] + arr[0:(n // 2 + 1)]
n = len(arr)
point = n - 1
while(k != 0):
    t = min(k, (n - point) * (arr[point - 1] - arr[point]))
    k -= t
    arr[point] += t // (n - point)
    if k != 0:
        point -= 1
print(arr[point])


I found an interesting problem on https://codeforces.com/problemset/problem/1201/D:
You are on the island which can be represented as a $n \times m$ table. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are $k$ treasures on the island, the $i$-th of them is located at the position $(r_i, c_i)$.

Initially you stand at the lower left corner of the island, at the position $(1, 1)$. If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from $(r, c)$ to $(r+1, c)$), left (from $(r, c)$ to $(r, c-1)$), or right (from position $(r, c)$ to $(r, c+1)$). Because of the traps, you can't move down.

However, moving up is also risky. You can move up only if you are in a safe column. There are $q$ safe columns: $b_1, b_2, \ldots, b_q$. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.

-----Input-----

The first line contains integers $n$, $m$, $k$ and $q$ ($2 \le n, \, m, \, k, \, q \le 2 \cdot 10^5$, $q \le m$) — the number of rows, the number of columns, the number of treasures in the island and the number of safe columns.

Each of the next $k$ lines contains two integers $r_i, c_i$, ($1 \le r_i \le n$, $1 \le c_i \le m$) — the coordinates of the cell with a treasure. All treasures are located in distinct cells.

The last line contains $q$ distinct integers $b_1, b_2, \ldots, b_q$ ($1 \le b_i \le m$) — the indices of safe columns.

-----Output-----

Print the minimum number of moves required to collect all the treasures.

-----Examples-----
Input
3 3 3 2
1 1
2 1
3 1
2 3

Output
6
Input
3 5 3 2
1 2
2 3
3 1
1 5

Output
8
Input
3 6 3 2
1 6
2 2
3 4
1 6

Output
15

-----Note-----

In the first example you should use the second column to go up, collecting in each row treasures from the first column. [Image]

In the second example, it is optimal to use the first column to go up. [Image]

In the third example, it is optimal to collect the treasure at cell $(1;6)$, go up to row $2$ at column $6$, then collect...

I tried it in Python, but could not do it. Can you solve it?

import sys
n, m, k, q = [int(i) for i in sys.stdin.readline().split()]
indata = sys.stdin.readlines()
data = []
inf = 1<<50

for i in range(k):
    data.append(tuple([int(f) for f in indata[i].split()]))

data.sort()
chutes = [int(i) for i in indata[-1].split()]
chutes.sort()
nearch = [(0,0)]*(m+1)
for i in range(1, chutes[0]+1):
    nearch[i] = (chutes[0], chutes[0])
for i in range(q-1):
    a = chutes[i]
    b = chutes[i+1]
    for j in range(a+1, b):
        nearch[j] = (a,b)
    nearch[b] = (b,b)
for i in range(chutes[-1], m+1):
    nearch[i] = (chutes[-1],chutes[-1])

lastr = -1
rows = []
rowdata = {}
for d in data:
    if d[0] != lastr:
        lastr = d[0]
        rows.append(d[0])
        rowdata[d[0]] = []
    rowdata[d[0]].append(d[1])

dp = [ [ (1, 0), (1, 0) ] ]
start = 0
if rows[0] == 1:
    #1+' '
    #dp[0] = [   (rowdata[1][-1], rowdata[1][-1] - 1 ) ,    (rowdata[1][0], 2 * rowdata[1][-1] - rowdata[1][0] - 1) ]
    dp[0] = [   (rowdata[1][-1], rowdata[1][-1] - 1 ) ,    (1, inf) ]
    start = 1

lnr = len(rows)
for i in range(start, lnr):
    row = rowdata[rows[i]]
    # ldp = dp[-1]
    LR = (0,inf)
    for f in range(4):
        ldp = dp[-1][f//2]
        am = ldp[1]
        d = nearch[ldp[0]][f%2]
        am += abs(ldp[0] - d)
        am += abs(d - row[0])
        am += row[-1] - row[0]

        if am < LR[1]:
            LR = (row[-1], am)

    RL = (0,inf)
    for f in range(4):
        ldp = dp[-1][f//2]
        am = ldp[1]
        d = nearch[ldp[0]][f%2]
        am += abs(ldp[0] - d)
        am += abs(d - row[-1])
        am += row[-1] - row[0]

        if am < RL[1]:
            RL = (row[0], am)
    dp.append([LR, RL])

# print(rows)
# print(rowdata)
# print(dp)

print(min(dp[-1][0][1], dp[-1][1][1]) + rows[-1] - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1202/A:
You are given two binary strings $x$ and $y$, which are binary representations of some two integers (let's denote these integers as $f(x)$ and $f(y)$). You can choose any integer $k \ge 0$, calculate the expression $s_k = f(x) + f(y) \cdot 2^k$ and write the binary representation of $s_k$ in reverse order (let's denote it as $rev_k$). For example, let $x = 1010$ and $y = 11$; you've chosen $k = 1$ and, since $2^1 = 10_2$, so $s_k = 1010_2 + 11_2 \cdot 10_2 = 10000_2$ and $rev_k = 00001$.

For given $x$ and $y$, you need to choose such $k$ that $rev_k$ is lexicographically minimal (read notes if you don't know what does "lexicographically" means).

It's guaranteed that, with given constraints, $k$ exists and is finite.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of queries.

Next $2T$ lines contain a description of queries: two lines per query. The first line contains one binary string $x$, consisting of no more than $10^5$ characters. Each character is either 0 or 1.

The second line contains one binary string $y$, consisting of no more than $10^5$ characters. Each character is either 0 or 1.

It's guaranteed, that $1 \le f(y) \le f(x)$ (where $f(x)$ is the integer represented by $x$, and $f(y)$ is the integer represented by $y$), both representations don't have any leading zeroes, the total length of $x$ over all queries doesn't exceed $10^5$, and the total length of $y$ over all queries doesn't exceed $10^5$.

-----Output-----

Print $T$ integers (one per query). For each query print such $k$ that $rev_k$ is lexicographically minimal.

-----Example-----
Input
4
1010
11
10001
110
1
1
1010101010101
11110000

Output
1
3
0
0

-----Note-----

The first query was described in the legend.

In the second query, it's optimal to choose $k = 3$. The $2^3 = 1000_2$ so $s_3 = 10001_2 + 110_2 \cdot 1000_2 = 10001 + 110000 = 1000001$ and $rev_3 = 1000001$. For example, if $k = 0$, then $s_0 = 10111$ and $rev_0 = 11101$, but $rev_3 = 1000001$ is lexicographically...

I tried it in Python, but could not do it. Can you solve it?

t = int(input())
for i in range(t):
    x = input()
    y = input()
    num = y.rfind("1")
    if num != -1:
        if x.rfind("1") == -1:
            print(0)
        else:
            ans = 0
            for i in range(len(x) - len(y) + num,-1,-1):
                if x[i] == "1":
                    ans = len(x) - len(y) + num - i
                    break
            print(ans)
    else:
        print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/1202/B:
Suppose you have a special $x$-$y$-counter. This counter can store some value as a decimal number; at first, the counter has value $0$.

The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $x$ or $y$ to its value. So all sequences this counter generates are starting from $0$. For example, a $4$-$2$-counter can act as follows:  it prints $0$, and adds $4$ to its value, so the current value is $4$, and the output is $0$;  it prints $4$, and adds $4$ to its value, so the current value is $8$, and the output is $04$;  it prints $8$, and adds $4$ to its value, so the current value is $12$, and the output is $048$;  it prints $2$, and adds $2$ to its value, so the current value is $14$, and the output is $0482$;  it prints $4$, and adds $4$ to its value, so the current value is $18$, and the output is $04824$.

This is only one of the possible outputs; for example, the same counter could generate $0246802468024$ as the output, if we chose to add $2$ during each step.

You wrote down a printed sequence from one of such $x$-$y$-counters. But the sequence was corrupted and several elements from the sequence could be erased.

Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $s$ — the remaining data of the sequence.

For all $0 \le x, y < 10$, calculate the minimum number of digits you have to insert in the string $s$ to make it a possible output of the $x$-$y$-counter. Note that you can't change the order of digits in string $s$ or erase any of them; only insertions are allowed.

-----Input-----

The first line contains a single string $s$ ($1 \le |s| \le 2 \cdot 10^6$, $s_i \in \{\text{0} - \text{9}\}$) — the remaining data you have. It's guaranteed that $s_1 = 0$.

-----Output-----

Print a $10 \times 10$ matrix, where the $j$-th integer ($0$-indexed) on the $i$-th line ($0$-indexed too) is equal to the minimum number of digits you have to insert in the string $s$ to make it a possible...

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin
from sys import setrecursionlimit as SRL

SRL(10 ** 7)
rd = stdin.readline
rrd = lambda: list(map(int, rd().strip().split()))

s = str(rd().strip())

ans = [[0] * 11 for _j in range(11)]

ddp = [[[100000] * 11 for _k in range(11)] for kk in range(11)]

tt = [0] * 11

for i in range(10):
    for j in range(10):
        for u in range(11):
            for v in range(11):
                k = (i*u + j*v) % 10
                ddp[i][j][k] = min(ddp[i][j][k], max(0,u+v-1))
                if k == 0 and (u!=0 or v!=0):
                    if u == 0 and v == 0:
                        print(u,v)
                    ddp[i][j][10] = min(ddp[i][j][10], max(0, u + v - 1))

pre = 0
for i in range(1, len(s)):
    t = ((int(s[i]) + 10) - pre) % 10
    if t == 0:
        t = 10
    tt[t] += 1
    pre = int(s[i])

for i in range(10):
    asi = ""
    for j in range(10):
        for k in range(11):
            if tt[k] and ddp[i][j][k] >= 80000:
                ans[i][j] = -1
                break
            ans[i][j] += tt[k] * ddp[i][j][k]
        asi = asi + str(ans[i][j]) + ' '
    print(asi)


I found an interesting problem on https://codeforces.com/problemset/problem/1202/D:
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

You are given an integer $n$.

You have to find a sequence $s$ consisting of digits $\{1, 3, 7\}$ such that it has exactly $n$ subsequences equal to $1337$.

For example, sequence $337133377$ has $6$ subsequences equal to $1337$:   $337\underline{1}3\underline{3}\underline{3}7\underline{7}$ (you can remove the second and fifth characters);  $337\underline{1}\underline{3}3\underline{3}7\underline{7}$ (you can remove the third and fifth characters);  $337\underline{1}\underline{3}\underline{3}37\underline{7}$ (you can remove the fourth and fifth characters);  $337\underline{1}3\underline{3}\underline{3}\underline{7}7$ (you can remove the second and sixth characters);  $337\underline{1}\underline{3}3\underline{3}\underline{7}7$ (you can remove the third and sixth characters);  $337\underline{1}\underline{3}\underline{3}3\underline{7}7$ (you can remove the fourth and sixth characters).

Note that the length of the sequence $s$ must not exceed $10^5$.

You have to answer $t$ independent queries.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 10$) — the number of queries.

Next $t$ lines contains a description of queries: the $i$-th line contains one integer $n_i$ ($1 \le n_i \le 10^9$).

-----Output-----

For the $i$-th query print one string $s_i$ ($1 \le |s_i| \le 10^5$) consisting of digits $\{1, 3, 7\}$. String $s_i$ must have exactly $n_i$ subsequences $1337$. If there are multiple such strings, print any of them.

-----Example-----
Input
2
6
1

Output
113337
1337

I tried it in Python, but could not do it. Can you solve it?

import sys
import math
input = sys.stdin.readline

arr=[]
for i in range(1,100000):
	arr.append(i*(i+1)//2)

def bs(l, r, x):
	if r>=l:
		mid = l + (r-l)//2
		if arr[mid]<=x and arr[mid+1]>x:
			return mid

		elif arr[mid]>x:
			return bs(l, mid-1, x)

		else:
			return bs(mid+1, r, x)

t=int(input())
for i in range(t):
	n=int(input())

	d=bs(0,len(arr)-1,n)
	diff=n-arr[d]
	#print(d,diff)

	ans=["1","3","3"]
	for j in range(diff):
		ans.append("7")
	for j in range(d):
		ans.append("3")
	ans.append("7")

	print(''.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1202/E:
You are given a string $t$ and $n$ strings $s_1, s_2, \dots, s_n$. All strings consist of lowercase Latin letters.

Let $f(t, s)$ be the number of occurences of string $s$ in string $t$. For example, $f('\text{aaabacaa}', '\text{aa}') = 3$, and $f('\text{ababa}', '\text{aba}') = 2$.

Calculate the value of $\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$, where $s + t$ is the concatenation of strings $s$ and $t$. Note that if there are two pairs $i_1$, $j_1$ and $i_2$, $j_2$ such that $s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}$, you should include both $f(t, s_{i_1} + s_{j_1})$ and $f(t, s_{i_2} + s_{j_2})$ in answer.

-----Input-----

The first line contains string $t$ ($1 \le |t| \le 2 \cdot 10^5$).

The second line contains integer $n$ ($1 \le n \le 2 \cdot 10^5$).

Each of next $n$ lines contains string $s_i$ ($1 \le |s_i| \le 2 \cdot 10^5$).

It is guaranteed that $\sum\limits_{i=1}^{n} |s_i| \le 2 \cdot 10^5$. All strings consist of lowercase English letters.

-----Output-----

Print one integer — the value of $\sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j)$.

-----Examples-----
Input
aaabacaa
2
a
aa

Output
5

Input
aaabacaa
4
a
a
a
b

Output
33

I tried it in Python, but could not do it. Can you solve it?

class Node(object):
    def __init__(self):
        super(Node, self).__init__()
        self.next = [-1] * 26
        self.trans = []
        self.matches = 0
        self.leaf = 0
        self.link = 0

class AhoCorasick(object):
    def __init__(self):
        super(AhoCorasick, self).__init__()
        self.T = [Node()]
        self.T[0].link = 0

    def insert_trie(self, s):
        v = 0
        for i in range(len(s)):
            c = ord(s[i]) - ord('a')
            if(self.T[v].next[c] == -1):
                self.T[v].trans.append(c)
                self.T[v].next[c] = len(self.T)
                self.T.append(Node())
            v = self.T[v].next[c]
        self.T[v].leaf += 1
        self.T[v].matches += 1

    def set_suffix_link(self, S):
        Q = []
        for j in range(len(S)):
            Q.append((j, 0, 0, 0))
            #string index, index in string, state, suff state,
        i = 0
        while(i < len(Q)):
            j,ind,v,suff = Q[i]
            i += 1
            c = ord(S[j][ind]) - ord('a')
            if(ind>0):
                while(suff>0 and self.T[suff].next[c]==-1):
                    suff = self.T[suff].link
                if(self.T[suff].next[c] != -1):
                    suff = self.T[suff].next[c]
            v = self.T[v].next[c]
            self.T[v].link = suff
            if(ind+1 < len(S[j])):
                Q.append((j,ind+1,v,suff))

    def set_matches(self):
        i = 0
        Q = [0]
        while(i < len(Q)):
            v = Q[i]
            self.T[v].matches = self.T[v].leaf + self.T[self.T[v].link].matches
            for c in self.T[v].trans:
                Q.append(self.T[v].next[c])
            i += 1

    def build(self, S):
        for i in range(len(S)):
            self.insert_trie(S[i])
        self.set_suffix_link(S)
        #self.printTree()
        self.set_matches()

    def get(self, s):
        v = 0
        matches = []
        for i in range(len(s)):
            c = ord(s[i]) - ord('a')
            while(v>0 and...


I found an interesting problem on https://codeforces.com/problemset/problem/1202/F:
You are given $a$ uppercase Latin letters 'A' and $b$ letters 'B'.

The period of the string is the smallest such positive integer $k$ that $s_i = s_{i~mod~k}$ ($0$-indexed) for each $i$. Note that this implies that $k$ won't always divide $a+b = |s|$.

For example, the period of string "ABAABAA" is $3$, the period of "AAAA" is $1$, and the period of "AABBB" is $5$.

Find the number of different periods over all possible strings with $a$ letters 'A' and $b$ letters 'B'.

-----Input-----

The first line contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$) — the number of letters 'A' and 'B', respectively.

-----Output-----

Print the number of different periods over all possible strings with $a$ letters 'A' and $b$ letters 'B'.

-----Examples-----
Input
2 4

Output
4

Input
5 3

Output
5

-----Note-----

All the possible periods for the first example:   $3$ "BBABBA"  $4$ "BBAABB"  $5$ "BBBAAB"  $6$ "AABBBB"

All the possible periods for the second example:   $3$ "BAABAABA"  $5$ "BAABABAA"  $6$ "BABAAABA"  $7$ "BAABAAAB"  $8$ "AAAAABBB"

Note that these are not the only possible strings for the given periods.

I tried it in Python, but could not do it. Can you solve it?

import math
a,b= list(map(int,input().split()))
n=a+b
ans,l=0,1
while l<=n:
    g= n//l
    if a<g or b<g:
        l= (n//g) +1
        continue
    r= n//g
    a_low = (a+g)//(g+1)
    a_high = a//g
    b_low=(b+g)//(g+1)
    b_high = b//g
    if (a_low <= a_high and b_low <= b_high):
        ans += max(0,min(r,a_high+b_high)- max(l,a_low +b_low)+1)

    l=r+1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1203/A:
There are $n$ students standing in a circle in some order. The index of the $i$-th student is $p_i$. It is guaranteed that all indices of students are distinct integers from $1$ to $n$ (i. e. they form a permutation).

Students want to start a round dance. A clockwise round dance can be started if the student $2$ comes right after the student $1$ in clockwise order (there are no students between them), the student $3$ comes right after the student $2$ in clockwise order, and so on, and the student $n$ comes right after the student $n - 1$ in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student $i$ should be right after the student $i - 1$ in counterclockwise order (this condition should be met for every $i$ from $2$ to $n$).

For example, if the indices of students listed in clockwise order are $[2, 3, 4, 5, 1]$, then they can start a clockwise round dance. If the students have indices $[3, 2, 1, 4]$ in clockwise order, then they can start a counterclockwise round dance.

Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle.

You have to answer $q$ independent queries.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 200$) — the number of queries. Then $q$ queries follow.

The first line of the query contains one integer $n$ ($1 \le n \le 200$) — the number of students.

The second line of the query contains a permutation of indices $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the index of the $i$-th student (in clockwise order). It is guaranteed that all $p_i$ are distinct integers from $1$ to $n$ (i. e. they form a permutation).

-----Output-----

For each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO".

-----Example-----
Input
5
4
1...

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
for _ in range(n):
	_ = int(input())
	*l, = map(int, input().split())
	ans = False
	for i in range(len(l)-1):
		if l[i] == len(l):
			if not l[i+1] == 1:
				break
		else:
			if not l[i] + 1 == l[i+1]:
				break
	else:
		ans = True
	for i in range(len(l)-1):
		if l[i] == 1:
			if not l[i+1] == len(l):
				break
		else:
			if not l[i] - 1 == l[i+1]:
				break
	else:
		ans = True
	if ans:
		print("YES")
	else:
		print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1203/B:
You are given $4n$ sticks, the length of the $i$-th stick is $a_i$.

You have to create $n$ rectangles, each rectangle will consist of exactly $4$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.

You want to all rectangles to have equal area. The area of the rectangle with sides $a$ and $b$ is $a \cdot b$.

Your task is to say if it is possible to create exactly $n$ rectangles of equal area or not.

You have to answer $q$ independent queries.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries. Then $q$ queries follow.

The first line of the query contains one integer $n$ ($1 \le n \le 100$) — the number of rectangles.

The second line of the query contains $4n$ integers $a_1, a_2, \dots, a_{4n}$ ($1 \le a_i \le 10^4$), where $a_i$ is the length of the $i$-th stick.

-----Output-----

For each query print the answer to it. If it is impossible to create exactly $n$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES".

-----Example-----
Input
5
1
1 1 10 10
2
10 5 2 10 1 1 2 5
2
10 5 1 10 5 1 1 1
2
1 1 1 1 1 1 1 1
1
10000 10000 10000 10000

Output
YES
YES
NO
YES
YES

I tried it in Python, but could not do it. Can you solve it?

Q = int(input())
for q in range(Q):
    N = int(input())
    A = sorted([int(a) for a in input().split()])
    S = A[0] * A[-1]
    i, j = 0, 4*N-1
    for _ in range(N):
        if not(A[i] == A[i+1] and A[j] == A[j-1] and A[i] * A[j] == S):
            print("NO")
            break
        i += 2
        j -= 2
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1203/C:
You are given an array $a$ consisting of $n$ integers.

Your task is to say the number of such positive integers $x$ such that $x$ divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.

For example, if the array $a$ will be $[2, 4, 6, 2, 10]$, then $1$ and $2$ divide each number from the array (so the answer for this test is $2$).

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 4 \cdot 10^5$) — the number of elements in $a$.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{12}$), where $a_i$ is the $i$-th element of $a$.

-----Output-----

Print one integer — the number of such positive integers $x$ such that $x$ divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array).

-----Examples-----
Input
5
1 2 3 4 5

Output
1

Input
6
6 90 12 18 30 18

Output
4

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
A = [int(i) for i in input().split()]

def gcd(a, b):
    if b==0:
        return a
    return gcd(b, a%b)

g = A[0]

for i in A:
    g = gcd(g, i)

fct = []

for i in range(1, g+1):
    if i*i > g:
        break
    if g%i == 0:
        fct.append(i)
        fct.append(g//i)

print(len(set(fct)))


I found an interesting problem on https://codeforces.com/problemset/problem/1203/D1:
The only difference between easy and hard versions is the length of the string.

You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$).

For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".

You want to remove some substring (contiguous subsequence) from $s$ of maximum possible length such that after removing this substring $t$ will remain a subsequence of $s$.

If you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$).

Your task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.

-----Input-----

The first line of the input contains one string $s$ consisting of at least $1$ and at most $200$ lowercase Latin letters.

The second line of the input contains one string $t$ consisting of at least $1$ and at most $200$ lowercase Latin letters.

It is guaranteed that $t$ is a subsequence of $s$.

-----Output-----

Print one integer — the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.

-----Examples-----
Input
bbaba
bb

Output
3

Input
baaba
ab

Output
2

Input
abcde
abcde

Output
0

Input
asdfasdf
fasd

Output
3

I tried it in Python, but could not do it. Can you solve it?

s = input()
t = input()
n = len(s)

ans = 0
for i in range(n):
    for j in range(i, n):
        st = s[ : i] + s[j+1 :]
        #print(st)

        cur, ok = 0, 0

        for ch in st:
            if ch == t[cur]:
                cur += 1
            if cur == len(t):
                ok = 1
                break

        if ok == 1:
            ans = max(ans, len(s) - len(st))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1203/D2:
The only difference between easy and hard versions is the length of the string.

You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$).

For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".

You want to remove some substring (contiguous subsequence) from $s$ of maximum possible length such that after removing this substring $t$ will remain a subsequence of $s$.

If you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$).

Your task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.

-----Input-----

The first line of the input contains one string $s$ consisting of at least $1$ and at most $2 \cdot 10^5$ lowercase Latin letters.

The second line of the input contains one string $t$ consisting of at least $1$ and at most $2 \cdot 10^5$ lowercase Latin letters.

It is guaranteed that $t$ is a subsequence of $s$.

-----Output-----

Print one integer — the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.

-----Examples-----
Input
bbaba
bb

Output
3

Input
baaba
ab

Output
2

Input
abcde
abcde

Output
0

Input
asdfasdf
fasd

Output
3

I tried it in Python, but could not do it. Can you solve it?

s = input()
t = input()

pos = [[-1, -1] for i in range(len(t))]

ptr = 0
for i,c in enumerate(t):
    while s[ptr] != c:
        ptr += 1
    pos[i][0] = ptr
    ptr += 1

ptr = len(s) - 1
for i in range(len(t)-1, -1, -1):
    c = t[i]
    while s[ptr] != c:
        ptr -= 1
    pos[i][1] = ptr
    ptr -= 1

best = max(pos[0][1], len(s)-pos[-1][0]-1)
for i in range(1, len(pos)):
    best = max(best, pos[i][1] - pos[i-1][0] - 1)

print(best)


I found an interesting problem on https://codeforces.com/problemset/problem/1203/E:
There are $n$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.

It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).

Write a program that for given current values $a_i$ will find the maximum possible number of boxers in a team.

It is possible that after some change the weight of some boxer is $150001$ (but no more).

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 150000$) — the number of boxers. The next line contains $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le 150000$) is the weight of the $i$-th boxer.

-----Output-----

Print a single integer — the maximum possible number of people in a team.

-----Examples-----
Input
4
3 2 4 1

Output
4

Input
6
1 1 1 4 4 4

Output
5

-----Note-----

In the first example, boxers should not change their weights — you can just make a team out of all of them.

In the second example, one boxer with a weight of $1$ can be increased by one (get the weight of $2$), one boxer with a weight of $4$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $3$ and $5$, respectively). Thus, you can get a team consisting of boxers with weights of $5, 4, 3, 2, 1$.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
res = prev = 0
for e in sorted(map(int, input().split())):
    if e < prev: continue
    res += 1
    if e == prev:
        e += 1
    if e - 1 > prev:
        e -= 1
    prev = e
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1203/F1:
The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.

Polycarp is a very famous freelancer. His current rating is $r$ units.

Some very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.

Is it possible to complete all the projects? Formally, write a program to check if such an order of the projects exists, that Polycarp has enough rating before starting each project, and he has non-negative rating after completing each project.

In other words, you have to check that there exists such an order of projects in which Polycarp will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.

-----Input-----

The first line of the input contains two integers $n$ and $r$ ($1 \le n \le 100, 1 \le r \le 30000$) — the number of projects and the initial rating of Polycarp, respectively.

The next $n$ lines contain projects, one per line. The $i$-th project is represented as a pair of integers $a_i$ and $b_i$ ($1 \le a_i \le 30000$, $-300 \le b_i \le 300$) — the rating required to complete the $i$-th project and the rating change after the project completion.

-----Output-----

Print "YES" or "NO".

-----Examples-----
Input
3 4
4 6
10 -2
8 -1

Output
YES

Input
3 5
4 -5
4 -2
1 3

Output
YES

Input
4 4
5 2
5 -3
2 1
4 -2

Output
YES

Input
3 10
10 0
10 -10
30 0

Output
NO

-----Note-----

In the first example, the possible order is: $1, 2, 3$.

In the second example, the possible order is: $2, 3, 1$.

In the third example, the possible order is: $3, 1, 4, 2$.

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline
n,r=list(map(int,input().split()))
ABP,ABN=[],[]
for i in range(n):
  a,b=list(map(int,input().split()))
  if b>=0:
    ABP.append([a,b])
  else:
    ABN.append([a,b])
ABP.sort(key=lambda x:(x[0],x[1]))
chk=True
for i in range(len(ABP)):
  if ABP[i][0]>r:
    chk=False
  else:
    r+=ABP[i][1]
if chk==False:
  print("NO")
else:
  ABN.sort(key=lambda x:(x[0]+x[1],x[0]),reverse=True)
  for i in range(len(ABN)):
    a,b=ABN[i]
    if r<a:
      chk=False
    else:
      r+=b
  if chk==False or r<0:
    print("NO")
  else:
    print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1203/F2:
The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.

Polycarp is a very famous freelancer. His current rating is $r$ units.

Some very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.

Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether.

To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.

Your task is to calculate the maximum possible size of such subset of projects.

-----Input-----

The first line of the input contains two integers $n$ and $r$ ($1 \le n \le 100, 1 \le r \le 30000$) — the number of projects and the initial rating of Polycarp, respectively.

The next $n$ lines contain projects, one per line. The $i$-th project is represented as a pair of integers $a_i$ and $b_i$ ($1 \le a_i \le 30000$, $-300 \le b_i \le 300$) — the rating required to complete the $i$-th project and the rating change after the project completion.

-----Output-----

Print one integer — the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose.

-----Examples-----
Input
3 4
4 6
10 -2
8 -1

Output
3

Input
5 20
45 -6
34 -15
10 34
1 27
40 -45

Output
5

Input
3 2
300 -300
1 299
1 123

Output
3

I tried it in Python, but could not do it. Can you solve it?

n, r = map(int, input().split())

pt = []
nt = []
r2 = r
result = 0

for _ in range(n):
    a, b = map(int, input().split())
    r2 += b
    if b >= 0:
        pt.append((a, b))
    else:
        nt.append((a, b))

pt.sort()
nt.sort(key=lambda t: t[1]+t[0], reverse=True)

for a, b in pt:
    if r < a:
        break
    result += 1
    r += b

k = len(nt)
ws = [[0]*(k+1) for i in range(r+1)]

for i in range(1, k+1):
    for w in range(1, r+1):
        a, b = nt[i-1]
        if w+b >= 0 and a <= r and ws[r-a][i-1] >= ws[w][i-1]:
            ws[w][i] = max(ws[w][i-1], 1+ws[w+b][i-1])
        else:
            ws[w][i] = ws[w][i-1]

result += ws[r][k]
'''
print(*enumerate(nt))
print(r, k)
print(*enumerate(ws), sep='\n')
'''
print(result)


I found an interesting problem on https://codeforces.com/problemset/problem/1204/A:
In the city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \geq 0$. Team BowWow has arrived at the station at the time $s$ and it is trying to count how many trains have they missed; in other words, the number of trains that have departed strictly before time $s$. For example if $s = 20$, then they missed trains which have departed at $1$, $4$ and $16$. As you are the only one who knows the time, help them!

Note that the number $s$ will be given you in a binary representation without leading zeroes.

-----Input-----

The first line contains a single binary number $s$ ($0 \leq s < 2^{100}$) without leading zeroes.

-----Output-----

Output a single number — the number of trains which have departed strictly before the time $s$.

-----Examples-----
Input
100000000

Output
4

Input
101

Output
2

Input
10100

Output
3

-----Note-----

In the first example $100000000_2 = 256_{10}$, missed trains have departed at $1$, $4$, $16$ and $64$.

In the second example $101_2 = 5_{10}$, trains have departed at $1$ and $4$.

The third example is explained in the statements.

I tried it in Python, but could not do it. Can you solve it?

i, k = 0, int(input(), 2)
while 4 ** i < k:
	i += 1
print(i)


I found an interesting problem on https://codeforces.com/problemset/problem/1204/B:
Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it:

 The number of different numbers in the array is not less than $l$ and is not greater than $r$;

 For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there is a number $\dfrac{a_i}{2}$ in the array.

For example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\frac{16}{2} = 8$.

According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.

-----Input-----

The only input line contains three integers $n$, $l$ and $r$ ($1 \leq n \leq 1\,000$, $1 \leq l \leq r \leq \min(n, 20)$) — an array's size, the minimal number and the maximal number of distinct elements in an array.

-----Output-----

Output two numbers — the minimal and the maximal possible sums of all elements in an array.

-----Examples-----
Input
4 2 2

Output
5 7

Input
5 1 5

Output
5 31

-----Note-----

In the first example, an array could be the one of the following: $[1,1,1,2]$, $[1,1,2,2]$ or $[1,2,2,2]$. In the first case the minimal sum is reached and in the last case the maximal sum is reached.

In the second example, the minimal sum is reached at the array $[1,1,1,1,1]$, and the maximal one is reached at the array $[1,2,4,8,16]$.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/1204/C:
The main characters have been omitted to be short.

You are given a directed unweighted graph without loops with $n$ vertexes and a path in it (that path is not necessary simple) given by a sequence $p_1, p_2, \ldots, p_m$ of $m$ vertexes; for each $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.

Define the sequence $v_1, v_2, \ldots, v_k$ of $k$ vertexes as good, if $v$ is a subsequence of $p$, $v_1 = p_1$, $v_k = p_m$, and $p$ is one of the shortest paths passing through the vertexes $v_1$, $\ldots$, $v_k$ in that order.

A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $p$ is good but your task is to find the shortest good subsequence.

If there are multiple shortest good subsequences, output any of them.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of vertexes in a graph.

The next $n$ lines define the graph by an adjacency matrix: the $j$-th character in the $i$-st line is equal to $1$ if there is an arc from vertex $i$ to the vertex $j$ else it is equal to $0$. It is guaranteed that the graph doesn't contain loops.

The next line contains a single integer $m$ ($2 \le m \le 10^6$) — the number of vertexes in the path.

The next line contains $m$ integers $p_1, p_2, \ldots, p_m$ ($1 \le p_i \le n$) — the sequence of vertexes in the path. It is guaranteed that for any $1 \leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.

-----Output-----

In the first line output a single integer $k$ ($2 \leq k \leq m$) — the length of the shortest good subsequence. In the second line output $k$ integers $v_1$, $\ldots$, $v_k$ ($1 \leq v_i \leq n$) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.

-----Examples-----
Input
4
0110
0010
0001
1000
4
1 2 3 4

Output
3
1 2 4
Input
4
0110
0010
1001
1000
20
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3...

I tried it in Python, but could not do it. Can you solve it?

from heapq import heapify, heappush as hpush, heappop as hpop
N = int(input())
X = [[] for _ in range(N)]
for i in range(N):
    s = input()
    for j in range(N):
        if s[j] == "1":
            X[i].append((j, 1))

def dijkstra(n, E, i0=0):
    h = [[0, i0]]
    D = [-1] * n
    done = [0] * n
    D[i0] = 0

    while h:
        d, i = hpop(h)
        done[i] = 1
        for j, w in E[i]:
            nd = d + w
            if D[j] < 0 or D[j] >= nd:
                if done[j] == 0:
                    hpush(h, [nd, j])
                    D[j] = nd
    return [d if d >= 0 else 1<<50 for d in D]

Y = []
for i in range(N):
    Y.append(dijkstra(N, X, i))

# print("Y =", Y)

M = int(input())
V = [int(a)-1 for a in input().split()]

a = 0
b = 1
t = Y[V[a]][V[b]]
ANS = [V[a]+1]
while b < M:
    if Y[V[a]][V[b]] < t:
        a = b-1
        ANS.append(V[a]+1)
        t = Y[V[a]][V[b]]
    elif b == M-1:
        break
    else:
        t += Y[V[b]][V[b+1]]
        b += 1
ANS.append(V[M-1]+1)
print(len(ANS))
print(*ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1204/D1:
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.

Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions:

 For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$;

 The number of zeroes in $t$ is the maximum possible.

A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$.

If there are multiple substrings which satisfy the conditions, output any.

-----Input-----

The first line contains a binary string of length not more than $2\: 000$.

-----Output-----

Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.

-----Examples-----
Input
110

Output
010

Input
010

Output
010

Input
0001111

Output
0000000

Input
0111001100111011101000

Output
0011001100001011101000

-----Note-----

In the first example:

 For the substrings of the length $1$ the length of the longest non-decreasing subsequnce is $1$;  For $l = 1, r = 2$ the longest non-decreasing subsequnce of the substring $s_{1}s_{2}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{2}$ is $01$;  For $l = 1, r = 3$ the longest non-decreasing subsequnce of the substring $s_{1}s_{3}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{3}$ is $00$;  For $l = 2, r = 3$ the longest non-decreasing subsequnce of the substring $s_{2}s_{3}$ is $1$ and the longest non-decreasing subsequnce of the substring $t_{2}t_{3}$ is $1$;

The second example is similar to...

I tried it in Python, but could not do it. Can you solve it?

s=list(map(int,input()))
stack=[]
for i in range(len(s)):
    if s[i]==1:
        stack.append(i)
    elif len(stack)!=0:
        stack=stack[:-1]
for i in stack:
    s[i]=0
s=list(map(str,s))
print(''.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/1204/D2:
The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.

Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions: For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$; The number of zeroes in $t$ is the maximum possible.

A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$.

If there are multiple substrings which satisfy the conditions, output any.

-----Input-----

The first line contains a binary string of length not more than $10^5$.

-----Output-----

Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.

-----Examples-----
Input
110

Output
010

Input
010

Output
010

Input
0001111

Output
0000000

Input
0111001100111011101000

Output
0011001100001011101000

-----Note-----

In the first example:  For the substrings of the length $1$ the length of the longest non-decreasing subsequnce is $1$;  For $l = 1, r = 2$ the longest non-decreasing subsequnce of the substring $s_{1}s_{2}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{2}$ is $01$;  For $l = 1, r = 3$ the longest non-decreasing subsequnce of the substring $s_{1}s_{3}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{3}$ is $00$;  For $l = 2, r = 3$ the longest non-decreasing subsequnce of the substring $s_{2}s_{3}$ is $1$ and the longest non-decreasing subsequnce of the substring $t_{2}t_{3}$...

I tried it in Python, but could not do it. Can you solve it?

s = input()
n = len(s)
if n == 1:
	print(0)
elif n == 2:
	if s == "10":
		print("10")
	else:
		print("00")
else:
	s_lis = 0
	s_max = 0
	s_zero = 0
	t_zero = 0
	stack_01 = []
	t = []
	for i in range(n):
		t.append("0")
		t_zero += 1
		if s[i] == "0":
			s_zero += 1
		if i > 0 and s[i-1:i+1] == "10":
			t[i-1] = "1"
			t_zero -= 1
			stack_01.append(i-2)
		if s_max <= int(s[i]):
			s_lis += 1
			s_max = max(s_max, int(s[i]))
		if s_lis <= s_zero:
			s_lis = s_zero
			s_max = 0
		if s_lis < t_zero:
			#print(t_01)
			while t[stack_01[-1]] == "1" or s[stack_01[-1]] == "0" or t[stack_01[-1]-1] == "1":
				stack_01.pop()
			t[stack_01[-1]] = "1"
			t_zero -= 1
			stack_01[-1] -= 1
	print(*t, sep="")


I found an interesting problem on https://codeforces.com/problemset/problem/1204/E:
Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ elements are equal to $-1$. For each such array they counted its maximal prefix sum, probably an empty one which is equal to $0$ (in another words, if every nonempty prefix sum is less to zero, then it is considered equal to zero). Formally, denote as $f(a)$ the maximal prefix sum of an array $a_{1, \ldots ,l}$ of length $l \geq 0$. Then:

$$f(a) = \max (0, \smash{\displaystyle\max_{1 \leq i \leq l}} \sum_{j=1}^{i} a_j )$$

Now they want to count the sum of maximal prefix sums for each such an array and they are asking you to help. As this sum can be very large, output it modulo $998\: 244\: 853$.

-----Input-----

The only line contains two integers $n$ and $m$ ($0 \le n,m \le 2\,000$).

-----Output-----

Output the answer to the problem modulo $998\: 244\: 853$.

-----Examples-----
Input
0 2

Output
0

Input
2 0

Output
2

Input
2 2

Output
5

Input
2000 2000

Output
674532367

-----Note-----

In the first example the only possible array is [-1,-1], its maximal prefix sum is equal to $0$.

In the second example the only possible array is [1,1], its maximal prefix sum is equal to $2$.

There are $6$ possible arrays in the third example:

[1,1,-1,-1], f([1,1,-1,-1]) = 2

[1,-1,1,-1], f([1,-1,1,-1]) = 1

[1,-1,-1,1], f([1,-1,-1,1]) = 1

[-1,1,1,-1], f([-1,1,1,-1]) = 1

[-1,1,-1,1], f([-1,1,-1,1]) = 0

[-1,-1,1,1], f([-1,-1,1,1]) = 0

So the answer for the third example is $2+1+1+1+0+0 = 5$.

I tried it in Python, but could not do it. Can you solve it?

MOD = 998244853
MAXN = 4000

fact, inv_fact = [0] * (MAXN + 1), [0] * (MAXN + 1)
fact[0] = 1
for i in range(MAXN):
    fact[i + 1] = fact[i] * (i + 1) % MOD

inv_fact[-1] = pow(fact[-1], MOD - 2, MOD)
for i in reversed(list(range(MAXN))):
    inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD

def nCr_mod(n, r):
    res = 1
    while n or r:
        a, b = n % MOD, r % MOD
        if a < b:
            return 0
        res = res * fact[a] % MOD * inv_fact[b] % MOD * inv_fact[a - b] % MOD
        n //= MOD
        r //= MOD
    return res

n, m = list(map(int, input().split()))
k = max(n - m - 1, 0)
print(((k * nCr_mod(n + m, m) +
       sum(nCr_mod(n + m, m + i) for i in range(k + 1, n)) + min(1, n)) % MOD))


I found an interesting problem on https://codeforces.com/problemset/problem/1205/B:
You are given $n$ integer numbers $a_1, a_2, \dots, a_n$. Consider graph on $n$ nodes, in which nodes $i$, $j$ ($i\neq j$) are connected if and only if, $a_i$ AND $a_j\neq 0$, where AND denotes the bitwise AND operation.

Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.

-----Input-----

The first line contains one integer $n$ $(1 \le n \le 10^5)$ — number of numbers.

The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{18}$).

-----Output-----

If the graph doesn't have any cycles, output $-1$. Else output the length of the shortest cycle.

-----Examples-----
Input
4
3 6 28 9

Output
4
Input
5
5 12 9 16 48

Output
3
Input
4
1 2 4 8

Output
-1

-----Note-----

In the first example, the shortest cycle is $(9, 3, 6, 28)$.

In the second example, the shortest cycle is $(5, 12, 9)$.

The graph has no cycles in the third example.

I tried it in Python, but could not do it. Can you solve it?

from collections import Counter, deque

n = int(input())
arr = list([x for x in map(int, input().strip().split()) if x != 0])

'''
for i, a in enumerate(arr):
    for j, b in enumerate(arr):
        if a & b != 0 and i != j:
            print(i,j,a,b)
return
'''

c = Counter()

for each in arr:
    for b in range(0, 64):
        if (1 << b) & each != 0:
            c[b] += 1
            if c[b] >= 3:
                print(3)
                return

ans = 1234567

for idx, st in enumerate(arr):
    dists = {}
    q = deque()
    q.append((idx, -1))
    dists[idx] = 0

    while q:
        node, par = q[0]
        dist = dists[node]
        q.popleft()
        for idx2, v in enumerate(arr):
            if idx2 == par:
                continue
            if idx2 == node or (v & arr[node]) == 0:
                continue
            if idx2 in dists:
                candidate = dists[idx2] + dist + 1
                if candidate != 2:
                    ans = min(ans, candidate)
                continue
            dists[idx2] = dist + 1
            q.append((idx2, node))

if ans == 1234567:
    print(-1)
else:
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1206/A:
You are given an array $A$, consisting of $n$ positive integers $a_1, a_2, \dots, a_n$, and an array $B$, consisting of $m$ positive integers $b_1, b_2, \dots, b_m$.

Choose some element $a$ of $A$ and some element $b$ of $B$ such that $a+b$ doesn't belong to $A$ and doesn't belong to $B$.

For example, if $A = [2, 1, 7]$ and $B = [1, 3, 4]$, we can choose $1$ from $A$ and $4$ from $B$, as number $5 = 1 + 4$ doesn't belong to $A$ and doesn't belong to $B$. However, we can't choose $2$ from $A$ and $1$ from $B$, as $3 = 2 + 1$ belongs to $B$.

It can be shown that such a pair exists. If there are multiple answers, print any.

Choose and print any such two numbers.

-----Input-----

The first line contains one integer $n$ ($1\le n \le 100$) — the number of elements of $A$.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 200$) — the elements of $A$.

The third line contains one integer $m$ ($1\le m \le 100$) — the number of elements of $B$.

The fourth line contains $m$ different integers $b_1, b_2, \dots, b_m$ ($1 \le b_i \le 200$) — the elements of $B$.

It can be shown that the answer always exists.

-----Output-----

Output two numbers $a$ and $b$ such that $a$ belongs to $A$, $b$ belongs to $B$, but $a+b$ doesn't belong to nor $A$ neither $B$.

If there are multiple answers, print any.

-----Examples-----
Input
1
20
2
10 20

Output
20 20
Input
3
3 2 2
5
1 5 7 7 9

Output
3 1

Input
4
1 3 5 7
4
7 5 3 1

Output
1 1

-----Note-----

In the first example, we can choose $20$ from array $[20]$ and $20$ from array $[10, 20]$. Number $40 = 20 + 20$ doesn't belong to any of those arrays. However, it is possible to choose $10$ from the second array too.

In the second example, we can choose $3$ from array $[3, 2, 2]$ and $1$ from array $[1, 5, 7, 7, 9]$. Number $4 = 3 + 1$ doesn't belong to any of those arrays.

In the third example, we can choose $1$ from array $[1, 3, 5, 7]$ and $1$ from array $[7, 5, 3, 1]$. Number $2 = 1 + 1$ doesn't belong to any of those arrays.

I tried it in Python, but could not do it. Can you solve it?

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

n = int(input())
a = list(mp())
m = int(input())
b = list(mp())
print(max(a), max(b))


I found an interesting problem on https://codeforces.com/problemset/problem/1206/B:
You are given $n$ numbers $a_1, a_2, \dots, a_n$. With a cost of one coin you can perform the following operation:

Choose one of these numbers and add or subtract $1$ from it.

In particular, we can apply this operation to the same number several times.

We want to make the product of all these numbers equal to $1$, in other words, we want $a_1 \cdot a_2$ $\dots$ $\cdot a_n = 1$.

For example, for $n = 3$ and numbers $[1, -3, 0]$ we can make product equal to $1$ in $3$ coins: add $1$ to second element, add $1$ to second element again, subtract $1$ from third element, so that array becomes $[1, -1, -1]$. And $1\cdot (-1) \cdot (-1) = 1$.

What is the minimum cost we will have to pay to do that?

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of numbers.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$) — the numbers.

-----Output-----

Output a single number — the minimal number of coins you need to pay to make the product equal to $1$.

-----Examples-----
Input
2
-1 1

Output
2
Input
4
0 0 0 0

Output
4
Input
5
-5 -3 5 3 0

Output
13

-----Note-----

In the first example, you can change $1$ to $-1$ or $-1$ to $1$ in $2$ coins.

In the second example, you have to apply at least $4$ operations for the product not to be $0$.

In the third example, you can change $-5$ to $-1$ in $4$ coins, $-3$ to $-1$ in $2$ coins, $5$ to $1$ in $4$ coins, $3$ to $1$ in $2$ coins, $0$ to $1$ in $1$ coin.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
array = list(map(int, input().split()))
total = 0
minus = 0
zero = 0

for i in range(len(array)):
    if array[i] > 0:
        total += array[i] - 1
    elif array[i] < 0:
        minus += 1
        total += -1 - array[i]
    else:
        zero += 1
        total += 1

if minus % 2 and zero == 0:
    total += 2

print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/1207/A:
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet.

You have $b$ buns, $p$ beef patties and $f$ chicken cutlets in your restaurant. You can sell one hamburger for $h$ dollars and one chicken burger for $c$ dollars. Calculate the maximum profit you can achieve.

You have to answer $t$ independent queries.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) – the number of queries.

The first line of each query contains three integers $b$, $p$ and $f$ ($1 \le b, ~p, ~f \le 100$) — the number of buns, beef patties and chicken cutlets in your restaurant.

The second line of each query contains two integers $h$ and $c$ ($1 \le h, ~c \le 100$) — the hamburger and chicken burger prices in your restaurant.

-----Output-----

For each query print one integer — the maximum profit you can achieve.

-----Example-----
Input
3
15 2 3
5 10
7 5 2
10 12
1 100 100
100 100

Output
40
34
0

-----Note-----

In first query you have to sell two hamburgers and three chicken burgers. Your income is $2 \cdot 5 + 3 \cdot 10 = 40$.

In second query you have to ell one hamburgers and two chicken burgers. Your income is $1 \cdot 10 + 2 \cdot 12 = 34$.

In third query you can not create any type of burgers because because you have only one bun. So your income is zero.

I tried it in Python, but could not do it. Can you solve it?

import sys
from collections import defaultdict
input = lambda : sys.stdin.readline().rstrip()

for t in range(int(input())):
  b, p, f = list(map(int, input().split()))
  h, c = list(map(int, input().split()))

  if h >= c:
    beef = min((b//2), p)
    b -= beef * 2
    chicken = min((b//2), f)
    print(beef*h + chicken*c)
  else:
    chicken = min((b//2), f)
    b -= chicken * 2
    beef = min((b//2), p)
    print(beef*h + chicken*c)


I found an interesting problem on https://codeforces.com/problemset/problem/1207/B:
You are given two matrices $A$ and $B$. Each matrix contains exactly $n$ rows and $m$ columns. Each element of $A$ is either $0$ or $1$; each element of $B$ is initially $0$.

You may perform some operations with matrix $B$. During each operation, you choose any submatrix of $B$ having size $2 \times 2$, and replace every element in the chosen submatrix with $1$. In other words, you choose two integers $x$ and $y$ such that $1 \le x < n$ and $1 \le y < m$, and then set $B_{x, y}$, $B_{x, y + 1}$, $B_{x + 1, y}$ and $B_{x + 1, y + 1}$ to $1$.

Your goal is to make matrix $B$ equal to matrix $A$. Two matrices $A$ and $B$ are equal if and only if every element of matrix $A$ is equal to the corresponding element of matrix $B$.

Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $B$ equal to $A$. Note that you don't have to minimize the number of operations.

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \le n, m \le 50$).

Then $n$ lines follow, each containing $m$ integers. The $j$-th integer in the $i$-th line is $A_{i, j}$. Each integer is either $0$ or $1$.

-----Output-----

If it is impossible to make $B$ equal to $A$, print one integer $-1$.

Otherwise, print any sequence of operations that transforms $B$ into $A$ in the following format: the first line should contain one integer $k$ — the number of operations, and then $k$ lines should follow, each line containing two integers $x$ and $y$ for the corresponding operation (set $B_{x, y}$, $B_{x, y + 1}$, $B_{x + 1, y}$ and $B_{x + 1, y + 1}$ to $1$). The condition $0 \le k \le 2500$ should hold.

-----Examples-----
Input
3 3
1 1 1
1 1 1
0 1 1

Output
3
1 1
1 2
2 2

Input
3 3
1 0 1
1 0 1
0 0 0

Output
-1

Input
3 2
0 0
0 0
0 0

Output
0

-----Note-----

The sequence of operations in the first example: $\begin{matrix} 0 & 0 & 0 & & 1 & 1 & 0 & & 1 & 1 & 1 & & 1 & 1 & 1 \\ 0 & 0 & 0 & \rightarrow & 1 & 1 & 0 & \rightarrow & 1 & 1 & 1 & \rightarrow & 1 & 1 & 1 \\ 0 & 0...

I tried it in Python, but could not do it. Can you solve it?

n, m = list(map(int, input().split()))
mat = []
for i in range(n):
    mat.append(list(map(int, input().split())))

ans = [[0 for i in range(m)] for j in range(n)]
anslist = []
for i in range(n-1):
    for j in range(m-1):
        if mat[i][j] == 1 and mat[i][j+1] == 1 and mat[i+1][j] == 1 and mat[i+1][j+1]:
            for k in range(2):
                for l in range(2):
                    ans[i+k][j+l] = 1
            anslist.append([i+1, j+1])

if mat == ans:
    print(len(anslist))
    for i, j in anslist:
        print(i, j)
else:
    print(-1)