I found an interesting problem on https://codeforces.com/problemset/problem/1363/F:
You are given two strings $s$ and $t$, each of length $n$ and consisting of lowercase Latin alphabets. You want to make $s$ equal to $t$.

You can perform the following operation on $s$ any number of times to achieve it —   Choose any substring of $s$ and rotate it clockwise once, that is, if the selected substring is $s[l,l+1...r]$, then it becomes $s[r,l,l + 1 ... r - 1]$. All the remaining characters of $s$ stay in their position.

For example, on rotating the substring $[2,4]$ , string "abcde" becomes "adbce".

A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Find the minimum number of operations required to convert $s$ to $t$, or determine that it's impossible.

-----Input-----

The first line of the input contains a single integer $t$ $(1\leq t \leq 2000)$ — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ $(1\leq n \leq 2000)$ — the length of the strings.

The second and the third lines contain strings $s$ and $t$ respectively.

The sum of $n$ over all the test cases does not exceed $2000$.

-----Output-----

For each test case, output the minimum number of operations to convert $s$ to $t$. If it is not possible to convert $s$ to $t$, output $-1$ instead.

-----Example-----
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc

Output
0
1
1
2
1
-1

-----Note-----

For the $1$-st test case, since $s$ and $t$ are equal, you don't need to apply any operation.

For the $2$-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.

For the $3$-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.

For the $4$-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length $2$ beginning...

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

def read_int():
    return int(input())

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

t = read_int()
for case_num in range(t):
    n = read_int()
    cnt = [0 for i in range(26)]
    ps = [[0 for j in range(n + 1)] for i in range(26)]
    pt = [[0 for j in range(n + 1)] for i in range(26)]
    s = input()
    t = input()
    for i in range(n):
        ch = ord(s[i]) - ord('a')
        cnt[ch] += 1
        for j in range(26):
            ps[j][i + 1] = ps[j][i] + (1 if ch == j else 0)
    for i in range(n):
        ch = ord(t[i]) - ord('a')
        cnt[ch] -= 1
        for j in range(26):
            pt[j][i + 1] = pt[j][i] + (1 if ch == j else 0)
    ok = True
    for i in cnt:
        if i != 0:
            ok = False
            break
    if not ok:
        print(-1)
    else:
        r = n
        while r >= 1 and s[r - 1] == t[r - 1]:
            r -= 1
        inf = int(1e8)
        dp = [[0 if i == 0 else inf for j in range(
            r + 1)] for i in range(r + 1)]
        for i in range(1, r + 1):
            for j in range(i, r + 1):
                if s[i - 1] == t[j - 1]:
                    dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])
                ch = ord(t[j - 1]) - ord('a')
                if ps[ch][r] - ps[ch][i] > pt[ch][r] - pt[ch][j]:
                    dp[i][j] = min(dp[i][j], dp[i][j - 1])
                dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1)
        print(dp[r][r])


I found an interesting problem on https://codeforces.com/problemset/problem/1364/A:
Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements isn't divisible by $x$, or determine that such subarray doesn't exist.

An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

-----Input-----

The first line contains an integer $t$ $(1 \le t \le 5)$ — the number of test cases you need to solve. The description of the test cases follows.

The first line of each test case contains 2 integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^4$) — the number of elements in the array $a$ and the number that Ehab hates.

The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($0 \le a_i \le 10^4$) — the elements of the array $a$.

-----Output-----

For each testcase, print the length of the longest subarray whose sum isn't divisible by $x$. If there's no such subarray, print $-1$.

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

Output
2
3
-1

-----Note-----

In the first test case, the subarray $[2,3]$ has sum of elements $5$, which isn't divisible by $3$.

In the second test case, the sum of elements of the whole array is $6$, which isn't divisible by $4$.

In the third test case, all subarrays have an even sum, so the answer is $-1$.

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

from collections import *
from math import *

t = int(input())
for y in range(t):
	n,x = list(map(int,input().split()))
	a = list(map(int,input().split()))
	s = sum(a)
	if(s%x != 0):
		print(n)
		continue
	s = -1
	for i in range(n):
		if(a[i]%x != 0):
			s = i+1
			break
	if(s == -1):
		print(-1)
		continue
	e = -1
	for i in range(n-1,-1,-1):
		if(a[i]%x != 0):
			e = n-i
			break
	print(n-min(s,e))


I found an interesting problem on https://codeforces.com/problemset/problem/1364/C:
Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that:

  for each $i$ $(1 \le i \le n)$ $MEX(\{b_1$, $b_2$, $\ldots$, $b_i\})=a_i$.

The $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.

If such array doesn't exist, determine this.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^5$) — the length of the array $a$.

The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_n$ ($0 \le a_i \le i$) — the elements of the array $a$. It's guaranteed that $a_i \le a_{i+1}$ for $1\le i < n$.

-----Output-----

If there's no such array, print a single line containing $-1$.

Otherwise, print a single line containing $n$ integers $b_1$, $b_2$, $\ldots$, $b_n$ ($0 \le b_i \le 10^6$)

If there are multiple answers, print any.

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

Output
0 1 2
Input
4
0 0 0 2

Output
1 3 4 0
Input
3
1 1 3

Output
0 2 1

-----Note-----

In the second test case, other answers like $[1,1,1,0]$, for example, are valid.

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

from collections import deque
import sys

N = int(input())

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

jokers = deque()

B = [-1] * N
current = 0

for i, el in enumerate(A):
    jokers.append(i)
    if el != current:
        for j in range(el - current):
            if not jokers:
                print(-1)
                return
            p = jokers.pop()
            if A[p] == current + j:
                print(-1)
                return
            else:
                B[p] = current + j
        current = el

while jokers:
    current += 1
    p = jokers.pop()
    B[p] = current

print(' '.join(map(str, B)))


I found an interesting problem on https://codeforces.com/problemset/problem/1364/D:
Given a connected undirected graph with $n$ vertices and an integer $k$, you have to either:  either find an independent set that has exactly $\lceil\frac{k}{2}\rceil$ vertices. or find a simple cycle of length at most $k$.

An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.

I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.

-----Input-----

The first line contains three integers $n$, $m$, and $k$ ($3 \le k \le n \le 10^5$, $n-1 \le m \le 2 \cdot 10^5$) — the number of vertices and edges in the graph, and the parameter $k$ from the statement.

Each of the next $m$ lines contains two integers $u$ and $v$ ($1 \le u,v \le n$) that mean there's an edge between vertices $u$ and $v$. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.

-----Output-----

If you choose to solve the first problem, then on the first line print $1$, followed by a line containing $\lceil\frac{k}{2}\rceil$ distinct integers not exceeding $n$, the vertices in the desired independent set.

If you, however, choose to solve the second problem, then on the first line print $2$, followed by a line containing one integer, $c$, representing the length of the found cycle, followed by a line containing $c$ distinct integers not exceeding $n$, the vertices in the desired cycle, in the order they appear in the cycle.

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

Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4

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

Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5

Output
1
1 4 5

-----Note-----

In the first sample:

[Image]

Notice that printing the independent set $\{2,4\}$ is also OK, but printing the cycle $1-2-3-4$ isn't, because its length must be at most $3$.

In the second sample:

$N$

Notice that printing the independent set $\{1,3\}$ or printing the cycle...

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

import sys
input = sys.stdin.readline
from collections import deque

class Graph(object):
	"""docstring for Graph"""
	def __init__(self,n,d): # Number of nodes and d is True if directed
		self.n = n
		self.graph = [[] for i in range(n)]
		self.parent = [-1 for i in range(n)]
		self.directed = d

	def addEdge(self,x,y):
		self.graph[x].append(y)
		if not self.directed:
			self.graph[y].append(x)

	def bfs(self, root): # NORMAL BFS
		queue = [root]
		queue = deque(queue)
		vis = [0]*self.n
		while len(queue)!=0:
			element = queue.popleft()
			vis[element] = 1
			for i in self.graph[element]:
				if vis[i]==0:
					queue.append(i)
					self.parent[i] = element
					vis[i] = 1

	def dfs(self, root, ans): # Iterative DFS
		stack=[root]
		vis=[0]*self.n
		stack2=[]
		while len(stack)!=0: # INITIAL TRAVERSAL
			element = stack.pop()
			if vis[element]:
				continue
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i]==0:
					self.parent[i] = element
					stack.append(i)

		while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question
			element = stack2.pop()
			m = 0
			for i in self.graph[element]:
				if i!=self.parent[element]:
					m += ans[i]
			ans[element] = m
		return ans

	def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes
		self.bfs(source)
		path = [dest]
		while self.parent[path[-1]]!=-1:
			path.append(parent[path[-1]])
		return path[::-1]

	def ifcycle(self):
		queue = [0]
		vis = [0]*n
		queue = deque(queue)
		while len(queue)!=0:
			element = queue.popleft()
			vis[element] = 1
			for i in self.graph[element]:
				if vis[i]==1 and i!=self.parent[element]:
					s = i
					e = element
					path1 = [s]
					path2 = [e]
					while self.parent[s]!=-1:
						s = self.parent[s]
						path1.append(s)
					while self.parent[e]!=-1:
						e = self.parent[e]
						path2.append(e)
					for i in range(-1,max(-len(path1),-len(path2))-1,-1):
						if path1[i]!=path2[i]:
							return path1[0:i+1]+path2[i+1::-1]
				if...


I found an interesting problem on https://codeforces.com/problemset/problem/1365/B:
Ashish has $n$ elements arranged in a line.

These elements are represented by two integers $a_i$ — the value of the element and $b_i$ — the type of the element (there are only two possible types: $0$ and $1$). He wants to sort the elements in non-decreasing values of $a_i$.

He can perform the following operation any number of times:  Select any two elements $i$ and $j$ such that $b_i \ne b_j$ and swap them. That is, he can only swap two elements of different types in one move.

Tell him if he can sort the elements in non-decreasing values of $a_i$ after performing any number of operations.

-----Input-----

The first line contains one integer $t$ $(1 \le t \le 100)$ — the number of test cases. The description of the test cases follows.

The first line of each test case contains one integer $n$ $(1 \le n \le 500)$ — the size of the arrays.

The second line contains $n$ integers $a_i$ $(1 \le a_i \le 10^5)$  — the value of the $i$-th element.

The third line containts $n$ integers $b_i$ $(b_i \in \{0, 1\})$  — the type of the $i$-th element.

-----Output-----

For each test case, print "Yes" or "No" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value.

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

-----Example-----
Input
5
4
10 20 20 30
0 1 0 1
3
3 1 2
0 1 1
4
2 2 4 8
1 1 1 1
3
5 15 4
0 0 0
4
20 10 100 50
1 0 0 1

Output
Yes
Yes
Yes
No
Yes

-----Note-----

For the first case: The elements are already in sorted order.

For the second case: Ashish may first swap elements at positions $1$ and $2$, then swap elements at positions $2$ and $3$.

For the third case: The elements are already in sorted order.

For the fourth case: No swap operations may be performed as there is no pair of elements $i$ and $j$ such that $b_i \ne b_j$. The elements cannot be sorted.

For the fifth case: Ashish may swap elements at positions $3$ and $4$, then elements at positions $1$ and $2$.

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

t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    if 0 < sum(b) < len(b):
        print("Yes")
    else:
        if a == sorted(a):
            print("Yes")
        else:
            print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/1365/C:
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $n$. Let's call them $a$ and $b$.

Note that a permutation of $n$ elements is a sequence of numbers $a_1, a_2, \ldots, a_n$, in which every number from $1$ to $n$ appears exactly once.

The message can be decoded by an arrangement of sequence $a$ and $b$, such that the number of matching pairs of elements between them is maximum. A pair of elements $a_i$ and $b_j$ is said to match if:   $i = j$, that is, they are at the same index.  $a_i = b_j$

His two disciples are allowed to perform the following operation any number of times:   choose a number $k$ and cyclically shift one of the permutations to the left or right $k$ times.

A single cyclic shift to the left on any permutation $c$ is an operation that sets $c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $c$ is an operation that sets $c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$ simultaneously.

Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

-----Input-----

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

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

The third line contains $n$ integers $b_1$, $b_2$, ..., $b_n$ $(1 \le b_i \le n)$ — the elements of the second permutation.

-----Output-----

Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.

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

Output
5
Input
5
5 4 3 2 1
1 2 3 4 5

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

Output
2

-----Note-----

For the first case: $b$ can be shifted to the right by $k = 1$. The resulting...

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

from collections import Counter

n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]

aidx = [-1]*n
bidx = [-1]*n

for i, (ai, bi) in enumerate(zip(a, b)):
    aidx[ai-1] = i
    bidx[bi-1] = i

diffs = [(aidx[i] - bidx[i]) % n for i in range(n)]
print(max(Counter(diffs).values()))


I found an interesting problem on https://codeforces.com/problemset/problem/1365/D:
Vivek has encountered a problem. He has a maze that can be represented as an $n \times m$ grid. Each of the grid cells may represent the following:  Empty — '.'  Wall — '#'  Good person  — 'G'  Bad person — 'B'

The only escape from the maze is at cell $(n, m)$.

A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.

Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.

It is guaranteed that the cell $(n,m)$ is empty. Vivek can also block this cell.

-----Input-----

The first line contains one integer $t$ $(1 \le t \le 100)$ — the number of test cases. The description of the test cases follows.

The first line of each test case contains two integers $n$, $m$ $(1 \le n, m \le 50)$ — the number of rows and columns in the maze.

Each of the next $n$ lines contain $m$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.

-----Output-----

For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"

You may print every letter in any case (upper or lower).

-----Example-----
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.

Output
Yes
Yes
No
No
Yes
Yes

-----Note-----

For the first and second test cases, all conditions are already satisfied.

For the third test case, there is only one empty cell $(2,2)$, and if it is replaced with a wall then the good person at $(1,2)$ will not be able to escape.

For the fourth test case, the good person at...

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

import sys
input = sys.stdin.readline
t=int(input())
ans=[]
for _ in range(t):
	h,w=map(int,input().split())
	grid=[list(input()) for _ in range(h)]
	good=set()
	bad=set()
	delta=[(-1,0),(1,0),(0,1),(0,-1)]
	for i in range(h):
		for j in range(w):
			if grid[i][j]=="G":
				good.add((i,j))
			elif grid[i][j]=="B":
				bad.add((i,j))
	if not good:
		ans.append("Yes")
		continue
	flg=0
	for ci,cj in bad:
		for di,dj in delta:
			ni,nj=ci+di,cj+dj
			if 0<=ni<h and 0<=nj<w:
				if grid[ni][nj]==".":
					grid[ni][nj]="#"
				elif grid[ni][nj]=="G":
					flg=1
					break
		if flg:
			break
	if flg or grid[h-1][w-1]=="#":
		ans.append("No")
		continue
	q=[(h-1,w-1)]
	vis=[[0]*w for _ in range(h)]
	vis[-1][-1]=1
	while q:
		ci,cj=q.pop()
		for di,dj in delta:
			ni,nj=ci+di,cj+dj
			if 0<=ni<h and 0<=nj<w and grid[ni][nj]!="#" and not vis[ni][nj]:
				vis[ni][nj]=1
				q.append((ni,nj))
	if all(vis[i][j] for i,j in good):
		ans.append("Yes")
	else:
		ans.append("No")
print("\n".join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1365/E:
Ridhiman challenged Ashish to find the maximum valued subsequence of an array $a$ of size $n$ consisting of positive integers.

The value of a non-empty subsequence of $k$ elements of $a$ is defined as $\sum 2^i$ over all integers $i \ge 0$ such that at least $\max(1, k - 2)$ elements of the subsequence have the $i$-th bit set in their binary representation (value $x$ has the $i$-th bit set in its binary representation if $\lfloor \frac{x}{2^i} \rfloor \mod 2$ is equal to $1$).

Recall that $b$ is a subsequence of $a$, if $b$ can be obtained by deleting some(possibly zero) elements from $a$.

Help Ashish find the maximum value he can get by choosing some subsequence of $a$.

-----Input-----

The first line of the input consists of a single integer $n$ $(1 \le n \le 500)$ — the size of $a$.

The next line consists of $n$ space-separated integers — the elements of the array $(1 \le a_i \le 10^{18})$.

-----Output-----

Print a single integer — the maximum value Ashish can get by choosing some subsequence of $a$.

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

Output
3
Input
3
3 1 4

Output
7
Input
1
1

Output
1
Input
4
7 7 1 1

Output
7

-----Note-----

For the first test case, Ashish can pick the subsequence $\{{2, 3}\}$ of size $2$. The binary representation of $2$ is 10 and that of $3$ is 11. Since $\max(k - 2, 1)$ is equal to $1$, the value of the subsequence is $2^0 + 2^1$ (both $2$ and $3$ have $1$-st bit set in their binary representation and $3$ has $0$-th bit set in its binary representation). Note that he could also pick the subsequence $\{{3\}}$ or $\{{2, 1, 3\}}$.

For the second test case, Ashish can pick the subsequence $\{{3, 4\}}$ with value $7$.

For the third test case, Ashish can pick the subsequence $\{{1\}}$ with value $1$.

For the fourth test case, Ashish can pick the subsequence $\{{7, 7\}}$ with value $7$.

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

n = int(input())
a = list(map(int,input().split()))
wynik = 0
if n < 3:
	wyn = a[0]
	for i in range(1,n):
		wyn = wyn|a[i]
	print(wyn)
else:
	for i in range(n):
		for j in range(i+1,n):
			for k in range(j+1,n):
				wynik = max(wynik, (a[i]|a[j])|a[k])
	print(wynik)


I found an interesting problem on https://codeforces.com/problemset/problem/1365/F:
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.

Each test case consists of an integer $n$ and two arrays $a$ and $b$, of size $n$. If after some (possibly zero) operations described below, array $a$ can be transformed into array $b$, the input is said to be valid. Otherwise, it is invalid.

An operation on array $a$ is:   select an integer $k$ $(1 \le k \le \lfloor\frac{n}{2}\rfloor)$  swap the prefix of length $k$ with the suffix of length $k$

For example, if array $a$ initially is $\{1, 2, 3, 4, 5, 6\}$, after performing an operation with $k = 2$, it is transformed into $\{5, 6, 3, 4, 1, 2\}$.

Given the set of test cases, help them determine if each one is valid or invalid.

-----Input-----

The first line contains one integer $t$ $(1 \le t \le 500)$ — the number of test cases. The description of each test case is as follows.

The first line of each test case contains a single integer $n$ $(1 \le n \le 500)$ — the size of the arrays.

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

The third line of each test case contains $n$ integers $b_1$, $b_2$, ..., $b_n$ $(1 \le b_i \le 10^9)$ — elements of array $b$.

-----Output-----

For each test case, print "Yes" if the given input is valid. Otherwise print "No".

You may print the answer in any case.

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

Output
yes
yes
No
yes
No

-----Note-----

For the first test case, we can swap prefix $a[1:1]$ with suffix $a[2:2]$ to get $a=[2, 1]$.

For the second test case, $a$ is already equal to $b$.

For the third test case, it is impossible since we cannot obtain $3$ in $a$.

For the fourth test case, we can first swap prefix $a[1:1]$ with suffix $a[4:4]$ to obtain $a=[2, 2, 3, 1]$. Now we can swap prefix $a[1:2]$ with suffix $a[3:4]$ to obtain $a=[3, 1, 2, 2]$.

For the fifth test case, it is...

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

from collections import deque

def Hopcroft_Karp(adj, L):
    """
    Computes maximal matching in unweighted bipartite graph `adj`. Here `L` is
    a boolean array which gives the left part of the bipartite graph. If w is
    in adj[v], then precisely one of L[v], L[w] should be True.

    Returns (N, matching), where N is the cardinality of the matching, and
    matching is a list encoding the matched vertex (where a -1 indicates an
    unmatched vertex).
    """
    N = len(adj)
    matching = [-1 for _ in range(N)]

    while True:
        # If our matching changes, we need another iteration.
        extended = False

        # Do a BFS starting at all unmatched left nodes.
        sources = [v for v in range(N) if matching[v] == -1 and L[v]]

        # Keep track of your immediate predecessor in the BFS.
        # -1 means an unvisited node. Sources have themselves as predecessor.
        bfs_pred = [-1 for _ in range(N)]

        # Keep track of which BFS source started your subtree.
        # -1 means an unvisited node.
        bfs_source = [-1 for _ in range(N)]

        for v in sources:
            bfs_pred[v] = v
            bfs_source[v] = v

        queue = deque(sources)
        while len(queue) > 0:
            cur = queue.popleft()

            # If the node that started this subtree has been matched, stop growing the BFS.
            if matching[bfs_source[cur]] != -1:
                continue

            for nb in adj[cur]:
                if matching[nb] == -1:
                    # We have found an augmenting path.
                    # Use a clever loop to use the path to update the matching.
                    while nb != -1:
                        matching[nb], matching[cur], nb, cur = cur, nb, matching[cur], bfs_pred[cur]
                    extended = True
                    break
                else:
                    new = matching[nb]
                    if bfs_pred[new] == -1:
                       ...


I found an interesting problem on https://codeforces.com/problemset/problem/1366/A:
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.

Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $a$ sticks and $b$ diamonds?

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases.

The only line of each test case contains two integers $a$ and $b$ ($0 \le a, b \le 10^9$) — the number of sticks and the number of diamonds, respectively.

-----Output-----

For each test case print one integer — the maximum number of emeralds Polycarp can earn.

-----Example-----
Input
4
4 4
1000000000 0
7 15
8 7

Output
2
0
7
5

-----Note-----

In the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel.

In the second test case Polycarp does not have any diamonds, so he cannot craft anything.

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

for _ in " "*int(input()):
    a,b=map(int,input().split())
    print(min(a,b,(a+b)//3))


I found an interesting problem on https://codeforces.com/problemset/problem/1366/B:
You are given an array consisting of $n$ integers $a_1$, $a_2$, ..., $a_n$. Initially $a_x = 1$, all other elements are equal to $0$.

You have to perform $m$ operations. During the $i$-th operation, you choose two indices $c$ and $d$ such that $l_i \le c, d \le r_i$, and swap $a_c$ and $a_d$.

Calculate the number of indices $k$ such that it is possible to choose the operations so that $a_k = 1$ in the end.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Then the description of $t$ testcases follow.

The first line of each test case contains three integers $n$, $x$ and $m$ ($1 \le n \le 10^9$; $1 \le m \le 100$; $1 \le x \le n$).

Each of next $m$ lines contains the descriptions of the operations; the $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le n$).

-----Output-----

For each test case print one integer — the number of indices $k$ such that it is possible to choose the operations so that $a_k = 1$ in the end.

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

Output
6
2
3

-----Note-----

In the first test case, it is possible to achieve $a_k = 1$ for every $k$. To do so, you may use the following operations:  swap $a_k$ and $a_4$;  swap $a_2$ and $a_2$;  swap $a_5$ and $a_5$.

In the second test case, only $k = 1$ and $k = 2$ are possible answers. To achieve $a_1 = 1$, you have to swap $a_1$ and $a_1$ during the second operation. To achieve $a_2 = 1$, you have to swap $a_1$ and $a_2$ during the second operation.

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

from collections import defaultdict as dd
import math
import sys
input=sys.stdin.readline
def nn():
	return int(input())

def li():
	return list(input())

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

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

q=nn()

for _ in range(q):
	n ,x,m=mi()
	minx= x
	maxx= x
	for i in range(m):
		l,r=mi()
		if l<minx and r>=minx:
			minx = l
		if r>maxx and l<=maxx:
			maxx = r
	print(maxx-minx+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1366/C:
You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$.

A chip is initially in the cell $(1, 1)$, and it will be moved to the cell $(n, m)$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $(x, y)$, then after the move it can be either $(x + 1, y)$ or $(x, y + 1)$). The chip cannot leave the matrix.

Consider each path of the chip from $(1, 1)$ to $(n, m)$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.

Your goal is to change the values in the minimum number of cells so that every path is palindromic.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 200$) — the number of test cases.

The first line of each test case contains two integers $n$ and $m$ ($2 \le n, m \le 30$) — the dimensions of the matrix.

Then $n$ lines follow, the $i$-th line contains $m$ integers $a_{i, 1}$, $a_{i, 2}$, ..., $a_{i, m}$ ($0 \le a_{i, j} \le 1$).

-----Output-----

For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.

-----Example-----
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0

Output
0
3
4
4

-----Note-----

The resulting matrices in the first three test cases: $\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$  $\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$  $\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$

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

import sys
input = sys.stdin.readline
for f in range(int(input())):
    n,m=map(int,input().split())
    ones=[0]*((n+m)//2)
    for i in range(n):
        line=list(map(int,input().split()))
        for j in range(m):
            x=i+j
            if x>(n+m-2)//2:
                x=n+m-2-x
            if line[j]==1:
                ones[x]+=1
    sol=0
    for i in range((n+m-1)//2):
        tot=2*min(i+1,n,m)
        sol+=min(ones[i],tot-ones[i])
    print(sol)


I found an interesting problem on https://codeforces.com/problemset/problem/1366/E:
You are given two arrays $a_1, a_2, \dots , a_n$ and $b_1, b_2, \dots , b_m$. Array $b$ is sorted in ascending order ($b_i < b_{i + 1}$ for each $i$ from $1$ to $m - 1$).

You have to divide the array $a$ into $m$ consecutive subarrays so that, for each $i$ from $1$ to $m$, the minimum on the $i$-th subarray is equal to $b_i$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $a$ compose the first subarray, the next several elements of $a$ compose the second subarray, and so on.

For example, if $a = [12, 10, 20, 20, 25, 30]$ and $b = [10, 20, 30]$ then there are two good partitions of array $a$:   $[12, 10, 20], [20, 25], [30]$;  $[12, 10], [20, 20, 25], [30]$.

You have to calculate the number of ways to divide the array $a$. Since the number can be pretty large print it modulo 998244353.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of arrays $a$ and $b$ respectively.

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

The third line contains $m$ integers $b_1, b_2, \dots , b_m$ ($1 \le b_i \le 10^9; b_i < b_{i+1}$) — the array $b$.

-----Output-----

In only line print one integer — the number of ways to divide the array $a$ modulo 998244353.

-----Examples-----
Input
6 3
12 10 20 20 25 30
10 20 30

Output
2

Input
4 2
1 3 3 7
3 7

Output
0

Input
8 2
1 2 2 2 2 2 2 2
1 2

Output
7

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

import sys
# import math
# from collections import deque
# import heapq
# from math import inf
# from math import gcd

# print(help(deque))
# 26
pprint = lambda s: print(' '.join(map(str, s)))
input = lambda: sys.stdin.readline().strip()
ipnut = input
# n,m = map(int, input().split())
# n = int(input())
#
n,m = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
mod = 998244353
suf_min = [(10000000000,-1)]
a_r = list(reversed(a))
for i in range(n):
    if a_r[i]<suf_min[-1][0]:
        suf_min.append((a_r[i],n-i-1))
    else:
        suf_min.append(suf_min[-1])
suf_min.reverse()

if suf_min[0][0]!=b[0]:
    print(0)
    return
ans = 1
def bin(a):
    l = 0
    r = n+1
    while r-l>1:
        m = (r+l)//2
        if suf_min[m][0]>a:
            r = m
        else:
            l = m
    return l
for k in range(m-1):
    j= bin(b[k+1])
    if suf_min[j][0]!=b[k+1]:
        print(0)
        return
    ans = (ans*(suf_min[j][1]-suf_min[bin(b[k+1]-1)][1]))%mod
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1366/F:
You are given a simple weighted connected undirected graph, consisting of $n$ vertices and $m$ edges.

A path in the graph of length $k$ is a sequence of $k+1$ vertices $v_1, v_2, \dots, v_{k+1}$ such that for each $i$ $(1 \le i \le k)$ the edge $(v_i, v_{i+1})$ is present in the graph. A path from some vertex $v$ also has vertex $v_1=v$. Note that edges and vertices are allowed to be included in the path multiple times.

The weight of the path is the total weight of edges in it.

For each $i$ from $1$ to $q$ consider a path from vertex $1$ of length $i$ of the maximum weight. What is the sum of weights of these $q$ paths?

Answer can be quite large, so print it modulo $10^9+7$.

-----Input-----

The first line contains a three integers $n$, $m$, $q$ ($2 \le n \le 2000$; $n - 1 \le m \le 2000$; $m \le q \le 10^9$) — the number of vertices in the graph, the number of edges in the graph and the number of lengths that should be included in the answer.

Each of the next $m$ lines contains a description of an edge: three integers $v$, $u$, $w$ ($1 \le v, u \le n$; $1 \le w \le 10^6$) — two vertices $v$ and $u$ are connected by an undirected edge with weight $w$. The graph contains no loops and no multiple edges. It is guaranteed that the given edges form a connected graph.

-----Output-----

Print a single integer — the sum of the weights of the paths from vertex $1$ of maximum weights of lengths $1, 2, \dots, q$ modulo $10^9+7$.

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

Output
4361

Input
2 1 5
1 2 4

Output
60

Input
15 15 23
13 10 12
11 14 12
2 15 5
4 10 8
10 2 4
10 7 5
3 10 1
5 6 11
1 13 8
9 15 4
4 2 9
11 15 1
11 12 14
10 8 12
3 6 11

Output
3250

Input
5 10 10000000
2 4 798
1 5 824
5 2 558
4 1 288
3 4 1890
3 1 134
2 3 1485
4 5 284
3 5 1025
1 2 649

Output
768500592

-----Note-----

Here is the graph for the first example: [Image]

Some maximum weight paths are:   length $1$: edges $(1, 7)$ — weight $3$;  length $2$: edges $(1, 2), (2, 3)$ — weight $1+10=11$; ...

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

import sys
input = sys.stdin.readline
#lev contains height from root,lower neighbour, higher neighbours
#lev[0] contains 0 (because it is the root), higher neighbours (=neighbours)
n,m,q=map(int,input().split())
mod=1000000007
mxw=0
wgts=[0]*n
neig=[0]*n
for i in range(n):
    neig[i]=[0]

for i in range(m):
    a,b,w=map(int,input().split())
    a-=1
    b-=1
    neig[a][0]+=1
    neig[b][0]+=1
    neig[a].append([b,w])
    neig[b].append([a,w])
    mxw=max(mxw,w)
    wgts[a]=max(wgts[a],w)
    wgts[b]=max(wgts[b],w)
poss=[-1]*n
poss[0]=0
sol=0
curw=0
hasmxw=[False]*n
for i in range(n):
    if wgts[i]==mxw:
        hasmxw[i]=True
ov=False
l=0
while l<q and not ov and l<3000:
    newposs=[-1]*n
    for i in range(n):
        if poss[i]>=0:
            for j in range(1,neig[i][0]+1):
                newposs[neig[i][j][0]]=max(newposs[neig[i][j][0]],poss[i]+neig[i][j][1])
    curmx=0
    for i in range(n):
        poss[i]=newposs[i]
        if poss[i]>curmx:
            curmx=poss[i]
            ov=hasmxw[i]
        else:
            if poss[i]==curmx and hasmxw[i]:
                ov=True
    curw=curmx
    sol+=curw
    sol%=mod
    l+=1
if l==q:
    print(sol)
else:
    if ov:
        rem=q-l
        sol+=rem*curw
        sol%=mod
        sol+=mxw*((rem*(rem+1))//2)
        sol%=mod
        print(sol)
    else:
        rem=q-l
        while not ov:
            mx=0
            for i in range(n):
                if poss[i]==curw:
                    mx=max(mx,wgts[i])
            gd=-1
            for i in range(n):
                if wgts[i]>mx and poss[i]>=0:
                    diff=wgts[i]-mx
                    loss=curw-poss[i]
                    loss+=diff-1
                    att=loss//diff
                    if gd==-1:
                        gd=att
                    gd=min(att,gd)
            if gd==-1 or gd>rem:
                sol+=rem*curw
                sol+=mx*((rem*(rem+1))//2)
                sol%=mod
                ov=True
            else:
                sol+=(gd-1)*curw
           ...


I found an interesting problem on https://codeforces.com/problemset/problem/1367/A:
Alice guesses the strings that Bob made for her.

At first, Bob came up with the secret string $a$ consisting of lowercase English letters. The string $a$ has a length of $2$ or more characters. Then, from string $a$ he builds a new string $b$ and offers Alice the string $b$ so that she can guess the string $a$.

Bob builds $b$ from $a$ as follows: he writes all the substrings of length $2$ of the string $a$ in the order from left to right, and then joins them in the same order into the string $b$.

For example, if Bob came up with the string $a$="abac", then all the substrings of length $2$ of the string $a$ are: "ab", "ba", "ac". Therefore, the string $b$="abbaac".

You are given the string $b$. Help Alice to guess the string $a$ that Bob came up with. It is guaranteed that $b$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

-----Input-----

The first line contains a single positive integer $t$ ($1 \le t \le 1000$) — the number of test cases in the test. Then $t$ test cases follow.

Each test case consists of one line in which the string $b$ is written, consisting of lowercase English letters ($2 \le |b| \le 100$) — the string Bob came up with, where $|b|$ is the length of the string $b$. It is guaranteed that $b$ was built according to the algorithm given above.

-----Output-----

Output $t$ answers to test cases. Each answer is the secret string $a$, consisting of lowercase English letters, that Bob came up with.

-----Example-----
Input
4
abbaac
ac
bccddaaf
zzzzzzzzzz

Output
abac
ac
bcdaf
zzzzzz

-----Note-----

The first test case is explained in the statement.

In the second test case, Bob came up with the string $a$="ac", the string $a$ has a length $2$, so the string $b$ is equal to the string $a$.

In the third test case, Bob came up with the string $a$="bcdaf", substrings of length $2$ of string $a$ are: "bc", "cd", "da", "af", so the string $b$="bccddaaf".

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

# @author

import sys

class AShortSubstrings:
    def solve(self, tc=0):
        for _ in range(int(input())):
            b = input().strip()
            print(''.join(b[i] for i in range(len(b)) if i % 2 == 0) + b[-1])

solver = AShortSubstrings()
input = sys.stdin.readline

solver.solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1367/B:
You are given an array $a[0 \ldots n-1]$ of length $n$ which consists of non-negative integers. Note that array indices start from zero.

An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $i$ ($0 \le i \le n - 1$) the equality $i \bmod 2 = a[i] \bmod 2$ holds, where $x \bmod 2$ is the remainder of dividing $x$ by 2.

For example, the arrays [$0, 5, 2, 1$] and [$0, 17, 0, 3$] are good, and the array [$2, 4, 6, 7$] is bad, because for $i=1$, the parities of $i$ and $a[i]$ are different: $i \bmod 2 = 1 \bmod 2 = 1$, but $a[i] \bmod 2 = 4 \bmod 2 = 0$.

In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).

Find the minimum number of moves in which you can make the array $a$ good, or say that this is not possible.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases in the test. Then $t$ test cases follow.

Each test case starts with a line containing an integer $n$ ($1 \le n \le 40$) — the length of the array $a$.

The next line contains $n$ integers $a_0, a_1, \ldots, a_{n-1}$ ($0 \le a_i \le 1000$) — the initial array.

-----Output-----

For each test case, output a single integer — the minimum number of moves to make the given array $a$ good, or -1 if this is not possible.

-----Example-----
Input
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0

Output
2
1
-1
0

-----Note-----

In the first test case, in the first move, you can swap the elements with indices $0$ and $1$, and in the second move, you can swap the elements with indices $2$ and $3$.

In the second test case, in the first move, you need to swap the elements with indices $0$ and $1$.

In the third test case, you cannot make the array good.

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

T = int(input())

for t in range(T):
    N = int(input())
    A = [int(_) for _ in input().split()]
    badE, badO = 0, 0
    for i, el in enumerate(A):
        if el%2 != i%2:
            if i%2:
                badO += 1
            else:
                badE += 1
    if badO != badE:
        print(-1)
    else:
        print(badO)


I found an interesting problem on https://codeforces.com/problemset/problem/1367/C:
Polycarp and his friends want to visit a new restaurant. The restaurant has $n$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $1$ to $n$ in the order from left to right. The state of the restaurant is described by a string of length $n$ which contains characters "1" (the table is occupied) and "0" (the table is empty).

Restaurant rules prohibit people to sit at a distance of $k$ or less from each other. That is, if a person sits at the table number $i$, then all tables with numbers from $i-k$ to $i+k$ (except for the $i$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $k$.

For example, if $n=8$ and $k=2$, then:  strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant;  strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $k=2$.

In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.

You are given a binary string $s$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $s$.

Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?

For example, if $n=6$, $k=1$, $s=$ "100010", then the answer to the problem will be $1$, since only the table at position $3$ can be occupied such that the rules are still satisfied.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test. Then $t$ test cases follow.

Each test case starts with a line containing two integers $n$ and $k$ ($1 \le k \le n \le 2\cdot...

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

def solve(n, k, s):
    nextone = [-1]*n
    last = float('inf')
    for i in range(n-1, -1, -1):
        if s[i] == '1':
            last = i
        nextone[i] = last
    prev = float('-inf')
    sol = 0
    for i in range(n):
        if s[i] == '1':
            prev = i
        else:
            if i-prev > k and nextone[i]-i > k:
                sol += 1
                prev = i
    return sol

t = int(input())
for _ in range(t):
    n, k = map(int, input().split())
    s = input()
    print(solve(n, k, s))


I found an interesting problem on https://codeforces.com/problemset/problem/1367/D:
Polycarp wrote on the board a string $s$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.

After that, he erased some letters from the string $s$, and he rewrote the remaining letters in any order. As a result, he got some new string $t$. You have to find it with some additional information.

Suppose that the string $t$ has length $m$ and the characters are numbered from left to right from $1$ to $m$. You are given a sequence of $m$ integers: $b_1, b_2, \ldots, b_m$, where $b_i$ is the sum of the distances $|i-j|$ from the index $i$ to all such indices $j$ that $t_j > t_i$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $b_i$, Polycarp finds all such indices $j$ that the index $j$ contains a letter that is later in the alphabet than $t_i$ and sums all the values $|i-j|$.

For example, if $t$ = "abzb", then:  since $t_1$='a', all other indices contain letters which are later in the alphabet, that is: $b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$;  since $t_2$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_2=|2-3|=1$;  since $t_3$='z', then there are no indexes $j$ such that $t_j>t_i$, thus $b_3=0$;  since $t_4$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_4=|4-3|=1$.

Thus, if $t$ = "abzb", then $b=[6,1,0,1]$.

Given the string $s$ and the array $b$, find any possible string $t$ for which the following two requirements are fulfilled simultaneously:  $t$ is obtained from $s$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $t$ according to the rules above, equals to the array $b$ specified in the input data.

-----Input-----

The first line contains an integer $q$ ($1 \le q \le 100$) — the number of test cases in the test. Then $q$ test cases follow.

Each test case consists of three lines:  the first line contains string $s$, which has a length from $1$ to $50$ and consists of lowercase English...

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

for _ in range(int(input())):
    s = input()
    m = int(input())
    b = list(map(int,input().split()))
    values = {}
    for num in b:
        if num not in values:
            values[num] = 0
        values[num] += 1
    letters = {}
    for c in s:
        if c not in letters:
            letters[c] = 0
        letters[c] += 1
    sortedLetters = []
    sortedValues = []
    for elem in letters:
        sortedLetters.append((elem, letters[elem]))
    sortedLetters.sort()
    ans = ["" for _ in range(m)]
    while True:
        done = True
        toChange = []
        for i in range(m):
            dist = 0
            if ans[i] != "":
                continue
            for j in range(m):
                if ans[j] != "":
                    dist += abs(i-j)
            if dist == b[i]:
                toChange.append(i)
        if len(toChange) == 0:
            break
        cnt = len(toChange)
        while sortedLetters[-1][1] < cnt:
            sortedLetters.pop(-1)
        for i in toChange:
            ans[i] = sortedLetters[-1][0]
        sortedLetters.pop(-1)
    print("".join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1367/E:
The store sells $n$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.

A necklace is a set of beads connected in a circle.

For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options): [Image]

And the following necklaces cannot be assembled from beads sold in the store: [Image] The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store.

We call a necklace $k$-beautiful if, when it is turned clockwise by $k$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace.  [Image]  As you can see, this necklace is, for example, $3$-beautiful, $6$-beautiful, $9$-beautiful, and so on, but it is not $1$-beautiful or $2$-beautiful.

In particular, a necklace of length $1$ is $k$-beautiful for any integer $k$. A necklace that consists of beads of the same color is also beautiful for any $k$.

You are given the integers $n$ and $k$, and also the string $s$ containing $n$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $k$-beautiful necklace you can assemble.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases in the test. Then $t$ test cases follow.

The first line of each test case contains two integers $n$ and $k$ ($1 \le n, k \le 2000$).

The second line of each test case contains the string $s$ containing $n$ lowercase English letters — the beads in the store.

It is guaranteed that the sum of $n$ for all test cases does not exceed $2000$.

-----Output-----

Output $t$ answers to the test cases. Each answer is a positive integer — the maximum length of...

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

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

t = int(input())
for _ in range(t):
    n,k = map(int,input().split())
    s = input()
    m = [0]*26
    for a in s:
        m[ord(a)-ord('a')]+=1
    t = max(m)
    x = t*k
    while True:
        b = x//(gcd(x,k))
        count = 0
        for a in m:
            count+=a//b
        if count*b>=x:
            break
        x-=1
    print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/1368/A:
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $2$, b = $3$ changes the value of a to $5$ (the value of b does not change).

In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $n$. What is the smallest number of operations he has to perform?

-----Input-----

The first line contains a single integer $T$ ($1 \leq T \leq 100$) — the number of test cases.

Each of the following $T$ lines describes a single test case, and contains three integers $a, b, n$ ($1 \leq a, b \leq n \leq 10^9$) — initial values of a and b, and the value one of the variables has to exceed, respectively.

-----Output-----

For each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.

-----Example-----
Input
2
1 2 3
5 4 100

Output
2
7

-----Note-----

In the first case we cannot make a variable exceed $3$ in one operation. One way of achieving this in two operations is to perform "b += a" twice.

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

for _ in range(int(input())):
    a, b, n = map(int, input().split())
    cnt = 0
    while a <= n or b <= n:
        if a > b:
            b += a
        else:
            a += b
        cnt += 1
    print(cnt-1)


I found an interesting problem on https://codeforces.com/problemset/problem/1368/B:
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least $k$ subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.

Formally, a codeforces subsequence of a string $s$ is a subset of ten characters of $s$ that read codeforces from left to right. For example, codeforces contains codeforces a single time, while codeforcesisawesome contains codeforces four times: codeforcesisawesome, codeforcesisawesome, codeforcesisawesome, codeforcesisawesome.

Help Karl find any shortest string that contains at least $k$ codeforces subsequences.

-----Input-----

The only line contains a single integer $k$ ($1 \leq k \leq 10^{16})$.

-----Output-----

Print a shortest string of lowercase English letters that contains at least $k$ codeforces subsequences. If there are several such strings, print any of them.

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

Output
codeforces

Input
3

Output
codeforcesss

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

from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
    return int(input())

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

def solve():
    n = ri()
    word = 'codeforces'
    mult = [1] * 10
    count = 1
    i = -1
    while count < n:
        i = (i + 1) % 10
        mult[i] += 1
        count = (count // (mult[i] - 1)) * mult[i]
    out = ""
    for i in range(10):
        out += word[i] * mult[i]

    print (out)

mode = 's'

if mode == 'T':
    t = ri()
    for i in range(t):
        solve()
else:
    solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1368/C:
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.

To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied:

 The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side).

 Each gray cell has an even number of gray neighbours.

 There are exactly $n$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).

Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $n$. Help him, and provide any example of a beautiful picture.

To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $(0, 0)$, axes $0x$ and $0y$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.

-----Input-----

The only line contains a single integer $n$ ($1 \leq n \leq 500$) — the number of gray cells with all gray neighbours in a beautiful picture.

-----Output-----

In the first line, print a single integer $k$ — the number of gray cells in your picture. For technical reasons, $k$ should not exceed $5 \cdot 10^5$.

Each of the following $k$ lines should contain two integers — coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $10^9$ by absolute value.

One can show that there exists an answer satisfying all requirements with a small enough $k$.

-----Example-----
Input
4

Output
12
1 0
2 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
1 3
2...

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

n = int(input())

ans = [ [0,0] , [0,1] , [1,0] , [1,1]]

p = 1

for i in range(n):

    p += 1
    ans.append( [p,p])
    ans.append( [p,p-1]  )
    ans.append( [p-1,p])

print(len(ans))

for i in ans:

    print(*i)


I found an interesting problem on https://codeforces.com/problemset/problem/1368/D:
Gottfried learned about binary number representation. He then came up with this task and presented it to you.

You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\mathsf{AND}~y$, $a_j = x~\mathsf{OR}~y$, where $\mathsf{AND}$ and $\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).

After all operations are done, compute $\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve?

-----Input-----

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

The second line contains $n$ integers $a_1, \ldots, a_n$ ($0 \leq a_i < 2^{20}$).

-----Output-----

Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations.

-----Examples-----
Input
1
123

Output
15129

Input
3
1 3 5

Output
51

Input
2
349525 699050

Output
1099509530625

-----Note-----

In the first sample no operation can be made, thus the answer is $123^2$.

In the second sample we can obtain the collection $1, 1, 7$, and $1^2 + 1^2 + 7^2 = 51$.

If $x$ and $y$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $x~\mathsf{AND}~y$ is set to $1$ if and only if both corresponding bits of $x$ and $y$ are set to $1$. Similarly, each bit of $x~\mathsf{OR}~y$ is set to $1$ if and only if at least one of the corresponding bits of $x$ and $y$ are set to $1$. For example, $x = 3$ and $y = 5$ are represented as $011_2$ and $101_2$ (highest bit first). Then, $x~\mathsf{AND}~y = 001_2 = 1$, and $x~\mathsf{OR}~y = 111_2 = 7$.

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

import sys
readline = sys.stdin.readline
N = int(readline())
A = list(map(int, readline().split()))
B = 20
table = [0]*B
for a in A:
    for i in range(B):
        if (1<<i) & a:
            table[i] += 1

ans = 0

for _ in range(N):
    res = 0
    for i in range(B):
        if table[i]:
            table[i] -= 1
            res |= (1<<i)
    ans += res**2

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1369/D:
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...

Let's define a Rooted Dead Bush (RDB) of level $n$ as a rooted tree constructed as described below.

A rooted dead bush of level $1$ is a single vertex. To construct an RDB of level $i$ we, at first, construct an RDB of level $i-1$, then for each vertex $u$:   if $u$ has no children then we will add a single child to it;  if $u$ has one child then we will add two children to it;  if $u$ has more than one child, then we will skip it.

 [Image] Rooted Dead Bushes of level $1$, $2$ and $3$.

Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:

 [Image] The center of the claw is the vertex with label $1$.

Lee has a Rooted Dead Bush of level $n$. Initially, all vertices of his RDB are green.

In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.

He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $10^9+7$.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

Next $t$ lines contain test cases — one per line.

The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^6$) — the level of Lee's RDB.

-----Output-----

For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo $10^9 + 7$.

-----Example-----
Input
7
1
2
3
4
5
100
2000000

Output
0
0
4
4
12
990998587
804665184

-----Note-----

It's easy to see that the answer for RDB of level $1$ or $2$ is $0$.

The answer for RDB of level $3$ is $4$ since there is only one claw we can...

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

# import numpy as np
# import sys

# q=int(input())
mod=1000000007
dp=[(0,0),(0,0)]
for i in range(2,2000001):
	dp.append(((max(dp[-1])+2*max(dp[-2]))%mod,(dp[-1][0]+2*dp[-2][0]+1)%mod))
for o in range(int(input())):
	print(max(dp[int(input())-1])*4%mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1369/E:
Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020...

There are $n$ different types of food and $m$ Lee's best friends. Lee has $w_i$ plates of the $i$-th type of food and each friend has two different favorite types of food: the $i$-th friend's favorite types of food are $x_i$ and $y_i$ ($x_i \ne y_i$).

Lee will start calling his friends one by one. Whoever is called will go to the kitchen and will try to eat one plate of each of his favorite food types. Each of the friends will go to the kitchen exactly once.

The only problem is the following: if a friend will eat at least one plate of food (in total) then he will be harmless. But if there is nothing left for him to eat (neither $x_i$ nor $y_i$), he will eat Lee instead $\times\_\times$.

Lee can choose the order of friends to call, so he'd like to determine if he can survive dinner or not. Also, he'd like to know the order itself.

-----Input-----

The first line contains two integers $n$ and $m$ ($2 \le n \le 10^5$; $1 \le m \le 2 \cdot 10^5$) — the number of different food types and the number of Lee's friends.

The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \le w_i \le 10^6$) — the number of plates of each food type.

The $i$-th line of the next $m$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$; $x_i \ne y_i$) — the favorite types of food of the $i$-th friend.

-----Output-----

If Lee can survive the dinner then print ALIVE (case insensitive), otherwise print DEAD (case insensitive).

Also, if he can survive the dinner, print the order Lee should call friends. If there are multiple valid orders, print any of them.

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

Output
ALIVE
3 2 1

Input
3 2
1 1 0
1 2
1 3

Output
ALIVE
2 1

Input
4 4
1 2 0 1
1 3
1 2
2 3
2 4

Output
ALIVE
1 3 2 4

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

Output
ALIVE
5 4 1 3 2

Input
4 10
2 4 1 4
3 2
4 2
4 1
3 1
4 1
1...

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

import sys
from collections import deque

input=sys.stdin.readline

n,m=list(map(int,input().split()))
w=list(map(int,input().split()))
data=[[] for i in range(n)]
fav=[]
for i in range(m):
    x,y=list(map(int,input().split()))
    x,y=min(x,y),max(x,y)
    w[x-1]-=1
    w[y-1]-=1
    data[x-1].append(i)
    data[y-1].append(i)
    fav.append((x-1,y-1))

ans=[]
used=[False]*m
useddish=[False]*n

que=deque([])
for i in range(n):
    if w[i]>=0:
        que.append(i)
        useddish[i]=True

while que:
    id=que.popleft()
    for i in data[id]:
        if not used[i]:
            used[i]=True
            ans.append(i)
            x,y=fav[i]
            w[x]+=1
            w[y]+=1
            if w[x]>=0 and not useddish[x]:
                que.append(x)
                useddish[x]=True
            if w[y]>=0 and not useddish[y]:
                que.append(y)
                useddish[y]=True

if len(ans)==m:
    print("ALIVE")
    ans=[ans[-i-1]+1 for i in range(m)]
    print(*ans)
else:
    print("DEAD")


I found an interesting problem on https://codeforces.com/problemset/problem/1369/F:
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...

The game is a one versus one game. It has $t$ rounds, each round has two integers $s_i$ and $e_i$ (which are determined and are known before the game begins, $s_i$ and $e_i$ may differ from round to round). The integer $s_i$ is written on the board at the beginning of the corresponding round.

The players will take turns. Each player will erase the number on the board (let's say it was $a$) and will choose to write either $2 \cdot a$ or $a + 1$ instead. Whoever writes a number strictly greater than $e_i$ loses that round and the other one wins that round.

Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $s_i$ and $e_i$ in advance. Lee will start the first round, the loser of each round will start the next round.

The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.

Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.

-----Input-----

The first line contains the integer $t$ ($1 \le t \le 10^5$) — the number of rounds the game has.

Then $t$ lines follow, each contains two integers $s_i$ and $e_i$ ($1 \le s_i \le e_i \le 10^{18}$) — the $i$-th round's information.

The rounds are played in the same order as given in input, $s_i$ and $e_i$ for all rounds are known to everyone before the game starts.

-----Output-----

Print two integers.

The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise.

The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.

-----Examples-----
Input
3
5 8
1 4
3 10

Output
1 1

Input
4
1 2
2 3
3 4
4 5

Output
0 0

Input
1
1 1

Output
0 1

Input
2
1 9
4 5

Output
0 0

Input
2
1 2
2...

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

import sys
input = sys.stdin.readline

def win(s, e):
    if e == s:
        return False
    elif e == s + 1:
        return True
    elif e & 1:
        return s & 1 == 0
    elif e // 2 < s:
        return s & 1 == 1
    elif e // 4 < s:
        return True
    else:
        return win(s, e // 4)

def lose(s, e):
    if e // 2 < s:
        return True
    else:
        return win(s, e // 2)

def main():
    res = [False, True]
    for _ in range(int(input())):
        s, e = [int(x) for x in input().split()]
        if res == [True, True]:
            continue
        if res == [False, False]:
            continue
        cur = [win(s, e), lose(s, e)]
        if res[0]:
            cur = [not x for x in cur]
        res = cur
    print(*[int(x) for x in res])

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1370/A:
Let's consider all integers in the range from $1$ to $n$ (inclusive).

Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $\mathrm{gcd}(a, b)$, where $1 \leq a < b \leq n$.

The greatest common divisor, $\mathrm{gcd}(a, b)$, of two positive integers $a$ and $b$ is the biggest integer that is a divisor of both $a$ and $b$.

-----Input-----

The first line contains a single integer $t$ ($1 \leq t \leq 100$)  — the number of test cases. The description of the test cases follows.

The only line of each test case contains a single integer $n$ ($2 \leq n \leq 10^6$).

-----Output-----

For each test case, output the maximum value of $\mathrm{gcd}(a, b)$ among all $1 \leq a < b \leq n$.

-----Example-----
Input
2
3
5

Output
1
2

-----Note-----

In the first test case, $\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$.

In the second test case, $2$ is the maximum possible value, corresponding to $\mathrm{gcd}(2, 4)$.

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

t = int(input())
for _ in range(t):
    n = int(input())
    print(n//2)


I found an interesting problem on https://codeforces.com/problemset/problem/1370/C:
Ashishgup and FastestFinger play a game.

They start with a number $n$ and play in turns. In each turn, a player can make any one of the following moves:  Divide $n$ by any of its odd divisors greater than $1$.  Subtract $1$ from $n$ if $n$ is greater than $1$.

Divisors of a number include the number itself.

The player who is unable to make a move loses the game.

Ashishgup moves first. Determine the winner of the game if both of them play optimally.

-----Input-----

The first line contains a single integer $t$ ($1 \leq t \leq 100$)  — the number of test cases. The description of the test cases follows.

The only line of each test case contains a single integer  — $n$ ($1 \leq n \leq 10^9$).

-----Output-----

For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).

-----Example-----
Input
7
1
2
3
4
5
6
12

Output
FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup

-----Note-----

In the first test case, $n = 1$, Ashishgup cannot make a move. He loses.

In the second test case, $n = 2$, Ashishgup subtracts $1$ on the first move. Now $n = 1$, FastestFinger cannot make a move, so he loses.

In the third test case, $n = 3$, Ashishgup divides by $3$ on the first move. Now $n = 1$, FastestFinger cannot make a move, so he loses.

In the last test case, $n = 12$, Ashishgup divides it by $3$. Now $n = 4$, FastestFinger is forced to subtract $1$, and Ashishgup gets $3$, so he wins by dividing it by $3$.

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

from sys import stdin

def isPrime(n):
    for i in range(2, int(n**0.5+1)):
        if n % i == 0:
            return False
    return True

t = int(stdin.readline().strip())
for _ in range(t):
    n = int(stdin.readline().strip())
    if n == 1:
        print("FastestFinger")
    elif n == 2:
        print("Ashishgup")
    elif n % 2 == 1:
        print("Ashishgup")
    elif n & (n-1) == 0:
        print("FastestFinger")
    elif (n/2) % 2 == 1 and isPrime(n/2):
        print("FastestFinger")
    else:
        print("Ashishgup")


I found an interesting problem on https://codeforces.com/problemset/problem/1370/D:
Ashish has an array $a$ of size $n$.

A subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements.

Consider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between:   The maximum among all elements at odd indices of $s$.  The maximum among all elements at even indices of $s$.

Note that the index of an element is its index in $s$, rather than its index in $a$. The positions are numbered from $1$. So, the cost of $s$ is equal to $min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$.

For example, the cost of $\{7, 5, 6\}$ is $min( max(7, 6), max(5) ) = min(7, 5) = 5$.

Help him find the minimum cost of a subsequence of size $k$.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \leq k \leq n \leq 2 \cdot 10^5$)  — the size of the array $a$ and the size of the subsequence.

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

-----Output-----

Output a single integer  — the minimum cost of a subsequence of size $k$.

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

Output
1
Input
4 3
1 2 3 4

Output
2
Input
5 3
5 3 4 2 6

Output
2
Input
6 4
5 3 50 2 4 5

Output
3

-----Note-----

In the first test, consider the subsequence $s$ = $\{1, 3\}$. Here the cost is equal to $min(max(1), max(3)) = 1$.

In the second test, consider the subsequence $s$ = $\{1, 2, 4\}$. Here the cost is equal to $min(max(1, 4), max(2)) = 2$.

In the fourth test, consider the subsequence $s$ = $\{3, 50, 2, 4\}$. Here the cost is equal to $min(max(3, 2), max(50, 4)) = 3$.

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

def check(num):
	count = 0
	flag = -1
	s = 0
	for i in range(n):
		if a[i]<=num:
			count += 1
			s += 1
		else:
			if flag == -1:
				flag = s%2
				count += 1
				s += 1
			else:
				if (s+1)%2!=flag:
					count += 1
					s += 1
		if count==k:
			return True
	return False

n,k = map(int,input().split())
a = list(map(int,input().split()))
if n==k:
	m1 = 0
	m2 = 0
	for i in range(0,n,2):
		m1 = max(m1,a[i])
	for i in range(1,n,2):
		m2 = max(m2,a[i])
	print (min(m1,m2))
	return
s = set(a)
minn,maxx = min(a),max(a)
low = minn
high = maxx
while low<high:
	mid = (low+high)//2
	if check(mid):
		high = mid-1
	else:
		low = mid+1
if check(low):
	print (low)
else:
	print (low+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1370/E:
Naman has two binary strings $s$ and $t$ of length $n$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $s$ into $t$ using the following operation as few times as possible.

In one operation, he can choose any subsequence of $s$ and rotate it clockwise once.

For example, if $s = 1\textbf{1}101\textbf{00}$, he can choose a subsequence corresponding to indices ($1$-based) $\{2, 6, 7 \}$ and rotate them clockwise. The resulting string would then be $s = 1\textbf{0}101\textbf{10}$.

A string $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the ordering of the remaining characters.

To perform a clockwise rotation on a sequence $c$ of size $k$ is to perform an operation which sets $c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$ simultaneously.

Determine the minimum number of operations Naman has to perform to convert $s$ into $t$ or say that it is impossible.

-----Input-----

The first line contains a single integer $n$ $(1 \le n \le 10^6)$ — the length of the strings.

The second line contains the binary string $s$ of length $n$.

The third line contains the binary string $t$ of length $n$.

-----Output-----

If it is impossible to convert $s$ to $t$ after any number of operations, print $-1$.

Otherwise, print the minimum number of operations required.

-----Examples-----
Input
6
010000
000001

Output
1
Input
10
1111100000
0000011111

Output
5
Input
8
10101010
01010101

Output
1
Input
10
1111100000
1111100001

Output
-1

-----Note-----

In the first test, Naman can choose the subsequence corresponding to indices $\{2, 6\}$ and rotate it once to convert $s$ into $t$.

In the second test, he can rotate the subsequence corresponding to all indices $5$ times. It can be proved, that it is the minimum required number of operations.

In the last test, it is impossible to convert $s$ into $t$.

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

n = int(input())
s = input()
t = input()
if s.count('1') != t.count('1'):
    print(-1)
    return

p = []
ans = [0, 0]
for i in range(n):
    if s[i] != t[i]:
        if p and s[i] != p[-1]:
            p.pop(-1)
        else:
            p.append(s[i])
            w = int(s[i])
            ans[w] = max(ans[w], len(p))
print(sum(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1371/B:
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $7$ days!

In detail, she can choose any integer $k$ which satisfies $1 \leq k \leq r$, and set $k$ days as the number of days in a week.

Alice is going to paint some $n$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.

She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.

Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.

For example, in the picture, a week has $4$ days and Alice paints $5$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes. [Image]

Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $n$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Next $t$ lines contain descriptions of test cases.

For each test case, the only line contains two integers $n$, $r$ ($1 \le n \le 10^9, 1 \le r \le 10^9$).

-----Output-----

For each test case, print a single integer  — the answer to the problem.

Please note, that the answer for some test cases won't fit into $32$-bit integer type, so you should use at least $64$-bit integer type in...

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

mod = 1000000007
eps = 10**-9

def main():
    import sys
    input = sys.stdin.readline

    for _ in range(int(input())):
        N, r = list(map(int, input().split()))
        if r >= N:
            print(N * (N-1) // 2 + 1)
        else:
            print(r * (r+1) // 2)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1371/C:
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $a$ vanilla cookies and $b$ chocolate cookies for the party.

She invited $n$ guests of the first type and $m$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:

If there are $v$ vanilla cookies and $c$ chocolate cookies at the moment, when the guest comes, then  if the guest of the first type: if $v>c$ the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie.  if the guest of the second type: if $v>c$ the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie.

After that:  If there is at least one cookie of the selected type, the guest eats one.  Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home.

Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Next $t$ lines contain descriptions of test cases.

For each test case, the only line contains four integers $a$, $b$, $n$, $m$ ($0 \le a,b,n,m \le 10^{18}, n+m \neq 0$).

-----Output-----

For each test case, print the answer in one line. If there exists at least one valid order, print "Yes". Otherwise, print "No".

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

-----Example-----
Input
6
2 2 1 2
0 100 0 1
12 13 25 1
27 83 14 25
0 0 1 0
1000000000000000000 1000000000000000000 1000000000000000000 1000000000000000000

Output
Yes
No
No
Yes
No
Yes

-----Note-----

In the first test case, let's consider the order $\{1, 2, 2\}$ of types of guests. Then:  The first guest eats a chocolate...

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

test= int(input())
for ii in range(test):
    a,b,n,m= list(map(int,input().split()))
    if(a+b)<(m+n):
        print ("No")
        continue
    if(a>b):
        a,b=b,a
    if(a<m):
        print ("No")
        continue
    rem= a-m
    if(b+rem)<n:
        print ("No")
        continue
    print ("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/1371/E1:
This is the easy version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.

First, Aoi came up with the following idea for the competitive programming problem:

Yuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies.

Yuzu is going to determine a permutation $P$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $\{2,3,1,5,4\}$ is a permutation, but $\{1,2,2\}$ is not a permutation ($2$ appears twice in the array) and $\{1,3,4\}$ is also not a permutation (because $n=3$ but there is the number $4$ in the array).

After that, she will do $n$ duels with the enemies with the following rules:  If Yuzu has equal or more number of candies than enemy $P_i$, she wins the duel and gets $1$ candy. Otherwise, she loses the duel and gets nothing.  The candy which Yuzu gets will be used in the next duels.

Yuzu wants to win all duels. How many valid permutations $P$ exist?

This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:

Let's define $f(x)$ as the number of valid permutations for the integer $x$.

You are given $n$, $a$ and a prime number $p \le n$. Let's call a positive integer $x$ good, if the value $f(x)$ is not divisible by $p$. Find all good integers $x$.

Your task is to solve this problem made by Akari.

-----Input-----

The first line contains two integers $n$, $p$ $(2 \le p \le n \le 2000)$. It is guaranteed, that the number $p$ is prime (it has exactly two divisors $1$ and $p$).

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

-----Output-----

In the first line, print the number of good integers $x$.

In the second line, output all good integers $x$ in the ascending order.

It is guaranteed that the number of...

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

n,p=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
ans=[]
for x in range(1,2001):
  fail=0
  pointer=0
  for i in range(n):
    while pointer<n-1 and x+i-a[pointer+1]>=0:
      pointer+=1
    if (pointer+1-i)%p==0:
      fail=1
      break
    if x+i-a[pointer]<0:
      fail=1
      break
  if fail==0:
    ans.append(str(x))
print(len(ans))
print(' '.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1371/E2:
This is the hard version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.

First, Aoi came up with the following idea for the competitive programming problem:

Yuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies.

Yuzu is going to determine a permutation $P$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $\{2,3,1,5,4\}$ is a permutation, but $\{1,2,2\}$ is not a permutation ($2$ appears twice in the array) and $\{1,3,4\}$ is also not a permutation (because $n=3$ but there is the number $4$ in the array).

After that, she will do $n$ duels with the enemies with the following rules:

  If Yuzu has equal or more number of candies than enemy $P_i$, she wins the duel and gets $1$ candy. Otherwise, she loses the duel and gets nothing.  The candy which Yuzu gets will be used in the next duels.

Yuzu wants to win all duels. How many valid permutations $P$ exist?

This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:

Let's define $f(x)$ as the number of valid permutations for the integer $x$.

You are given $n$, $a$ and a prime number $p \le n$. Let's call a positive integer $x$ good, if the value $f(x)$ is not divisible by $p$. Find all good integers $x$.

Your task is to solve this problem made by Akari.

-----Input-----

The first line contains two integers $n$, $p$ $(2 \le p \le n \le 10^5)$. It is guaranteed, that the number $p$ is prime (it has exactly two divisors $1$ and $p$).

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

-----Output-----

In the first line, print the number of good integers $x$.

In the second line, output all good integers $x$ in the ascending order.

It is guaranteed that the number of...

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

# f = open('test.py')
# def input():
# 	return f.readline().replace('\n','')

# import heapq
# import bisect
# from collections import deque
# from collections import defaultdict
def read_list():
	return list(map(int,input().strip().split(' ')))
def print_list(l):
	print(' '.join(map(str,l)))

# N = int(input())
# for _ in range(N):
n,p= read_list()
a = read_list()
a.sort()
mi = max(a[i]-i for i in range(n))
res = []
ll = []

x = mi
now = x
i = 0
dic = [[-1]]
for step in range(n):
	while i<n and now>=a[i]:
		i+=1
	now+=1
	tmp = (i - step)%p
	tmp = (p - tmp)%p
	if step>=tmp:
		dic.append([tmp,step])
dic.pop(0)

for i in range(len(dic)-1,0,-1):
	if dic[i][0]<=dic[i-1][1]-1:
		dic[i-1][1] = dic[i][1]
		dic[i-1][0] = min(dic[i][0],dic[i-1][0])
		dic.pop(i)
# print(dic)

las = 0
for d in dic:
	flag = True
	for i in range(las,d[0]):
		if i>=p-1:
			flag = False
			break
		res.append(mi+i)
	las = d[1]+1
	if not flag:
		break
if dic:
	for i in range(dic[-1][-1]+1,p-1):
		res.append(mi+i)

print(len(res))
print_list(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1372/B:
In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$.

Omkar, having a laudably curious mind, immediately thought of a problem involving the $LCM$ operation: given an integer $n$, find positive integers $a$ and $b$ such that $a + b = n$ and $LCM(a, b)$ is the minimum value possible.

Can you help Omkar solve his ludicrously challenging math problem?

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 10$). Description of the test cases follows.

Each test case consists of a single integer $n$ ($2 \leq n \leq 10^{9}$).

-----Output-----

For each test case, output two positive integers $a$ and $b$, such that $a + b = n$ and $LCM(a, b)$ is the minimum possible.

-----Example-----
Input
3
4
6
9

Output
2 2
3 3
3 6

-----Note-----

For the first test case, the numbers we can choose are $1, 3$ or $2, 2$. $LCM(1, 3) = 3$ and $LCM(2, 2) = 2$, so we output $2 \ 2$.

For the second test case, the numbers we can choose are $1, 5$, $2, 4$, or $3, 3$. $LCM(1, 5) = 5$, $LCM(2, 4) = 4$, and $LCM(3, 3) = 3$, so we output $3 \ 3$.

For the third test case, $LCM(3, 6) = 6$. It can be shown that there are no other pairs of numbers which sum to $9$ that have a lower $LCM$.

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

from math import sqrt
def solve():
    n = int(input())
    for i in range(2, int(sqrt(n)) + 1):
        if n % i == 0:
            x = n // i
            print(x, x * (i-1))
            return
    print(n-1,1)
for i in range(int(input())):
    solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1372/C:
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!

Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position.

Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.

An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.

The first line of each test case contains integer $n$ ($1 \leq n \leq 2 \cdot 10^5$)  — the length of the given permutation.

The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ ($1 \leq a_{i} \leq n$)  — the initial permutation.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.

-----Output-----

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.

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

Output
0
2

-----Note-----

In the first permutation, it is already sorted so no exchanges are needed.

It can be shown that you need at least $2$ exchanges to sort...

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

from math import *

def r1(t):
    return t(input())

def r2(t):
    return [t(i) for i in input().split()]

for _ in range(r1(int)):
    n = r1(int)
    a = r2(int)
    g = True
    for i in range(n):
        if a[i] != i + 1:
            g = False
            break
    if g:
        print(0)
        continue

    g = True
    c = 0
    p = False
    for i in range(n):
        if a[i] != i + 1:
            if p == False:
                c += 1
                p = True
        else:
            p = False
    print(min(c, 2))


I found an interesting problem on https://codeforces.com/problemset/problem/1372/D:
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!

You are given $n$ nonnegative integers $a_1, a_2, \dots, a_n$ arranged in a circle, where $n$ must be odd (ie. $n-1$ is divisible by $2$). Formally, for all $i$ such that $2 \leq i \leq n$, the elements $a_{i - 1}$ and $a_i$ are considered to be adjacent, and $a_n$ and $a_1$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.

Help Danny find the maximum possible circular value after some sequences of operations.

-----Input-----

The first line contains one odd integer $n$ ($1 \leq n < 2 \cdot 10^5$, $n$ is odd)  — the initial size of the circle.

The second line contains $n$ integers $a_{1},a_{2},\dots,a_{n}$ ($0 \leq a_{i} \leq 10^9$)  — the initial numbers in the circle.

-----Output-----

Output the maximum possible circular value after applying some sequence of operations to the given circle.

-----Examples-----
Input
3
7 10 2

Output
17

Input
1
4

Output
4

-----Note-----

For the first test case, here's how a circular value of $17$ is obtained:

Pick the number at index $3$. The sum of adjacent elements equals $17$. Delete $7$ and $10$ from the circle and replace $2$ with $17$.

Note that the answer may not fit in a $32$-bit integer.

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

n = int(input())
l = list(map(int, input().split()))

pref_odd = [0]
curr = 0
for i in range(n):
    if i % 2 == 1:
        curr += l[i]
    pref_odd.append(curr)

pref_even = [0]
curr = 0
for i in range(n):
    if i % 2 == 0:
        curr += l[i]
    pref_even.append(curr)

best = 0
for i in range(n):
    o1 = pref_even[i] + (pref_odd[-1] - pref_odd[i+1])
    o2 = pref_odd[i] + (pref_even[-1] - pref_even[i+1])
    best = max(best,max(o1,o2)+l[i])
print(best)


I found an interesting problem on https://codeforces.com/problemset/problem/1372/E:
Omkar is building a house. He wants to decide how to make the floor plan for the last floor.

Omkar's floor starts out as $n$ rows of $m$ zeros ($1 \le n,m \le 100$). Every row is divided into intervals such that every $0$ in the row is in exactly $1$ interval. For every interval for every row, Omkar can change exactly one of the $0$s contained in that interval to a $1$. Omkar defines the quality of a floor as the sum of the squares of the sums of the values in each column, i. e. if the sum of the values in the $i$-th column is $q_i$, then the quality of the floor is $\sum_{i = 1}^m q_i^2$.

Help Omkar find the maximum quality that the floor can have.

-----Input-----

The first line contains two integers, $n$ and $m$ ($1 \le n,m \le 100$), which are the number of rows and number of columns, respectively.

You will then receive a description of the intervals in each row. For every row $i$ from $1$ to $n$: The first row contains a single integer $k_i$ ($1 \le k_i \le m$), which is the number of intervals on row $i$. The $j$-th of the next $k_i$ lines contains two integers $l_{i,j}$ and $r_{i,j}$, which are the left and right bound (both inclusive), respectively, of the $j$-th interval of the $i$-th row. It is guaranteed that all intervals other than the first interval will be directly after the interval before it. Formally, $l_{i,1} = 1$, $l_{i,j} \leq r_{i,j}$ for all $1 \le j \le k_i$, $r_{i,j-1} + 1 = l_{i,j}$ for all $2 \le j \le k_i$, and $r_{i,k_i} = m$.

-----Output-----

Output one integer, which is the maximum possible quality of an eligible floor plan.

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

Output
36

-----Note-----

The given test case corresponds to the following diagram. Cells in the same row and have the same number are a part of the same interval.

 [Image]

The most optimal assignment is:

 [Image]

The sum of the $1$st column is $4$, the sum of the $2$nd column is $2$, the sum of the $3$rd and $4$th columns are $0$, and the sum of the $5$th column...

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

import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return list(map(int, minp().split()))

def solve():
	n, m = mints()
	lines = []
	rows = [[0]*(m+2) for i in range(n)]
	col = [n]*(m+2)
	lstart = [[] for i in range(m+2)]
	lend = [[] for i in range(m+2)]
	dp = [[0]*(m+2) for i in range(m+2)]
	for i in range(n):
		for j in range(mint()):
			l, r = mints()
			lstart[l].append((i, r + 1))
			lend[r + 1].append((i, l))
	for i in range(1,m+2):
		for r, start in lend[i]:
			#print("end", r, start, i-1)
			for p in range(start, i):
				rows[r][p] -= 1
				if rows[r][p] == 0:
					col[p] += 1
		for r, end in lstart[i]:
			#print("start", r, i, end)
			for p in range(i, end):
				rows[r][p] += 1
				if rows[r][p] == 1:
					col[p] -= 1
		bcol = col.copy()
		brows = [rows[i].copy() for i in range(n)]
		#print(i, col)
		cc = [None]*(i-1)
		for j in range(i-1):
			for r, start in lend[j]:
				for p in range(start, j):
					rows[r][p] -= 1
					if rows[r][p] == 0:
						col[p] += 1
			for r, end in lstart[j]:
				for p in range(j, end):
					rows[r][p] += 1
					if rows[r][p] == 1:
						col[p] -= 1
			cc[j] = col.copy()

		for j in range(i-2,-1,-1):
			d = 0
			col = cc[j]
			for p in range(j+1, i):
				d = max(d, dp[j][p] + dp[p][i] + col[p]**2)
			dp[j][i] = d
			#print(j, i, col, d)
		col = bcol
		rows = brows
	print(dp[0][m+1])

solve()