I found an interesting problem on https://codeforces.com/problemset/problem/1025/C:
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras.

Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let's call the number of selected pieces the length of the zebra.

Before assembling the zebra Grisha can make the following operation $0$ or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order "bwbbw" (here 'b' denotes a black strip, and 'w' denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain "wbwbb".

Determine the maximum possible length of the zebra that Grisha can produce.

-----Input-----

The only line contains a string $s$ ($1 \le |s| \le 10^5$, where $|s|$ denotes the length of the string $s$) comprised of lowercase English letters 'b' and 'w' only, where 'w' denotes a white piece and 'b' denotes a black piece.

-----Output-----

Print a single integer — the maximum possible zebra length.

-----Examples-----
Input
bwwwbwwbw

Output
5

Input
bwwbwwb

Output
3

-----Note-----

In the first example one of the possible sequence of operations is bwwwbww|bw $\to$ w|wbwwwbwb $\to$ wbwbwwwbw, that gives the answer equal to $5$.

In the second example no operation can increase the answer.

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

s=str(input())
fans=1
first=s[0]
last=s[-1]
i=0
j=len(s)-1
tempans=1
turns=0
counter=len(s)-1
while(i<counter and i<j and i<len(s)-1):
    if(turns%2==0):
        if(s[i]!=s[i+1]):
            tempans+=1
            fans=max(tempans,fans)
            i+=1
        else:
            if(first==last):
                tempans=1
                i+=1
            else:
                first=s[i]
                last=s[i+1]
                tempans+=1
                fans=max(tempans,fans)
                i+=1
                turns+=1
                j=counter
    else:
        if(s[j]!=s[j-1]):
            tempans+=1
            fans=max(tempans,fans)
            j-=1
            counter-=1
        else:
            if(first==last):
                tempans=1
                j-=1
                counter-=1
            else:
                first=s[j]
                last=s[j-1]
                tempans+=1
                fans=max(tempans,fans)
                j-=1
                turns+=1
                counter=j
i=len(s)-1
j=0
counter=0
first=s[0]
last=s[-1]
turns=0
tempans=1
while(i>counter and i>j and i>0):
    if(turns%2==0):
        if(s[i]!=s[i-1]):
            tempans+=1
            fans=max(fans,tempans)
            i-=1
        else:
            if(first==last):
                tempans=1
                i-=1
            else:
                first=s[i-1]
                last=s[i]
                tempans+=1
                fans=max(fans,tempans)
                i-=1
                turns+=1
                j=counter
    else:
        if(s[j]!=s[j+1]):
            tempans+=1
            fans=max(tempans,fans)
            j+=1
            counter+=1
        else:
            if(first==last):
                tempans=1
                j+=1
                counter+=1
            else:
                first=s[j]
                last=s[j+1]
                tempans+=1
                fans=max(tempans,fans)
                j+=1
                turns+=1
                counter=j
print(fans)


I found an interesting problem on https://codeforces.com/problemset/problem/1025/D:
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!

Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset.

To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed $1$.

Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found here.

-----Input-----

The first line contains the number of vertices $n$ ($2 \le n \le 700$).

The second line features $n$ distinct integers $a_i$ ($2 \le a_i \le 10^9$) — the values of vertices in ascending order.

-----Output-----

If it is possible to reassemble the binary search tree, such that the greatest common divisor of any two vertices connected by the edge is greater than $1$, print "Yes" (quotes for clarity).

Otherwise, print "No" (quotes for clarity).

-----Examples-----
Input
6
3 6 9 18 36 108

Output
Yes

Input
2
7 17

Output
No

Input
9
4 8 10 12 15 18 33 44 81

Output
Yes

-----Note-----

The picture below illustrates one of the possible trees for the first example. [Image]

The picture below illustrates one of the possible trees for the third example. [Image]

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

from sys import stdin
from math import gcd
n=int(stdin.readline())
a=[int(x) for x in stdin.readline().split()]
c = []
ld=[]
rd=[]

def check(l, r, e):
    if r == l: return c[l][e] > 0
    if e < l and ld[l][r-l] != 0:
        return ld[l][r-l] == 1
    elif e > r and rd[l][r-l] != 0:
        return rd[l][r-l] == 1
    for i in range(l, r+1):
        if c[i][e]>0:
            if i==l or check(l, i-1, i):
                if i==r or check(i+1, r, i):
                    if e < l:
                        ld[l][r-l] = 1
                    else:
                        rd[l][r-l] = 1
                    return True
    if e < l:
        ld[l][r - l] = -1
    else:
        rd[l][r - l] = -1
    return False

for i in range(n):
    c.append([0]*n)
    ld.append([0]*n)
    rd.append([0] * n)
for i in range(n):
    for j in range(i+1,n):
        if gcd(a[i],a[j]) > 1:
            c[i][j] = c[j][i] = 1
ans=False
for i in range(n):
    if i == 0 or check(0, i - 1, i):
        if i == n-1 or check(i + 1, n-1, i):
            ans = True
            break
if ans:
    print("Yes")
else:
    print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/1027/A:
You are given a string $s$ consisting of $n$ lowercase Latin letters. $n$ is even.

For each position $i$ ($1 \le i \le n$) in string $s$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.

For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.

That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' $\rightarrow$ 'd', 'o' $\rightarrow$ 'p', 'd' $\rightarrow$ 'e', 'e' $\rightarrow$ 'd', 'f' $\rightarrow$ 'e', 'o' $\rightarrow$ 'p', 'r' $\rightarrow$ 'q', 'c' $\rightarrow$ 'b', 'e' $\rightarrow$ 'f', 's' $\rightarrow$ 't').

String $s$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.

Your goal is to check if it's possible to make string $s$ a palindrome by applying the aforementioned changes to every position. Print "YES" if string $s$ can be transformed to a palindrome and "NO" otherwise.

Each testcase contains several strings, for each of them you are required to solve the problem separately.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 50$) — the number of strings in a testcase.

Then $2T$ lines follow — lines $(2i - 1)$ and $2i$ of them describe the $i$-th string. The first line of the pair contains a single integer $n$ ($2 \le n \le 100$, $n$ is even) — the length of the corresponding string. The second line of the pair contains a string $s$, consisting of $n$ lowercase Latin letters.

-----Output-----

Print $T$ lines. The $i$-th line should contain the answer to the $i$-th string of the input. Print "YES" if it's possible to make the $i$-th string a palindrome by applying the aforementioned changes to every position. Print "NO"...

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

for _ in range(int(input())):
    n=int(input())
    s=input()
    s2=s[::-1]
    fail=False
    for i in range(len(s)):
        diff=abs(ord(s[i])-ord(s2[i]))
        if diff and diff!=2:
            print('NO')
            fail=True
            break
    if not fail: print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1027/B:
You are given a chessboard of size $n \times n$. It is filled with numbers from $1$ to $n^2$ in the following way: the first $\lceil \frac{n^2}{2} \rceil$ numbers from $1$ to $\lceil \frac{n^2}{2} \rceil$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $n^2 - \lceil \frac{n^2}{2} \rceil$ numbers from $\lceil \frac{n^2}{2} \rceil + 1$ to $n^2$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $\lceil\frac{x}{y}\rceil$ means division $x$ by $y$ rounded up.

For example, the left board on the following picture is the chessboard which is given for $n=4$ and the right board is the chessboard which is given for $n=5$. [Image]

You are given $q$ queries. The $i$-th query is described as a pair $x_i, y_i$. The answer to the $i$-th query is the number written in the cell $x_i, y_i$ ($x_i$ is the row, $y_i$ is the column). Rows and columns are numbered from $1$ to $n$.

-----Input-----

The first line contains two integers $n$ and $q$ ($1 \le n \le 10^9$, $1 \le q \le 10^5$) — the size of the board and the number of queries.

The next $q$ lines contain two integers each. The $i$-th line contains two integers $x_i, y_i$ ($1 \le x_i, y_i \le n$) — description of the $i$-th query.

-----Output-----

For each query from $1$ to $q$ print the answer to this query. The answer to the $i$-th query is the number written in the cell $x_i, y_i$ ($x_i$ is the row, $y_i$ is the column). Rows and columns are numbered from $1$ to $n$. Queries are numbered from $1$ to $q$ in order of the input.

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

Output
1
8
16
13
4

Input
5 4
2 1
4 2
3 3
3 4

Output
16
9
7
20

-----Note-----

Answers to the queries from examples are on the board in the picture from the problem statement.

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

import sys

def query(n, x, y):
    num = ((x - 1)*n)//2 + (y + 1)//2
    factor = (x + 1) % 2 if n % 2 == 1 else 0
    return num + factor if (x + y) % 2 == 0 else (n*n + 1)//2 + num

n, q = list(map(int, sys.stdin.readline().split()))
for line in sys.stdin:
    print(query(n, *list(map(int, line.split()))))


I found an interesting problem on https://codeforces.com/problemset/problem/1027/C:
You have $n$ sticks of the given lengths.

Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.

Let $S$ be the area of the rectangle and $P$ be the perimeter of the rectangle.

The chosen rectangle should have the value $\frac{P^2}{S}$ minimal possible. The value is taken without any rounding.

If there are multiple answers, print any of them.

Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately.

-----Input-----

The first line contains a single integer $T$ ($T \ge 1$) — the number of lists of sticks in the testcase.

Then $2T$ lines follow — lines $(2i - 1)$ and $2i$ of them describe the $i$-th list. The first line of the pair contains a single integer $n$ ($4 \le n \le 10^6$) — the number of sticks in the $i$-th list. The second line of the pair contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_j \le 10^4$) — lengths of the sticks in the $i$-th list.

It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle.

The total number of sticks in all $T$ lists doesn't exceed $10^6$ in each testcase.

-----Output-----

Print $T$ lines. The $i$-th line should contain the answer to the $i$-th list of the input. That is the lengths of the four sticks you choose from the $i$-th list, so that they form a rectangle and the value $\frac{P^2}{S}$ of this rectangle is minimal possible. You can print these four lengths in arbitrary order.

If there are multiple answers, print any of them.

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

Output
2 7 7 2
2 2 1 1
5 5 5 5

-----Note-----

There is only one way to choose four sticks in the first list, they form a rectangle with sides $2$ and $7$, its area is $2 \cdot 7 = 14$, perimeter is $2(2 + 7) = 18$....

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

import sys
from collections import *
l=sys.stdin.readlines()[2::2]
r=[]
for a in l:
 a=Counter(map(int,a.split()))
 s=sorted([k for k in a if a[k]>1]+[k for k in a if a[k]>3])
 a=min(zip(s,s[1:]),key=lambda a:sum(a)**2/a[0]/a[1])
 r+=['%d %d '%a*2]
print('\n'.join(r))


I found an interesting problem on https://codeforces.com/problemset/problem/1027/D:
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $80\%$ of applicants are girls and majority of them are going to live in the university dormitory for the next $4$ (hopefully) years.

The dormitory consists of $n$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $i$ costs $c_i$ burles. Rooms are numbered from $1$ to $n$.

Mouse doesn't sit in place all the time, it constantly runs. If it is in room $i$ in second $t$ then it will run to room $a_i$ in second $t + 1$ without visiting any other rooms inbetween ($i = a_i$ means that mouse won't leave room $i$). It's second $0$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.

That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $1$ to $n$ at second $0$.

What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?

-----Input-----

The first line contains as single integers $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of rooms in the dormitory.

The second line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 10^4$) — $c_i$ is the cost of setting the trap in room number $i$.

The third line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) — $a_i$ is the room the mouse will run to the next second after being in room $i$.

-----Output-----

Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.

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

Output
3

Input
4
1 10 2 10
2 4 2 2

Output
10

Input
7
1 1 1 1 1 1 1
2 2 2 3 6 7 6

Output
2

-----Note-----

In the first example it is enough to set...

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

def main():
        n=int(input())
        c=[int(i) for i in input().split()]
        a=[int(i) for i in input().split()]
        vis=[0]*(n+1)
        sum=0
        for i in range(1,n+1):
                x=i
                while(vis[x]==0):
                        vis[x]=i
                        x=a[x-1]
                if vis[x]!=i:
                        continue
                p=x
                cos=c[x-1]
                while(p!=a[x-1]):
                        x=a[x-1]
                        cos=min(c[x-1],cos)
                sum=sum+cos
        return sum
print(main())


I found an interesting problem on https://codeforces.com/problemset/problem/1027/E:
You are given a square board, consisting of $n$ rows and $n$ columns. Each tile in it should be colored either white or black.

Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well.

Let's call some coloring suitable if it is beautiful and there is no rectangle of the single color, consisting of at least $k$ tiles.

Your task is to count the number of suitable colorings of the board of the given size.

Since the answer can be very large, print it modulo $998244353$.

-----Input-----

A single line contains two integers $n$ and $k$ ($1 \le n \le 500$, $1 \le k \le n^2$) — the number of rows and columns of the board and the maximum number of tiles inside the rectangle of the single color, respectively.

-----Output-----

Print a single integer — the number of suitable colorings of the board of the given size modulo $998244353$.

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

Output
0

Input
2 3

Output
6

Input
49 1808

Output
359087121

-----Note-----

Board of size $1 \times 1$ is either a single black tile or a single white tile. Both of them include a rectangle of a single color, consisting of $1$ tile.

Here are the beautiful colorings of a board of size $2 \times 2$ that don't include rectangles of a single color, consisting of at least $3$ tiles: [Image]

The rest of beautiful colorings of a board of size $2 \times 2$ are the following: [Image]

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

def norm(x):
    return (x % 998244353 + 998244353) % 998244353

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

dp1 = [0]
dp2 = [0]

for i in range(n):
    l = [1]
    cur = 0
    for j in range(n + 1):
        cur += l[j]
        if(j > i):
            cur -= l[j - i - 1]
        cur = norm(cur)
        l.append(cur)
    dp1.append(l[n])
    dp2.append(norm(dp1[i + 1] - dp1[i]))

ans = 0
for i in range(n + 1):
    for j in range(n + 1):
        if(i * j < k):
            ans = norm(ans + dp2[i] * dp2[j])

ans = norm(ans * 2)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1027/G:
The campus has $m$ rooms numbered from $0$ to $m - 1$. Also the $x$-mouse lives in the campus. The $x$-mouse is not just a mouse: each second $x$-mouse moves from room $i$ to the room $i \cdot x \mod{m}$ (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the $x$-mouse is unknown.

You are responsible to catch the $x$-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the $x$-mouse enters a trapped room, it immediately gets caught.

And the only observation you made is $\text{GCD} (x, m) = 1$.

-----Input-----

The only line contains two integers $m$ and $x$ ($2 \le m \le 10^{14}$, $1 \le x < m$, $\text{GCD} (x, m) = 1$) — the number of rooms and the parameter of $x$-mouse.

-----Output-----

Print the only integer — minimum number of traps you need to install to catch the $x$-mouse.

-----Examples-----
Input
4 3

Output
3

Input
5 2

Output
2

-----Note-----

In the first example you can, for example, put traps in rooms $0$, $2$, $3$. If the $x$-mouse starts in one of this rooms it will be caught immediately. If $x$-mouse starts in the $1$-st rooms then it will move to the room $3$, where it will be caught.

In the second example you can put one trap in room $0$ and one trap in any other room since $x$-mouse will visit all rooms $1..m-1$ if it will start in any of these rooms.

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

from math import gcd
def powmod(a,b,m):
 a%=m
 r=1
 while b:
  if b&1:r=r*a%m
  a=a*a%m
  b>>=1
 return r

def f(n):
 r=[]
 if (n&1)==0:
  e=0
  while (n&1)==0:n>>=1;e+=1
  yield (2,e)
 p=3
 while n>1:
  if p*p>n:p=n
  if n%p:
   p+=2
   continue
  e=1;n//=p
  while n%p==0:n//=p;e+=1
  yield (p,e)
  p+=2
 return r
m,x=map(int,input().split())
p=2
r=[(1,1)]
for p,e in f(m):
 assert e>=1
 ord=p-1
 assert powmod(x,ord,p)==1
 for pi,ei in f(p-1):
  while ord % pi == 0 and powmod(x,ord//pi,p)==1: ord//=pi
 ords=[(1,1),(ord,p-1)]
 q=p
 for v in range(2,e+1):
  q*=p
  if powmod(x,ord,q)!=1:ord*=p
  assert powmod(x,ord,q)==1
  ords.append((ord,q//p*(p-1)))
 r=[(a//gcd(a,c)*c,b*d) for a,b in r for c,d in ords]
print(sum(y//x for x,y in r))


I found an interesting problem on https://codeforces.com/problemset/problem/1028/A:
Consider a table of size $n \times m$, initially fully white. Rows are numbered $1$ through $n$ from top to bottom, columns $1$ through $m$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n, m \le 115$) — the number of rows and the number of columns in the table.

The $i$-th of the next $n$ lines contains a string of $m$ characters $s_{i1} s_{i2} \ldots s_{im}$ ($s_{ij}$ is 'W' for white cells and 'B' for black cells), describing the $i$-th row of the table.

-----Output-----

Output two integers $r$ and $c$ ($1 \le r \le n$, $1 \le c \le m$) separated by a space — the row and column numbers of the center of the black square.

-----Examples-----
Input
5 6
WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW

Output
2 4

Input
3 3
WWW
BWW
WWW

Output
2 1

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

n, m = map(int, input().split())
arr = [input() for i in range(n)]
x_c = []
y_c = []
for i in range(n):
	for j in range(m):
		if arr[i][j] == 'B':
			x_c.append(i)
			y_c.append(j)
x_c.sort()
y_c.sort()

print(x_c[len(x_c) // 2] + 1, y_c[len(y_c) // 2] + 1)


I found an interesting problem on https://codeforces.com/problemset/problem/1028/C:
You are given $n$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $(n-1)$ of the given $n$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.

Find any point with integer coordinates that belongs to at least $(n-1)$ given rectangles.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 132\,674$) — the number of given rectangles.

Each the next $n$ lines contains four integers $x_1$, $y_1$, $x_2$ and $y_2$ ($-10^9 \le x_1 < x_2 \le 10^9$, $-10^9 \le y_1 < y_2 \le 10^9$) — the coordinates of the bottom left and upper right corners of a rectangle.

-----Output-----

Print two integers $x$ and $y$ — the coordinates of any point that belongs to at least $(n-1)$ given rectangles.

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

Output
1 1

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

Output
1 1

Input
4
0 0 5 5
0 0 4 4
1 1 4 4
1 1 4 4

Output
1 1

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

Output
3 4

-----Note-----

The picture below shows the rectangles in the first and second samples. The possible answers are highlighted. [Image]

The picture below shows the rectangles in the third and fourth samples. [Image]

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

def excl_max_list(a):
    first_max = max(a)
    imax = a.index(first_max)
    second_max = max(a[:imax] + a[imax + 1:])
    return [second_max if elem == first_max else first_max for elem in a]

def excl_min_list(a):
    first_min = min(a)
    imin = a.index(first_min)
    second_min = min(a[:imin] + a[imin + 1:])
    return [second_min if elem == first_min else first_min for elem in a]

n = int(input())
rectangles = [tuple(map(int, input().split())) for i in range(n)]
lefts = [l for l, d, r, u in rectangles]
rights = [r for l, d, r, u in rectangles]
downs = [d for l, d, r, u in rectangles]
ups = [u for l, d, r, u in rectangles]

max_lefts = excl_max_list(lefts)
max_downs = excl_max_list(downs)
min_rights = excl_min_list(rights)
min_ups = excl_min_list(ups)

for i in range(n):
    if max_lefts[i] <= min_rights[i] and max_downs[i] <= min_ups[i]:
        print(max_lefts[i], max_downs[i])
        break


I found an interesting problem on https://codeforces.com/problemset/problem/1029/A:
You are given a string $t$ consisting of $n$ lowercase Latin letters and an integer number $k$.

Let's define a substring of some string $s$ with indices from $l$ to $r$ as $s[l \dots r]$.

Your task is to construct such string $s$ of minimum possible length that there are exactly $k$ positions $i$ such that $s[i \dots i + n - 1] = t$. In other words, your task is to construct such string $s$ of minimum possible length that there are exactly $k$ substrings of $s$ equal to $t$.

It is guaranteed that the answer is always unique.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 50$) — the length of the string $t$ and the number of substrings.

The second line of the input contains the string $t$ consisting of exactly $n$ lowercase Latin letters.

-----Output-----

Print such string $s$ of minimum possible length that there are exactly $k$ substrings of $s$ equal to $t$.

It is guaranteed that the answer is always unique.

-----Examples-----
Input
3 4
aba

Output
ababababa

Input
3 2
cat

Output
catcat

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

s=input().split()
n=int(s[0])
k=int(s[1])
s=input()
if n==1:
    print(s*k)
elif k==1:
    print(s)
else:
    flag=True
    for i in range(1,n):
        if s[:-i]==s[i:]:
            print(s+s[-i:]*(k-1))
            flag=False
            break
    if flag:
        print(s*k)


I found an interesting problem on https://codeforces.com/problemset/problem/1029/B:
You are given a problemset consisting of $n$ problems. The difficulty of the $i$-th problem is $a_i$. It is guaranteed that all difficulties are distinct and are given in the increasing order.

You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $a_{i_1}, a_{i_2}, \dots, a_{i_p}$ be the difficulties of the selected problems in increasing order. Then for each $j$ from $1$ to $p-1$ $a_{i_{j + 1}} \le a_{i_j} \cdot 2$ should hold. It means that the contest consisting of only one problem is always valid.

Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.

-----Input-----

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

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.

-----Output-----

Print a single integer — maximum number of problems in the contest satisfying the condition in the problem statement.

-----Examples-----
Input
10
1 2 5 6 7 10 21 23 24 49

Output
4

Input
5
2 10 50 110 250

Output
1

Input
6
4 7 12 100 150 199

Output
3

-----Note-----

Description of the first example: there are $10$ valid contests consisting of $1$ problem, $10$ valid contests consisting of $2$ problems ($[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$),...

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

n = int(input())
line = list(map(int, input().split()))
ans = 1
prev_i = 0
for i in range(1, n):
    if line[i - 1] * 2 >= line[i]:
        continue
    ans = max(i - prev_i, ans)
    prev_i = i
ans = max(n - prev_i, ans)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1029/C:
You are given $n$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.

The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $0$ in case the intersection is an empty set.

For example, the intersection of segments $[1;5]$ and $[3;10]$ is $[3;5]$ (length $2$), the intersection of segments $[1;5]$ and $[5;7]$ is $[5;5]$ (length $0$) and the intersection of segments $[1;5]$ and $[6;6]$ is an empty set (length $0$).

Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $(n - 1)$ segments has the maximal possible length.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of segments in the sequence.

Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($0 \le l_i \le r_i \le 10^9$) — the description of the $i$-th segment.

-----Output-----

Print a single integer — the maximal possible length of the intersection of $(n - 1)$ remaining segments after you remove exactly one segment from the sequence.

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

Output
1

Input
5
2 6
1 3
0 4
1 20
0 4

Output
2

Input
3
4 5
1 2
9 20

Output
0

Input
2
3 10
1 5

Output
7

-----Note-----

In the first example you should remove the segment $[3;3]$, the intersection will become $[2;3]$ (length $1$). Removing any other segment will result in the intersection $[3;3]$ (length $0$).

In the second example you should remove the segment $[1;3]$ or segment $[2;6]$, the intersection will become $[2;4]$ (length $2$) or $[1;3]$ (length $2$), respectively. Removing any other segment will...

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

N=int(input())

A=[None]*N
for i in range(N):
    A[i]=list(map(int,input().split()))

A.sort(key=lambda x:x[1])
left=sorted(A)
right=sorted(A[::-1],key=lambda x:x[1])

X=left[:N-1]
Y=right[1:]

aa=min(X,key=lambda x:x[1])[1]-max(X)[0]
bb=min(Y,key=lambda x:x[1])[1]-max(Y)[0]

print(max(aa,bb,0))


I found an interesting problem on https://codeforces.com/problemset/problem/1029/D:
You are given an array $a$, consisting of $n$ positive integers.

Let's call a concatenation of numbers $x$ and $y$ the number that is obtained by writing down numbers $x$ and $y$ one right after another without changing the order. For example, a concatenation of numbers $12$ and $3456$ is a number $123456$.

Count the number of ordered pairs of positions $(i, j)$ ($i \neq j$) in array $a$ such that the concatenation of $a_i$ and $a_j$ is divisible by $k$.

-----Input-----

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

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

-----Output-----

Print a single integer — the number of ordered pairs of positions $(i, j)$ ($i \neq j$) in array $a$ such that the concatenation of $a_i$ and $a_j$ is divisible by $k$.

-----Examples-----
Input
6 11
45 1 10 12 11 7

Output
7

Input
4 2
2 78 4 10

Output
12

Input
5 2
3 7 19 3 3

Output
0

-----Note-----

In the first example pairs $(1, 2)$, $(1, 3)$, $(2, 3)$, $(3, 1)$, $(3, 4)$, $(4, 2)$, $(4, 3)$ suffice. They produce numbers $451$, $4510$, $110$, $1045$, $1012$, $121$, $1210$, respectively, each of them is divisible by $11$.

In the second example all $n(n - 1)$ pairs suffice.

In the third example no pair is sufficient.

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

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

n,k=list(map(int,input().split()))
A=list(map(int,input().split()))

D=[Counter() for i in range(11)]
for a in A:
    for j in range(1,11):
        D[j][a*(10**j)%k]+=1

ANS=0
for a in A:
    L=len(str(a))
    x=-a%k

    if a*(10**L)%k==x:
        ANS-=1

    ANS+=D[L][x]

print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1029/E:
You are given an undirected tree consisting of $n$ vertices. An undirected tree is a connected undirected graph with $n - 1$ edges.

Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $1$ to any other vertex is at most $2$. Note that you are not allowed to add loops and multiple edges.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of vertices in the tree.

The following $n - 1$ lines contain edges: edge $i$ is given as a pair of vertices $u_i, v_i$ ($1 \le u_i, v_i \le n$). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.

-----Output-----

Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex $1$ to any other vertex at most $2$. Note that you are not allowed to add loops and multiple edges.

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

Output
2

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

Output
0

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

Output
1

-----Note-----

The tree corresponding to the first example: [Image] The answer is $2$, some of the possible answers are the following: $[(1, 5), (1, 6)]$, $[(1, 4), (1, 7)]$, $[(1, 6), (1, 7)]$.

The tree corresponding to the second example: [Image] The answer is $0$.

The tree corresponding to the third example: [Image] The answer is $1$, only one possible way to reach it is to add the edge $(1, 3)$.

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

from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
    u,v = map(int,stdin.readline().split())
    g.setdefault(u-1,[]).append(v-1)
    g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
    top = st.pop()
    msk[top] = 1
    for c in g[top]:
        if msk[c] == 0:
            st.append(c)
            tree[c] = top
            rank[c] = rank[top]+1
            rd.setdefault(rank[c], []).append(c)
max_rank = max(rank)
reach = [0]*n
build = [0]*n
ans = 0
for r in range(max_rank, 2, -1):
    for node in rd[r]:
        if reach[node] == 0:
            reach[node] = 1
            reach[tree[node]] = 1
            reach[tree[tree[node]]] = 1
            build[tree[node]] = 1
print(sum(build))


I found an interesting problem on https://codeforces.com/problemset/problem/1029/F:
There is an infinite board of square tiles. Initially all tiles are white.

Vova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly $a$ red tiles and exactly $b$ blue tiles across the board.

Vova wants to color such a set of tiles that:

  they would form a rectangle, consisting of exactly $a+b$ colored tiles;  all tiles of at least one color would also form a rectangle.

Here are some examples of correct colorings:

 [Image]

Here are some examples of incorrect colorings:

 [Image]

Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?

It is guaranteed that there exists at least one correct coloring.

-----Input-----

A single line contains two integers $a$ and $b$ ($1 \le a, b \le 10^{14}$) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively.

-----Output-----

Print a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly $a$ tiles red and exactly $b$ tiles blue.

It is guaranteed that there exists at least one correct coloring.

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

Output
12

Input
3 9

Output
14

Input
9 3

Output
14

Input
3 6

Output
12

Input
506 2708

Output
3218

-----Note-----

The first four examples correspond to the first picture of the statement.

Note that for there exist multiple correct colorings for all of the examples.

In the first example you can also make a rectangle with sides $1$ and $8$, though its perimeter will be $18$ which is greater than $8$.

In the second example you can make the same resulting rectangle with sides $3$ and $4$, but red tiles will form the rectangle with sides $1$ and $3$ and blue tiles will form the rectangle with sides $3$ and $3$.

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

import math
a,b = [int(x) for x in input().split()]

area = a+b
t = int(math.sqrt(area))
sa = int(math.sqrt(a))
sb = int(math.sqrt(b))

D = []
DA = []
DB = []
for i in range(1,t+1):
    if area % i == 0:
        if i*i != area:
            D.append(i)
            D.append(area//i)
        else:
            D.append(i)

for i in range(1,sa+1):
    if a % i == 0:
        if i*i != a:
            DA.append(i)
            DA.append(a//i)
        else:
            DA.append(i)

for i in range(1,sb+1):
    if b % i == 0:
        if i*i != b:
            DB.append(i)
            DB.append(b//i)
        else:
            DB.append(i)
DA.sort()
DB.sort()
D.sort()

start = ((len(D)+1)//2)-1
div = len(D)

def closestdiv(t,D):
    low = 0
    high = len(D)-1
    while high - low > 1:
        guess = (high+low)//2
        if D[guess] > t:
            high = guess
        else:
            low = guess
    if D[high] <= t:
        return high
    else:
        return low

while start > -1:
    t = D[start]
    s = D[-start-1]
    if DA[-closestdiv(t,DA)-1] <= s:
        print(2*t+2*s)
        break
    elif DB[-closestdiv(t,DB)-1] <= s:
        print(2*t+2*s)
        break
    start -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1030/A:
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked $n$ people about their opinions. Each person answered whether this problem is easy or hard.

If at least one of these $n$ people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 100$) — the number of people who were asked to give their opinions.

The second line contains $n$ integers, each integer is either $0$ or $1$. If $i$-th integer is $0$, then $i$-th person thinks that the problem is easy; if it is $1$, then $i$-th person thinks that the problem is hard.

-----Output-----

Print one word: "EASY" if the problem is easy according to all responses, or "HARD" if there is at least one person who thinks the problem is hard.

You may print every letter in any register: "EASY", "easy", "EaSY" and "eAsY" all will be processed correctly.

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

Output
HARD

Input
1
0

Output
EASY

-----Note-----

In the first example the third person says it's a hard problem, so it should be replaced.

In the second example the problem easy for the only person, so it doesn't have to be replaced.

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

n,a=int(input()),input()
if '1'in a:print("HARD")
else:print("EASY")


I found an interesting problem on https://codeforces.com/problemset/problem/1030/B:
Vasya owns a cornfield which can be defined with two integers $n$ and $d$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $(0, d), (d, 0), (n, n - d)$ and $(n - d, n)$.

 [Image] An example of a cornfield with $n = 7$ and $d = 2$.

Vasya also knows that there are $m$ grasshoppers near the field (maybe even inside it). The $i$-th grasshopper is at the point $(x_i, y_i)$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.

Help Vasya! For each grasshopper determine if it is inside the field (including the border).

-----Input-----

The first line contains two integers $n$ and $d$ ($1 \le d < n \le 100$).

The second line contains a single integer $m$ ($1 \le m \le 100$) — the number of grasshoppers.

The $i$-th of the next $m$ lines contains two integers $x_i$ and $y_i$ ($0 \le x_i, y_i \le n$) — position of the $i$-th grasshopper.

-----Output-----

Print $m$ lines. The $i$-th line should contain "YES" if the position of the $i$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $i$-th line should contain "NO".

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

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

Output
YES
NO
NO
YES

Input
8 7
4
4 4
2 8
8 1
6 1

Output
YES
NO
YES
YES

-----Note-----

The cornfield from the first example is pictured above. Grasshoppers with indices $1$ (coordinates $(2, 4)$) and $4$ (coordinates $(4, 5)$) are inside the cornfield.

The cornfield from the second example is pictured below. Grasshoppers with indices $1$ (coordinates $(4, 4)$), $3$ (coordinates $(8, 1)$) and $4$ (coordinates $(6, 1)$) are inside the cornfield.  [Image]

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

n, d = list(map(int, input().split()))
m = int(input())

for i in range(m):
    x, y = list(map(int, input().split()))
    if (y >= x - d) and (y <= x + d) and (y >= -x + d) and (y <= -x + 2*n - d):
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1030/C:
Recently Vasya found a golden ticket — a sequence which consists of $n$ digits $a_1a_2\dots a_n$. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket $350178$ is lucky since it can be divided into three segments $350$, $17$ and $8$: $3+5+0=1+7=8$. Note that each digit of sequence should belong to exactly one segment.

Help Vasya! Tell him if the golden ticket he found is lucky or not.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 100$) — the number of digits in the ticket.

The second line contains $n$ digits $a_1 a_2 \dots a_n$ ($0 \le a_i \le 9$) — the golden ticket. Digits are printed without spaces.

-----Output-----

If the golden ticket is lucky then print "YES", otherwise print "NO" (both case insensitive).

-----Examples-----
Input
5
73452

Output
YES

Input
4
1248

Output
NO

-----Note-----

In the first example the ticket can be divided into $7$, $34$ and $52$: $7=3+4=5+2$.

In the second example it is impossible to divide ticket into segments with equal sum.

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

def check(a, count):
    ks = 0
    for i in range(len(a)):
        ks += a[i]
        if ks > count:
            return False
        elif ks == count:
            ks = 0

    return True

n = int(input())
a = list(map(int, list(input())))
ss = sum(a)
flag = False
for k in range(2, 1000):
    if ss % k == 0:
        if check(a, ss // k):
            flag = True
            break
if flag:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1030/D:
Vasya has got three integers $n$, $m$ and $k$. He'd like to find three integer points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$, such that $0 \le x_1, x_2, x_3 \le n$, $0 \le y_1, y_2, y_3 \le m$ and the area of the triangle formed by these points is equal to $\frac{nm}{k}$.

Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

-----Input-----

The single line contains three integers $n$, $m$, $k$ ($1\le n, m \le 10^9$, $2 \le k \le 10^9$).

-----Output-----

If there are no such points, print "NO".

Otherwise print "YES" in the first line. The next three lines should contain integers $x_i, y_i$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them.

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

-----Examples-----
Input
4 3 3

Output
YES
1 0
2 3
4 1

Input
4 4 7

Output
NO

-----Note-----

In the first example area of the triangle should be equal to $\frac{nm}{k} = 4$. The triangle mentioned in the output is pictured below:  [Image]

In the second example there is no triangle with area $\frac{nm}{k} = \frac{16}{7}$.

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

def gcd(a, b):
    while b:
        a, b = b, a%b
    return a
n,m,k=list(map(int,input().split()))
if (2*n*m)%k==0:
    c=0
    if k%2!=0:
        c=1
    else:
        k//=2
    a=n//gcd(k,n)
    k//=gcd(k,n)
    b=m//gcd(m,k)
    if c==1:
        if a*2>n and a*2>m:
            b*=2
        else:
            a*=2
    if a>n or b>m:
        a,b=b,a
    print("YES")
    print("0 0")
    print("0",b)
    print(a,"0")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1030/E:
Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(\dots 000000001100_2)$, $1026$ $(\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.

Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$.

For the given sequence $a_1, a_2, \ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \le l \le r \le n$ and sequence $a_l, a_{l + 1}, \dots, a_r$ is good.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — length of the sequence.

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

-----Output-----

Print one integer — the number of pairs $(l, r)$ such that $1 \le l \le r \le n$ and the sequence $a_l, a_{l + 1}, \dots, a_r$ is good.

-----Examples-----
Input
3
6 7 14

Output
2

Input
4
1 2 1 16

Output
4

-----Note-----

In the first example pairs $(2, 3)$ and $(1, 3)$ are valid. Pair $(2, 3)$ is valid since $a_2 = 7 \rightarrow 11$, $a_3 = 14 \rightarrow 11$ and $11 \oplus 11 = 0$, where $\oplus$ — bitwise exclusive or. Pair $(1, 3)$ is valid since $a_1 = 6 \rightarrow 3$, $a_2 = 7 \rightarrow 13$, $a_3 = 14 \rightarrow 14$ and $3 \oplus 13 \oplus 14 = 0$.

In the second example pairs $(1, 2)$, $(2, 3)$, $(3, 4)$ and $(1, 4)$ are valid.

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

from array import array
def popcount(x):
    res = 0;
    while(x > 0):
        res += (x & 1)
        x >>= 1
    return res

def main():
    n = int(input())
    a = array('i',[popcount(int(x)) for x in input().split(' ')])

    ans,s0,s1 = 0,0,0
    for i in range(n):
        if(a[i] & 1):
            s0,s1 = s1,s0 + 1
        else:
            s0,s1 = s0 + 1, s1
        ans += s0

    for i in range(n):
        mx,sum = a[i],0
        for j in range(i, min(n, i + 70)):
            mx = max(mx, a[j]<<1)
            sum += a[j]
            if( (sum & 1 is 0) and (mx > sum)):
                ans-=1
    print(ans)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/1031/A:
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into $w\times h$ cells. There should be $k$ gilded rings, the first one should go along the edge of the plate, the second one — $2$ cells away from the edge and so on. Each ring has a width of $1$ cell. Formally, the $i$-th of these rings should consist of all bordering cells on the inner rectangle of size $(w - 4(i - 1))\times(h - 4(i - 1))$.

 [Image] The picture corresponds to the third example.

Your task is to compute the number of cells to be gilded.

-----Input-----

The only line contains three integers $w$, $h$ and $k$ ($3 \le w, h \le 100$, $1 \le k \le \left\lfloor \frac{min(n, m) + 1}{4}\right\rfloor$, where $\lfloor x \rfloor$ denotes the number $x$ rounded down) — the number of rows, columns and the number of rings, respectively.

-----Output-----

Print a single positive integer — the number of cells to be gilded.

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

Output
8

Input
7 9 1

Output
28

Input
7 9 2

Output
40

-----Note-----

The first example is shown on the picture below.

 [Image]

The second example is shown on the picture below.

 [Image]

The third example is shown in the problem description.

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

(w, h, k) = list(map(int, input().split()))

ans = 0
i = 0
while i < k:
    ans += 2 * w
    w -= 4
    i += 1

h -= 2
i = 0
while i < k:
    ans += 2 * h
    h -= 4
    i += 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1031/B:
When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \le a_i \le 3$), and the elements of the second sequence as $b_i$ ($0 \le b_i \le 3$).

Masha became interested if or not there is an integer sequence of length $n$, which elements we will denote as $t_i$ ($0 \le t_i \le 3$), so that for every $i$ ($1 \le i \le n - 1$) the following is true:   $a_i = t_i | t_{i + 1}$ (where $|$ denotes the bitwise OR operation) and  $b_i = t_i \& t_{i + 1}$ (where $\&$ denotes the bitwise AND operation).

The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $t_i$ of length $n$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.

-----Input-----

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

The second line contains $n - 1$ integers $a_1, a_2, \ldots, a_{n-1}$ ($0 \le a_i \le 3$) — the first sequence on the blackboard.

The third line contains $n - 1$ integers $b_1, b_2, \ldots, b_{n-1}$ ($0 \le b_i \le 3$) — the second sequence on the blackboard.

-----Output-----

In the first line print "YES" (without quotes), if there is a sequence $t_i$ that satisfies the conditions from the statements, and "NO" (without quotes), if there is no such sequence.

If there is such a sequence, on the second line print $n$ integers $t_1, t_2, \ldots, t_n$ ($0 \le t_i \le 3$) — the sequence that satisfies the statements conditions.

If there are multiple answers, print any of them.

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

Output
YES
1 3 2 0
Input
3
1 3
3 2

Output
NO

-----Note-----

In the first example it's easy to see that the sequence from output satisfies the given conditions:   $t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1$ and $t_1 \& t_2 = (01_2) \& (11_2) = (01_2) = 1 = b_1$;  $t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2$ and $t_2 \& t_3 = (11_2) \&...

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

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for k in range(4):
    t = [-1] * n
    t[0] = k
    x = False
    for i in range(1, n):
        x = False
        for j in range(4):
            if a[i-1] == (j | t[i - 1]) and b[i-1] == (j & t[i - 1]):
                t[i] = j
                x = True
        if not x:
            break
    if x:
        print("YES")
        print(*t)
        return
print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/1031/C:
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.

Lesha knows that today he can study for at most $a$ hours, and he will have $b$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $k$ in $k$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.

Thus, the student has to fully read several lecture notes today, spending at most $a$ hours in total, and fully read several lecture notes tomorrow, spending at most $b$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?

-----Input-----

The only line of input contains two integers $a$ and $b$ ($0 \leq a, b \leq 10^{9}$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.

-----Output-----

In the first line print a single integer $n$ ($0 \leq n \leq a$) — the number of lecture notes Lesha has to read in the first day. In the second line print $n$ distinct integers $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq a$), the sum of all $p_i$ should not exceed $a$.

In the third line print a single integer $m$ ($0 \leq m \leq b$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $m$ distinct integers $q_1, q_2, \ldots, q_m$ ($1 \leq q_i \leq b$), the sum of all $q_i$ should not exceed $b$.

All integers $p_i$ and $q_i$ should be...

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

a, b = list(map(int,input().split()))
if a <= b:
    l = 0
    r = a + 1
    while r - l > 1:
        m = (l + r) // 2
        if m * (m + 1) // 2 > a:
            r = m
        else:
            l = m
    n = l
    a -= n*(n+1) // 2
    c = 1
    N = [i + 1 for i in range(n)]
    if a > 0:
        c = n + 1 - a
        N.pop(c - 1)
        N.append(c + a)
        N[-1] = c + a
    D = []
    if a != 0:
        b -= c
        D = [c]
        n = n + 1
    n += 1
    while b >= 0:
        b -= n
        D.append(n)
        n += 1
    D.pop(-1)
    print(len(N))
    if len(N) != 0:
        print(*N)
    print(len(D))
    if len(D) != 0:
        print(*D)
else:
    c = a
    a = b
    b = c
    l = 0
    r = a + 1
    while r - l > 1:
        m = (l + r) // 2
        if m * (m + 1) // 2 > a:
            r = m
        else:
            l = m
    n = l
    a -= n*(n+1) // 2
    c = 1
    N = [i + 1 for i in range(n)]
    if a > 0:
        c = n + 1 - a
        N.pop(c - 1)
        N.append(c + a)
        N[-1] = c + a
    D = []
    if a != 0:
        b -= c
        D = [c]
        n = n + 1
    n += 1
    while b >= 0:
        b -= n
        D.append(n)
        n += 1
    D.pop(-1)
    print(len(D))
    if len(D) != 0:
        print(*D)
    print(len(N))
    if len(N) != 0:
        print(*N)


I found an interesting problem on https://codeforces.com/problemset/problem/1031/D:
You are given a matrix of size $n \times n$ filled with lowercase English letters. You can change no more than $k$ letters in this matrix.

Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $2n - 1$.

Find the lexicographically smallest string that can be associated with a path after changing letters in at most $k$ cells of the matrix.

A string $a$ is lexicographically smaller than a string $b$, if the first different letter in $a$ and $b$ is smaller in $a$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 2000$, $0 \le k \le n^2$) — the size of the matrix and the number of letters you can change.

Each of the next $n$ lines contains a string of $n$ lowercase English letters denoting one row of the matrix.

-----Output-----

Output the lexicographically smallest string that can be associated with some valid path after changing no more than $k$ letters in the matrix.

-----Examples-----
Input
4 2
abcd
bcde
bcad
bcde

Output
aaabcde

Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw

Output
aaaepfafw

Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz

Output
aaaaaaadudsnz

-----Note-----

In the first sample test case it is possible to change letters 'b' in cells $(2, 1)$ and $(3, 1)$ to 'a', then the minimum path contains cells $(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$. The first coordinate corresponds to the row and the second coordinate corresponds to the column.

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

from array import array
inf = (1 << 30)

def main():
    (n,k) = [int(x) for x in input().split(' ')]
    Matrix = []
    for i in range(n):
        Matrix.append(array('b',[ord(x) for x in input()]))
    dp = [array('l', [inf for j in range(n)]) for i in range(n)]
    direct = [[ord('d') for j in range(n)] for i in range(n)]
    opt = ""
    for s in range (2 * n - 1):
        opchar = chr(ord('z') + 1)
        positions = []
        for i in range(0, s+1):
            j = s - i;
            if j < n and i < n:
                if(i > 0 and j > 0):
                    if(dp[i-1][j] < dp[i][j-1]):
                        dp[i][j] = dp[i-1][j]
                        direct[i][j] = 'l'
                    else:
                       dp[i][j] = dp[i][j-1]
                       direct[i][j] = 'd'
                elif i > 0:
                    dp[i][j] = dp[i-1][j]
                    direct[i][j] = 'l'
                elif j > 0:
                    dp[i][j] = dp[i][j-1]
                    direct[i][j] = 'd'
                else:
                    dp[i][j] = 0
                    direct[i][j] = 'e'
                if(dp[i][j] < k and Matrix[i][j] is not ord('a')):
                    dp[i][j]+=1
                    Matrix[i][j] = ord('a')
                if(Matrix[i][j] < ord(opchar) and dp[i][j] <= k):
                     opchar = chr(Matrix[i][j])
        for i in range(0, s+1):
            j = s - i;
            if j < n and i < n:
                if(Matrix[i][j] is not ord(opchar)):
                    dp[i][j] = inf
    ans = ""
    a,b = (n-1,n-1)
    while(direct[a][b] is not 'e'):
        ans += chr(Matrix[a][b])
        if(direct[a][b] is 'l'):
            a-=1
        else:
            b-=1
    ans += chr(Matrix[0][0])
    print(ans[::-1])

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1032/A:
The king's birthday dinner was attended by $k$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.

All types of utensils in the kingdom are numbered from $1$ to $100$. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.

After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.

-----Input-----

The first line contains two integer numbers $n$ and $k$ ($1 \le n \le 100, 1 \le k \le 100$)  — the number of kitchen utensils remaining after the dinner and the number of guests correspondingly.

The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$)  — the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils.

-----Output-----

Output a single value — the minimum number of utensils that could be stolen by the guests.

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

Output
1

Input
10 3
1 3 3 1 3 5 5 5 5 100

Output
14

-----Note-----

In the first example it is clear that at least one utensil of type $3$ has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set $(1, 2, 3)$ of utensils. Therefore, the answer is $1$.

One can show that in the second example at least $2$ dishes should have been served for every guest, so the number...

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

n, k = list(map(int, input().split()))
prib = list(map(int, input().split()))
prib.sort()
I = 0
p = []
while I < n:
    a = prib[I]
    p.append(0)
    while I < n and a == prib[I]:
        I += 1
        p[-1] += 1
p.sort()
l = (p[-1] - 1) // k + 1
l *= k
ans = 0
for i in p:
    ans += l - i
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1032/D:
In this problem we consider a very simplified model of Barcelona city.

Barcelona can be represented as a plane with streets of kind $x = c$ and $y = c$ for every integer $c$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $(x, y)$ for which $ax + by + c = 0$.

One can walk along streets, including the avenue. You are given two integer points $A$ and $B$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $B$ from $A$.

-----Input-----

The first line contains three integers $a$, $b$ and $c$ ($-10^9\leq a, b, c\leq 10^9$, at least one of $a$ and $b$ is not zero) representing the Diagonal Avenue.

The next line contains four integers $x_1$, $y_1$, $x_2$ and $y_2$ ($-10^9\leq x_1, y_1, x_2, y_2\leq 10^9$) denoting the points $A = (x_1, y_1)$ and $B = (x_2, y_2)$.

-----Output-----

Find the minimum possible travel distance between $A$ and $B$. Your answer is considered correct if its absolute or relative error does not exceed $10^{-6}$.

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

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

Output
4.2426406871

Input
3 1 -9
0 3 3 -1

Output
6.1622776602

-----Note-----

The first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot. [Image]

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


I found an interesting problem on https://codeforces.com/problemset/problem/1033/A:
Alice and Bob are playing chess on a huge chessboard with dimensions $n \times n$. Alice has a single piece left — a queen, located at $(a_x, a_y)$, while Bob has only the king standing at $(b_x, b_y)$. Alice thinks that as her queen is dominating the chessboard, victory is hers.

But Bob has made a devious plan to seize the victory for himself — he needs to march his king to $(c_x, c_y)$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.

Bob will win if he can move his king from $(b_x, b_y)$ to $(c_x, c_y)$ without ever getting in check. Remember that a king can move to any of the $8$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen.

Find whether Bob can win or not.

-----Input-----

The first line contains a single integer $n$ ($3 \leq n \leq 1000$) — the dimensions of the chessboard.

The second line contains two integers $a_x$ and $a_y$ ($1 \leq a_x, a_y \leq n$) — the coordinates of Alice's queen.

The third line contains two integers $b_x$ and $b_y$ ($1 \leq b_x, b_y \leq n$) — the coordinates of Bob's king.

The fourth line contains two integers $c_x$ and $c_y$ ($1 \leq c_x, c_y \leq n$) — the coordinates of the location that Bob wants to get to.

It is guaranteed that Bob's king is currently not in check and the target location is not in check either.

Furthermore, the king is not located on the same square as the queen (i.e. $a_x \neq b_x$ or $a_y \neq b_y$), and the target does coincide neither with the queen's position (i.e. $c_x \neq a_x$ or $c_y \neq a_y$) nor with the king's position (i.e. $c_x \neq b_x$ or $c_y \neq b_y$).

-----Output-----

Print "YES" (without quotes) if Bob can get from $(b_x, b_y)$ to $(c_x, c_y)$ without ever getting in check, otherwise print "NO".

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

-----Examples-----
Input
8
4 4
1 3
3 1

Output
YES

Input
8
4 4
2...

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

size = int(input())
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())

if (y2 - y1) * (y3 - y1) > 0 and (x2 - x1) * (x3 - x1) > 0 and x1 + y1 != x3 + y3:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1033/B:
Alice has a lovely piece of cloth. It has the shape of a square with a side of length $a$ centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length $b$ centimeters (where $b < a$). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to Bob. Now she is left with an ugly L shaped cloth (see pictures below).

Alice would like to know whether the area of her cloth expressed in square centimeters is prime. Could you help her to determine it?

-----Input-----

The first line contains a number $t$ ($1 \leq t \leq 5$) — the number of test cases.

Each of the next $t$ lines describes the $i$-th test case. It contains two integers $a$ and $b~(1 \leq b < a \leq 10^{11})$ — the side length of Alice's square and the side length of the square that Bob wants.

-----Output-----

Print $t$ lines, where the $i$-th line is the answer to the $i$-th test case. Print "YES" (without quotes) if the area of the remaining piece of cloth is prime, otherwise print "NO".

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

-----Example-----
Input
4
6 5
16 13
61690850361 24777622630
34 33

Output
YES
NO
NO
YES

-----Note-----

The figure below depicts the first test case. The blue part corresponds to the piece which belongs to Bob, and the red part is the piece that Alice keeps for herself. The area of the red part is $6^2 - 5^2 = 36 - 25 = 11$, which is prime, so the answer is "YES". [Image]

In the second case, the area is $16^2 - 13^2 = 87$, which is divisible by $3$. [Image]

In the third case, the area of the remaining piece is $61690850361^2 - 24777622630^2 = 3191830435068605713421$. This number is not prime because $3191830435068605713421 = 36913227731 \cdot 86468472991 $.

In the last case, the area is $34^2 - 33^2 = 67$.

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

t=int(input())
a=[]
b=[]
for i in range(t):
    aa,bb=[int(el) for el in input().split()]
    a.append(aa)
    b.append(bb)

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

for i in range(t):
    if a[i]-b[i]!=1:
        print ('NO')
        continue
    if prost(a[i]+b[i]):
        print('YES')
    else:
        print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/1033/C:
After a long day, Alice and Bob decided to play a little game. The game board consists of $n$ cells in a straight line, numbered from $1$ to $n$, where each cell contains a number $a_i$ between $1$ and $n$. Furthermore, no two cells contain the same number.

A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell $i$ to cell $j$ only if the following two conditions are satisfied:   the number in the new cell $j$ must be strictly larger than the number in the old cell $i$ (i.e. $a_j > a_i$), and  the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. $|i-j|\bmod a_i = 0$).

Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). Furthermore, there are no pair of indices $i \neq j$ such that $a_i = a_j$.

-----Output-----

Print $s$ — a string of $n$ characters, where the $i$-th character represents the outcome of the game if the token is initially placed in the cell $i$. If Alice wins, then $s_i$ has to be equal to "A"; otherwise, $s_i$ has to be equal to "B".

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

Output
BAAAABAB

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

Output
ABAAAABBBAABAAB

-----Note-----

In the first sample, if Bob puts the token on the number (not position):   $1$: Alice can move to any number. She can win by picking $7$, from which Bob has no move.  $2$: Alice can move to $3$ and $5$. Upon moving to $5$, Bob can win by moving to $8$. If she chooses $3$ instead, she wins, as Bob has only a move to $4$, from which Alice can move to $8$.  $3$: Alice can...

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

n = int(input())
board = list(map(int,input().split(" ")))
index = list(range(0,n))
ascending = [x for _,x in sorted(zip(board,index))]

winners = n * [""]

for c in reversed(ascending):
	if board[c] == n:
		winners[c] = "B"
	# going down
	toCheck = c - board[c]
	while(toCheck >= 0):
		if winners[toCheck] == "B":
			winners[c] = "A"
		toCheck = toCheck - board[c]
	if winners[c] == "":
		toCheck = c + board[c]
		while(toCheck < n):
			if winners[toCheck] == "B":
				winners[c] = "A"
			toCheck = toCheck + board[c]
	if winners[c] == "":
		winners[c] = "B"
	#print("board at c",board[c])
	#print(c)
	#print(winners)

for i in range(n):
	print(winners[i],end="")
print()


I found an interesting problem on https://codeforces.com/problemset/problem/1034/B:
Little C loves number «3» very much. He loves all things about it.

Now he is playing a game on a chessboard of size $n \times m$. The cell in the $x$-th row and in the $y$-th column is called $(x,y)$. Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly $3$. The Manhattan distance between two cells $(x_i,y_i)$ and $(x_j,y_j)$ is defined as $|x_i-x_j|+|y_i-y_j|$.

He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.

-----Input-----

A single line contains two integers $n$ and $m$ ($1 \leq n,m \leq 10^9$) — the number of rows and the number of columns of the chessboard.

-----Output-----

Print one integer — the maximum number of chessmen Little C can place.

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

Output
0
Input
3 3

Output
8

-----Note-----

In the first example, the Manhattan distance between any two cells is smaller than $3$, so the answer is $0$.

In the second example, a possible solution is $(1,1)(3,2)$, $(1,2)(3,3)$, $(2,1)(1,3)$, $(3,1)(2,3)$.

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


I found an interesting problem on https://codeforces.com/problemset/problem/1036/A:
You are given a set of $2n+1$ integer points on a Cartesian plane. Points are numbered from $0$ to $2n$ inclusive. Let $P_i$ be the $i$-th point. The $x$-coordinate of the point $P_i$ equals $i$. The $y$-coordinate of the point $P_i$ equals zero (initially). Thus, initially $P_i=(i,0)$.

The given points are vertices of a plot of a piecewise function. The $j$-th piece of the function is the segment $P_{j}P_{j + 1}$.

In one move you can increase the $y$-coordinate of any point with odd $x$-coordinate (i.e. such points are $P_1, P_3, \dots, P_{2n-1}$) by $1$. Note that the corresponding segments also change.

For example, the following plot shows a function for $n=3$ (i.e. number of points is $2\cdot3+1=7$) in which we increased the $y$-coordinate of the point $P_1$ three times and $y$-coordinate of the point $P_5$ one time: [Image]

Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).

Let the height of the plot be the maximum $y$-coordinate among all initial points in the plot (i.e. points $P_0, P_1, \dots, P_{2n}$). The height of the plot on the picture above is 3.

Your problem is to say which minimum possible height can have the plot consisting of $2n+1$ vertices and having an area equal to $k$. Note that it is unnecessary to minimize the number of moves.

It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $10^{18}$.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 10^{18}$) — the number of vertices in a plot of a piecewise function and the area we need to obtain.

-----Output-----

Print one integer — the minimum possible height of a plot consisting of $2n+1$ vertices and with an area equals $k$. It is easy to see that any answer which can be obtained by performing moves described above...

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

[n, k]=[int(i) for i in input().split()]
print((k+n-1)//n)


I found an interesting problem on https://codeforces.com/problemset/problem/1036/D:
Vasya has two arrays $A$ and $B$ of lengths $n$ and $m$, respectively.

He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $[1, 10, 100, 1000, 10000]$ Vasya can obtain array $[1, 1110, 10000]$, and from array $[1, 2, 3]$ Vasya can obtain array $[6]$.

Two arrays $A$ and $B$ are considered equal if and only if they have the same length and for each valid $i$ $A_i = B_i$.

Vasya wants to perform some of these operations on array $A$, some on array $B$, in such a way that arrays $A$ and $B$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.

Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $A$ and $B$ equal.

-----Input-----

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

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

The third line contains a single integer $m~(1 \le m \le 3 \cdot 10^5)$ — the length of the second array.

The fourth line contains $m$ integers $b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$ - elements of the array $B$.

-----Output-----

Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $A$ and $B$ in such a way that they became equal.

If there is no way to make array equal, print "-1".

-----Examples-----
Input
5
11 2 3 5 7
4
11 7 3 7

Output
3

Input
2
1 2
1
100

Output
-1

Input
3
1 2 3
3
1 2 3

Output
3

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

'''input
3
1 2 3
3
1 2 3
'''
import sys
from collections import defaultdict as dd
from itertools import  permutations as pp
from itertools import combinations as cc
from collections import Counter as ccd
from random import randint as rd
from bisect import bisect_left as bl
mod=10**9+7

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

for i in range(1,n):
	a[i]+=a[i-1]
for i in range(1,m):
	b[i]+=b[i-1]

if a[-1]!=b[-1]:
	print(-1)
else:
	a=set(a)
	b=set(b)

	ans=len(a.intersection(b))

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


I found an interesting problem on https://codeforces.com/problemset/problem/1036/E:
You are given $n$ segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.

Count the number of distinct points with integer coordinates, which are covered by at least one segment.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 1000$) — the number of segments.

Each of the next $n$ lines contains four integers $Ax_i, Ay_i, Bx_i, By_i$ ($-10^6 \le Ax_i, Ay_i, Bx_i, By_i \le 10^6$) — the coordinates of the endpoints $A$, $B$ ($A \ne B$) of the $i$-th segment.

It is guaranteed that no two segments lie on the same line.

-----Output-----

Print a single integer — the number of distinct points with integer coordinates, which are covered by at least one segment.

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

Output
42

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

Output
7

-----Note-----

The image for the first example: [Image]

Several key points are marked blue, the answer contains some non-marked points as well.

The image for the second example: [Image]

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

'''

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

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

def cross(x1, y1, x2, y2):
    return x1 * y2 - x2 * y1

def online(line, x, y):
    a, b, c, d = line
    if min(a, c) <= x <= max(a, c) and min(b, d) <= y <= max(b, d):
        return True
    else:
        return False

def CF1036E():
    N = int(input())
    lines = []
    count = 0

    # Find the lines covered by each line segment
    for _ in range(N):
        x1, y1, x2, y2 = map(int, input().split())
        count += gcd(abs(x1 - x2), abs(y1 - y2)) + 1
        lines.append((x1, y1, x2, y2))

    # Deal with the intersecting points
    for i in range(N):
        d = set()
        for j in range(i+1, N):
            px, py, qx, qy = lines[i]
            rx, ry, sx, sy = lines[j]

            line1p = (px - qx, rx - sx)
            line2p = (py - qy, ry - sy)

            # Cross of two lines
            area = cross(line1p[0], line1p[1], line2p[0], line2p[1])

            # Parallel line has no intersection
            if area == 0: continue

            lineA = cross(px, py, qx, qy)
            lineB = cross(rx, ry, sx, sy)
            x = cross(lineA, lineB, line1p[0], line1p[1]) / area
            y = cross(lineA, lineB, line2p[0], line2p[1]) / area

            # Verify the points are good
            if not (x % 1 == 0 and y % 1 == 0): continue
            if not (online(lines[i], x, y) and online(lines[j], x, y)): continue

            d.add((x, y))

        count -= len(d)

    return count

def __starting_point():
    res = CF1036E()
    print(res)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1036/F:
Consider some positive integer $x$. Its prime factorization will be of form $x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot \dots$

Let's call $x$ elegant if the greatest common divisor of the sequence $k_1, k_2, \dots$ is equal to $1$. For example, numbers $5 = 5^1$, $12 = 2^2 \cdot 3$, $72 = 2^3 \cdot 3^2$ are elegant and numbers $8 = 2^3$ ($GCD = 3$), $2500 = 2^2 \cdot 5^4$ ($GCD = 2$) are not.

Count the number of elegant integers from $2$ to $n$.

Each testcase contains several values of $n$, for each of them you are required to solve the problem separately.

-----Input-----

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

Each of the next $T$ lines contains a single integer $n_i$ ($2 \le n_i \le 10^{18}$).

-----Output-----

Print $T$ lines — the $i$-th line should contain the number of elegant numbers from $2$ to $n_i$.

-----Example-----
Input
4
4
2
72
10

Output
2
1
61
6

-----Note-----

Here is the list of non-elegant numbers up to $10$:

  $4 = 2^2, GCD = 2$;  $8 = 2^3, GCD = 3$;  $9 = 3^2, GCD = 2$.

The rest have $GCD = 1$.

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

from math import sqrt, log2
from sys import stdin
from bisect import bisect
import time

def all_primes(n):
    res = []
    for i in range(1, n+1):
        prime = True
        for j in range(2, min(int(sqrt(i))+2, i)):
            if i % j == 0:
                prime = False
                break
        if prime: res.append(i)
    return res

def count_pow_nums(n, p):  #don't count 1
    top = int(pow(n, 1.0/p))
    if pow(top+2, p) <= n:
        return top+1
    elif pow(top+1, p) <= n:
        return top
    elif pow(top, p) <= n:
        return top-1
    else:
        return top-2
primes = all_primes(64)
num_set=set()
max_n = 1000000000000000000
for pi in range(3, len(primes)):
    p = primes[pi]
    cnt = count_pow_nums(max_n, p)
    for n in range(2, cnt+5):
        sq2 = round(sqrt(n))
        sq3 = round(pow(n, 1/3))
        if sq2**2 != n and sq3**3 != n:
            num = pow(n, p)
            if num <= max_n:
                num_set.add(num)
nums = sorted(num_set)
t = int(stdin.readline())
for i in range(t):
    n = int(stdin.readline())
    ans = n-1-count_pow_nums(n, 2)-count_pow_nums(n, 3)+count_pow_nums(n, 6)
    ans -= bisect(nums, n)
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1037/A:
You have $n$ coins, each of the same value of $1$.

Distribute them into packets such that any amount $x$ ($1 \leq x \leq n$) can be formed using some (possibly one or all) number of these packets.

Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single $x$, however it may be reused for the formation of other $x$'s.

Find the minimum number of packets in such a distribution.

-----Input-----

The only line contains a single integer $n$ ($1 \leq n \leq 10^9$) — the number of coins you have.

-----Output-----

Output a single integer — the minimum possible number of packets, satisfying the condition above.

-----Examples-----
Input
6

Output
3
Input
2

Output
2

-----Note-----

In the first example, three packets with $1$, $2$ and $3$ coins can be made to get any amount $x$ ($1\leq x\leq 6$).  To get $1$ use the packet with $1$ coin.  To get $2$ use the packet with $2$ coins.  To get $3$ use the packet with $3$ coins.  To get $4$ use packets with $1$ and $3$ coins.  To get $5$ use packets with $2$ and $3$ coins  To get $6$ use all packets.

In the second example, two packets with $1$ and $1$ coins can be made to get any amount $x$ ($1\leq x\leq 2$).

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

import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline

n=int(input())

ans=1
while 2**ans-1<n:
    ans+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1037/D:
The BFS algorithm is defined as follows.  Consider an undirected graph with vertices numbered from $1$ to $n$. Initialize $q$ as a new queue containing only vertex $1$, mark the vertex $1$ as used.  Extract a vertex $v$ from the head of the queue $q$.  Print the index of vertex $v$.  Iterate in arbitrary order through all such vertices $u$ that $u$ is a neighbor of $v$ and is not marked yet as used. Mark the vertex $u$ as used and insert it into the tail of the queue $q$.  If the queue is not empty, continue from step 2.  Otherwise finish.

Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.

In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex $1$. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) which denotes the number of nodes in the tree.

The following $n - 1$ lines describe the edges of the tree. Each of them contains two integers $x$ and $y$ ($1 \le x, y \le n$) — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.

The last line contains $n$ distinct integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$) — the sequence to check.

-----Output-----

Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.

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

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

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

Output
No

-----Note-----

Both sample tests have the same tree in them.

In this tree, there are two valid BFS orderings:   $1, 2, 3, 4$,  $1, 3, 2, 4$.

The ordering $1, 2, 4, 3$ doesn't correspond to any valid BFS order.

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

n = int(input())

d = {}

for i in range(n-1):
	a,b = map(int,input().split())

	try:
		d[a].append(b);
	except:
		d[a] = [b]
	try:
		d[b].append(a);
	except:
		d[b] = [a]

array = list(map(int,input().split()))
flag=0;

if array[0]==1:

	i = 1;
	j = 0;

	while ( j < n and i < n ):
		if ( array[j] in d[array[i]] ):
			i+=1;
		else:
			j+=1;
	if j==n and i!=n:
		flag=1;
else:
	flag=1;

if flag==1:
	print("No")
else:
	print("Yes")


I found an interesting problem on https://codeforces.com/problemset/problem/1038/A:
You are given a string $s$ of length $n$, which consists only of the first $k$ letters of the Latin alphabet. All letters in string $s$ are uppercase.

A subsequence of string $s$ is a string that can be derived from $s$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.

A subsequence of $s$ called good if the number of occurences of each of the first $k$ letters of the alphabet is the same.

Find the length of the longest good subsequence of $s$.

-----Input-----

The first line of the input contains integers $n$ ($1\le n \le 10^5$) and $k$ ($1 \le k \le 26$).

The second line of the input contains the string $s$ of length $n$. String $s$ only contains uppercase letters from 'A' to the $k$-th letter of Latin alphabet.

-----Output-----

Print the only integer — the length of the longest good subsequence of string $s$.

-----Examples-----
Input
9 3
ACAABCCAB

Output
6
Input
9 4
ABCABCABC

Output
0

-----Note-----

In the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.

In the second example, none of the subsequences can have 'D', hence the answer is $0$.

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

#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

import sys
import bisect
from collections import Counter

read_int = lambda : int(sys.stdin.readline())
read_ints = lambda : list(map(int,sys.stdin.readline().split()))
read_int_list = lambda : list(read_ints())
read = lambda : sys.stdin.readline().strip()
read_list = lambda : sys.stdin.readline().split()

def main():
    n,k = read_ints()
    s = read()
    d = Counter(s)
    res = k*min(d.values()) if len(d) == k else 0
    print(res)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/1038/B:
Find out if it is possible to partition the first $n$ positive integers into two non-empty disjoint sets $S_1$ and $S_2$ such that:$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$

Here $\mathrm{sum}(S)$ denotes the sum of all elements present in set $S$ and $\mathrm{gcd}$ means thegreatest common divisor.

Every integer number from $1$ to $n$ should be present in exactly one of $S_1$ or $S_2$.

-----Input-----

The only line of the input contains a single integer $n$ ($1 \le n \le 45\,000$)

-----Output-----

If such partition doesn't exist, print "No" (quotes for clarity).

Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $S_1$ and $S_2$ respectively.

Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty.

If there are multiple possible partitions — print any of them.

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

Output
No
Input
3

Output
Yes
1 2
2 1 3

-----Note-----

In the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".

In the second example, the sums of the sets are $2$ and $4$ respectively. The $\mathrm{gcd}(2, 4) = 2 > 1$, hence that is one of the possible answers.

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

n = int(input())
if n <= 2:
	print("No")
else:
	print("Yes")
	print(1, (n + 1) // 2)
	ans = []
	for i in range(1, n + 1):
		if i != (n + 1) // 2:
			ans.append(i)
	print(n - 1, *ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1038/C:
Two players A and B have a list of $n$ integers each. They both want to maximize the subtraction between their score and their opponent's score.

In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).

Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $\{1, 2, 2, 3\}$ in a list and you decided to choose $2$ for the next turn, only a single instance of $2$ will be deleted (and added to the score, if necessary).

The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.

Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

-----Input-----

The first line of input contains an integer $n$ ($1 \le n \le 100\,000$) — the sizes of the list.

The second line contains $n$ integers $a_i$ ($1 \le a_i \le 10^6$), describing the list of the player A, who starts the game.

The third line contains $n$ integers $b_i$ ($1 \le b_i \le 10^6$), describing the list of the player B.

-----Output-----

Output the difference between A's score and B's score ($A-B$) if both of them are playing optimally.

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

Output
0
Input
3
100 100 100
100 100 100

Output
0
Input
2
2 1
5 6

Output
-3

-----Note-----

In the first example, the game could have gone as follows:   A removes $5$ from B's list.  B removes $4$ from A's list.  A takes his $1$.  B takes his $1$.

Hence, A's score is $1$, B's score...

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

def gambling():
    n = int(input())
    aa = list(map(int, input().split()))
    bb = list(map(int, input().split()))
    aa.sort()
    bb.sort()

    sa, sb = 0, 0
    while aa or bb:
        # turn a
        if len(aa) == 0:
            bb.pop()
        elif len(bb) == 0:
            sa += aa.pop()
        elif aa[-1] >= bb[-1]:
            sa += aa.pop()
        else:
            bb.pop()

        # turn b
        if len(bb) == 0:
            aa.pop()
        elif len(aa) == 0:
            sb += bb.pop()
        elif bb[-1] >= aa[-1]:
            sb += bb.pop()
        else:
            aa.pop()

    print(sa-sb)

def __starting_point():
    gambling()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1038/D:
There are $n$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.

Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).

When a slime with a value $x$ eats a slime with a value $y$, the eaten slime disappears, and the value of the remaining slime changes to $x - y$.

The slimes will eat each other until there is only one slime left.

Find the maximum possible value of the last slime.

-----Input-----

The first line of the input contains an integer $n$ ($1 \le n \le 500\,000$) denoting the number of slimes.

The next line contains $n$ integers $a_i$ ($-10^9 \le a_i \le 10^9$), where $a_i$ is the value of $i$-th slime.

-----Output-----

Print an only integer — the maximum possible value of the last slime.

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

Output
4
Input
5
0 -1 -1 -1 -1

Output
4

-----Note-----

In the first example, a possible way of getting the last slime with value $4$ is:

  Second slime eats the third slime, the row now contains slimes $2, -1, 1$

 Second slime eats the third slime, the row now contains slimes $2, -2$

 First slime eats the second slime, the row now contains $4$

In the second example, the first slime can keep eating slimes to its right to end up with a value of $4$.

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

import math
n=int(input())
arr=list(map(int,input().split()))
cp=0
cn=0
for i in range(len(arr)):
	if arr[i]>=0:
		cp+=1
	else:
		cn+=1
b=[]
for i in range(len(arr)):
	b.append(abs(arr[i]))
m=min(b)
if n==1:
	print(arr[0])
else:
	if cp>0 and  cn>0:
		print(sum(b))
	else:
		nrt=2*(min(b))
		print(sum(b)-nrt)


I found an interesting problem on https://codeforces.com/problemset/problem/1038/E:
You are given $n$ blocks, each of them is of the form [color$_1$|value|color$_2$], where the block can also be flipped to get [color$_2$|value|color$_1$].

A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.

The value of the sequence is defined as the sum of the values of the blocks in this sequence.

Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.

-----Input-----

The first line of input contains a single integer $n$ ($1 \le n \le 100$) — the number of given blocks.

Each of the following $n$ lines describes corresponding block and consists of $\mathrm{color}_{1,i}$, $\mathrm{value}_i$ and $\mathrm{color}_{2,i}$ ($1 \le \mathrm{color}_{1,i}, \mathrm{color}_{2,i} \le 4$, $1 \le \mathrm{value}_i \le 100\,000$).

-----Output-----

Print exactly one integer — the maximum total value of the subset of blocks, which makes a valid sequence.

-----Examples-----
Input
6
2 1 4
1 2 4
3 4 4
2 8 3
3 16 3
1 32 2

Output
63
Input
7
1 100000 1
1 100000 2
1 100000 2
4 50000 3
3 50000 4
4 50000 4
3 50000 3

Output
300000
Input
4
1 1000 1
2 500 2
3 250 3
4 125 4

Output
1000

-----Note-----

In the first example, it is possible to form a valid sequence from all blocks.

One of the valid sequences is the following:

[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]

The first block from the input ([2|1|4] $\to$ [4|1|2]) and second ([1|2|4] $\to$ [4|2|1]) are flipped.

In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):

[2|100000|1] [1|100000|1] [1|100000|2]

In the third example,...

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

from random import randint

values = [[] for _ in range(10)]
types = [[0, 1, 2, 3], [1, 4, 5, 6], [2, 5, 7, 8], [3, 6, 8, 9]]
b = [1]*10
B = 128
for i in range(9):
    b[i+1] = b[i]*B

for i in range(4):
    values[types[i][i]].append(0)

n = int(input())
for _ in range(n):
    i, v, j = map(int,input().split())
    t = types[i-1][j-1]
    if i == j:
        values[t][0] += v
    else:
        values[t].append(v)

for i in range(4):
    for j in range(i+1,4):
        t = types[i][j]
        values[t].sort()
        while len(values[t])>3:
            v=values[t].pop()+ values[t].pop()
            values[t][-1]+= v
        values[t].sort(reverse = True)

cur=[{},{},{},{}]
m = 0
for i in range(4):
    for j in range(i,4):
        t = types[i][j]
        if values[t]:
            cur[i][b[t]] = values[t][0]
            m = max(m,values[t][0])

def cnt(k,t):
    return k//b[t]%B

for _ in range(n):
    next = [{},{},{},{}]
    for i in range(4):
        for j in range(4):
            t = types[i][j]
            for k, v in cur[i].items():
                c = cnt(k,t)
                if len(values[t])>c:
                    nk = k+b[t]
                    if nk not in next[j]:
                        next[j][nk] = values[t][c] + v
                        m = max(m, values[t][c] + v)
    cur = next

print (m)