Solve in Python:
Chef and his friend Miron were getting bored and decided to play a game.
Miron thinks of a sequence of  N  integers (A1, A2, …., AN) and gives Chef a matrix B, where Bi,j = |Ai - Aj|. He further tells Chef that A1 = 0. The game is for Chef to guess the sequence that Miron thought of.
But Miron is an adversarial player. Every time Chef tries to guess the sequence, he makes a change to the matrix. He makes such a change Q times. Each time, he replaces an entry in some row and the corresponding column with a new one leaving Chef to guess the sequence after each change.
Chef needs a friend to help him against such an adversarial player. Can you be that friend and help Chef find a suitable sequence A for the initial matrix B and also after each change Miron makes?
Note that if several answers exist, then print the lexicographically smallest answer. Further, the numbers in the sequence can be negative.

-----Input-----

The first line contains two space-separated integers N, Q. Each of the N subsequent lines contains N space-separated integers, denoting the matrix B.

Q queries follow. Each query has two lines. The first line of each query contains an integer p, denoting the number of row and column that is changed. The second line of each query contains N space-separated integers F1, F2, F3, ... FN, denoting the new values to the corresponding cells of the matrix (you should make the following assignments Bi,p = Bp,i = Fi for all valid i).

-----Output-----
Print Q + 1 lines which contain N space-separated integers, Miron's initial array and Miron's array after each query.

-----Constraints-----
- 3 ≤ N ≤  1000
- 1 ≤ Q ≤  1000
- 0 ≤ Bi,j ≤  5000
- 1 ≤ p ≤  n
- 0 ≤ Fi ≤  5000
- it's guaranteed there's always an answer

-----Example-----
Input:
3 2
0 1 2
1 0 1
2 1 0
1
0 4 3
2
4 0 7
Output:
0 -1 -2
0 -4 -3
0 -4 3

-----Explanation-----
Example case 1. Initially, sequence {0, 1, 2} is also suitable, but {0, -1, -2} is lexicografically smaller.

def update_B(B, query):
 p, R = query
 for i in range(len(R)):
  B[p][i] = R[i]
  B[i][p] = R[i]

def get_A(B):
 N = len(B)
 A = [0] * N
 i = 0
 for j in range(N):
  if B[0][j] != 0:
   i = j
   A[i] = -B[0][i]
   break

 for j in range(i + 1, N):
  if abs(A[i] - B[0][j]) == B[i][j]:
   A[j] = B[0][j]
  else:
   A[j] = -B[0][j]

 return A

def print_list(A):
 print(' '.join([str(a) for a in get_A(B)]))

N, Q = [int(x) for x in input().rstrip().split()]
B = []
for i in range(N):
 B += [[int(x) for x in input().rstrip().split()]]
queries = []
for i in range(Q):
 p = int(input()) - 1
 arr = input().rstrip().split()
 queries += [(p, [int(x) for x in arr])]

print_list(get_A(B))
for q in queries:
 update_B(B, q)
 print_list(' '.join([str(a) for a in get_A(B)]))


Solve in Python:
Chef and his friends are playing the game AMONG US. They all have chosen their names as numbers. There are N people in Chef’s group including him, and each swears that he is not the imposter. However, it turns out there were N+1 people in the game. Now all that Chef needs to know is the name of the imposter, which is a number. Also remember that numbers can be duplicate. Can you help out Chef in finding the imposter?
Input :
First line contains the value of N. Second line contains the N numbers that Chef’s friends used as their names. Third line contains the N+1 numbers that people in the game have used as their names.
Output :
Print the extra number in new line.
Constraints :
1 ≤ Numbers used as names ≤ 1,000
1 ≤ N ≤ 1,000,000
Sample Input :
3
4 2 5
4 2 3 5
Sample Output :
3

n=int(input())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
p=1
l1=sorted(l1)
l2=sorted(l2)
for i in range(len(l1)):
    if l1[i]==l2[i]:
        continue
    else:
        print(l2[i])
        p=0
        break
if p:
    print(l2[-1])


Solve in Python:
Chef and his girlfriend are going to have a promenade. They are walking along the straight road which consists of segments placed one by one. Before walking Chef and his girlfriend stay at the beginning of the first segment, they want to achieve the end of the last segment.
There are few problems:

-  At the beginning Chef should choose constant integer - the velocity of mooving. It can't be changed inside one segment.
-  The velocity should be decreased by at least 1 after achieving the end of some segment.
-  There is exactly one shop on each segment. Each shop has an attractiveness. If it's attractiveness is W and Chef and his girlfriend move with velocity V then if V < W girlfriend will run away into the shop and the promenade will become ruined.

Chef doesn't want to lose her girl in such a way, but he is an old one, so you should find the minimal possible velocity at the first segment to satisfy all conditions.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N denoting the number of segments. The second line contains N space-separated integers W1, W2, ..., WN denoting the attractiveness of shops.

-----Output-----
- For each test case, output a single line containing the minimal possible velocity at the beginning.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10^5
- 1 ≤ Wi ≤ 10^6

-----Example-----
Input:

2
5
6 5 4 3 2
5
3 4 3 1 1

Output:

6
5

-----Explanation-----
Example case 1.
If we choose velocity 6, on the first step we have 6 >= 6 everything is OK, then we should decrease the velocity to 5 and on the 2nd segment we'll receive 5 >= 5, again OK, and so on.
Example case 2.
If we choose velocity 4, the promanade will be ruined on the 2nd step (we sould decrease our velocity, so the maximal possible will be 3 which is less than 4).

# cook your dish here
t=int(input())
for _ in range(t):
 n=int(input())
 l = list(map(int,input().split()))

 temp,speed = l[0],l[0]

 for i in range(1,n):

  if temp < l[i]:

   speed += l[i] - temp
   temp = speed-i-1

  else:
   temp -= 1

 print(speed)


Solve in Python:
Chef and his mother are going travelling. Chef's world consists of $N$ cities (numbered $1$ through $N$) connected by $N-1$ bidirectional roads such that each city can be reached from any other city using roads. For each city, we know its age — the number of years elapsed since the foundation of the city; let's denote the age of city $i$ by $a_i$.
First of all, Chef and his mother have to decide what city they should visit first. Suppose that Chef chooses a city $c_c$ and his mother chooses a (not necessarily different) city $c_m$. The difference of their choices is the number of different bits in the binary representations of $a_{c_c}$ and $a_{c_m}$.
Chef will not argue with his mother if the parity of this difference is not equal to the parity of the length of the shortest path between cities $c_c$ and $c_m$ (the number of roads on the shortest path between them). Find the number of ways to choose the cities $c_c$ and $c_m$ such that Chef avoids quarreling with his mother.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- Each of the following $N-1$ lines contains two space-separated integers $A$ and $B$ denoting a road between cities $A$ and $B$.
- The last line contains $N$ space-separated integers $a_1, a_2, \dots, a_N$.

-----Output-----
For each test case, print a single line containing one integer — the number of valid pairs $c_c, c_m$.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^5$
- $1 \le A, B \le N$
- $0 \le a_i \le 10^9$ for each valid $i$

-----Sample Input-----
1
3
1 2
1 3
1 2 3

-----Sample Output-----
2

-----Explanation-----
Example case 1: The two possible choices are $c_c=2, c_m=3$ (their binary representations differ by one bit, the shortest path has length $2$) and $c_c=1, c_m=2$ (there are two different bits in their binary representations and the shortest path has length $1$).

'''input
1
3
1 2
1 3
1 2 3
'''
import sys
sys.setrecursionlimit(1000000)
for _ in range(eval(input())):
 C=[]
 n=eval(input())
 for i in range(n):
  C.append([])
 for i in range(n-1):
  a,b=[int(x)-1 for x in input().split()]
  C[a].append(b)
  C[b].append(a)
 cnt=0
 Co=[bin(int(x)).count("1") for x in input().split()]
 Q=[0]*(n+100)
 cur=0
 done=[0]*n
 done[0]=1
 H=[0]*n
 for i in range(n):
  r=Q[i]
  if H[r]&1 == Co[r]&1:
   cnt+=1
  for i in C[r]:
   if done[i]==0:
    done[i]=1
    Q[cur+1]=i
    cur+=1
    H[i]=H[r]+1
 #dfs(0,-1)
 print(cnt*(n-cnt))


Solve in Python:
Chef belongs to a very rich family which owns many gold mines. Today, he brought N gold coins and decided to form a triangle using these coins. Isn't it strange?
Chef has a unusual way of forming a triangle using gold coins, which is described as follows:
- He puts 1 coin in the 1st row.
- then puts 2 coins in the 2nd row.
- then puts 3 coins in the 3rd row.
-  and so on as shown in the given figure.
Chef is interested in forming a triangle with maximum possible height using at most N coins. Can you tell him the maximum possible height of the triangle?

-----Input-----
The first line of input contains a single integer T denoting the number of test cases.
The first and the only line of each test case contains an integer N denoting the number of gold coins Chef has.

-----Output-----
For each test case, output a single line containing an integer corresponding to the maximum possible height of the triangle that Chef can get.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 109

-----Subtasks-----
- Subtask 1 (48 points) : 1 ≤ N ≤ 105
- Subtask 2 (52 points) : 1 ≤ N ≤ 109

-----Example-----
Input3
3
5
7

Output2
2
3

-----Explanation-----
- Test 1: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins.
- Test 2: Chef can't form a triangle with height > 2 as it requires atleast 6 gold coins.
- Test 3: Chef can't form a triangle with height > 3 as it requires atleast 10 gold coins.

t = int(input())
for x in range(t):
 n = int(input())
 n *= 2
 a = int(n ** 0.5)
 if a*(a+1) <= n:
  print(a)
 else:
  print(a-1)


Solve in Python:
Chef bought a huge (effectively infinite) planar island and built $N$ restaurants (numbered $1$ through $N$) on it. For each valid $i$, the Cartesian coordinates of restaurant $i$ are $(X_i, Y_i)$.
Now, Chef wants to build $N-1$ straight narrow roads (line segments) on the island. The roads may have arbitrary lengths; restaurants do not have to lie on the roads. The slope of each road must be $1$ or $-1$, i.e. for any two points $(x_1, y_1)$ and $(x_2, y_2)$ on the same road, $|x_1-x_2| = |y_1-y_2|$ must hold.
Let's denote the minimum distance Chef has to walk from restaurant $i$ to reach a road by $D_i$. Then, let's denote $a = \mathrm{max}\,(D_1, D_2, \ldots, D_N)$; Chef wants this distance to be minimum possible.
Chef is a busy person, so he decided to give you the job of building the roads. You should find a way to build them that minimises $a$ and compute $a \cdot \sqrt{2}$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_i$ and $Y_i$.

-----Output-----
For each test case, print a single line containing one real number — the minimum distance $a$ multiplied by $\sqrt{2}$. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$.

-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 10^4$
- $|X_i|, |Y_i| \le 10^9$ for each valid $i$

-----Subtasks-----
Subtask #1 (10 points):
- $1 \le T \le 10$
- $2 \le N \le 5$
- $|X_i|, |Y_i| \le 10$ for each valid $i$
- $a \cdot \sqrt{2}$ is an integer
Subtask #2 (90 points): original constraints

-----Example Input-----
2
3
0 0
0 1
0 -1
3
0 1
1 0
-1 0

-----Example Output-----
0.5
0

-----Explanation-----
Example case 1: We should build roads described by equations $y-x+0.5 = 0$ and $y-x-0.5 = 0$.
Example case 2: We should build roads described by...

t=int(input())
while (t>0):
 t-=1
 n=int(input())
 d=[]
 dl=[]
 for i in range(n):
  x,y=map(int,input().split())
  d.append(y-x)
  dl.append(y+x)
 #print("d = ",d)
 #print("dl = ",dl)
 d=sorted(d)
 dl=sorted(dl)
 #print("d now = ",d)
 #print("dl now = ",dl)
 ans=abs(d[0]-d[1])
 k=0
 while (k<n-1):
  ans=min(ans,abs(d[k]-d[k+1]))
  ans=min(ans,abs(dl[k]-dl[k+1]))
  k+=1
 if (ans%2==0):
  print(int(ans/2))
 else:
  print(ans/2)


Solve in Python:
Chef bought an electronic board and pen. He wants to use them to record his clients' signatures.
The board is a grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$) of pixels. Initially, all pixels are white. A client uses the electronic pen to sign on the board; whenever the pen touches a pixel, this pixel becomes black. Note that a signature may be non-continuous (a client may lift the pen while signing).
Chef stores a typical signature of his current client as a matrix of characters $A_{i, j}$, where for each valid $i$ and $j$, $A_{i, j}$ is either '1' (if the cell in the $i$-th row and $j$-th column is black) or '0' (if this cell is white). The client just signed on the board; this signature is stored in the same form as a matrix $B_{i, j}$. Chef wants to know how close this signature is to this client's typical signature.
Two signatures are considered the same if it is possible to choose (possibly negative) integers $dr$ and $dc$ such that for each $1 \le i \le N$ and $1 \le j \le M$, $A_{i, j} = B_{i + dr, j + dc}$. Here, if $B_{i + dr, j + dc}$ does not correspond to a valid cell, it is considered to be '0'.
To compare the signatures, the colours of zero or more cells must be flipped in such a way that the signatures become the same (each flipped cell may be in any matrix). The error in the client's current signature is the minimum number of cells whose colours must be flipped. Find the error in the signature.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $M$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains a string with length $M$ describing the $i$-th row of the matrix $A$.
- $N$ more lines follow. For each valid $i$, the $i$-th of these lines contains a string with length $M$ describing the $i$-th row of the matrix $B$.

-----Output-----
For each test...

import numpy as np
for _ in range(int(input())):
 ans = np.float('inf')
 n, m = (int(x) for x in input().split())
 sig = np.zeros((n,m))
 img = np.zeros((3*n,3*m))
 for row in range(n):
  sig[row,:] = np.array([int(x) for x in input()])
 for row in range(n):
  img[row+n,m:2*m] = np.array([int(x) for x in input()])
 for i in range(2*n):
  for j in range(2*m):
   ans = min(ans, np.abs(np.sum(img[i:n+i, j:m+j] != sig)))
 print(ans)


Solve in Python:
Chef changed the password of his laptop a few days ago, but he can't remember it today. Luckily, he wrote the encrypted password on a piece of paper, along with the rules for decryption.
The encrypted password is a string S consists of ASCII printable characters except space (ASCII 33 - 126, in decimal notation, the same below). Read here for more details: ASCII printable characters.
Each rule contains a pair of characters ci, pi, denoting that every character ci appears in the encrypted password should be replaced with pi. Notice that it is not allowed to do multiple replacements on a single position, see example case 1 for clarification.
After all the character replacements, the string is guaranteed to be a positive decimal number. The shortest notation of this number is the real password. To get the shortest notation, we should delete all the unnecessary leading and trailing zeros. If the number contains only non-zero fractional part, the integral part should be omitted (the shortest notation of "0.5" is ".5"). If the number contains zero fractional part, the decimal point should be omitted as well (the shortest notation of "5.00" is "5").
Please help Chef to find the real password.

-----Input-----
The first line of the input contains an interger T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains a single interger N, denoting the number of rules.
Each of the next N lines contains two space-separated characters ci and pi,
denoting a rule.
The next line contains a string S, denoting the encrypted password.

-----Output-----
For each test case, output a single line containing the real password.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 0 ≤ N ≤ 94
- All characters in S and ci may be any ASCII printable character except space. (ASCII 33 - 126)
- All ci in a single test case are distinct.
- pi is a digit ("0" - "9") or a decimal point "." (ASCII 46).
- The total length of S in a single input file will not exceed...

for _ in range(int(input())):
    n=int(input())
    rule=[]
    ci=""
    pi=""
    for _ in range(n):
        c,p=input().split()
        ci+=c
        pi+=p
    trans=str.maketrans(ci,pi)
    s=input()
    s=s.translate(trans)
    s="".join(s)
    dot = s.find(".")
    if dot!=-1:
        s=s.strip("0").rstrip(".")
    else:
        s=s.lstrip("0")

    if s=="":
        print(0)
    else:
        print(s)


Solve in Python:
Chef develops his own computer program for playing chess. He is at the very beginning. At first he needs to write the module that will receive moves written by the players and analyze it. The module will receive a string and it should report at first whether this string represents the correct pair of cells on the chess board (we call such strings correct) and then report whether it represents the correct move depending on the situation on the chess board. Chef always has troubles with analyzing knight moves. So at first he needs a test program that can say whether a given string is correct and then whether it represents a correct knight move (irregardless of the situation on the chess board). The cell on the chessboard is represented as a string of two characters: first character is a lowercase Latin letter from a to h and the second character is a digit from 1 to 8. The string represents the correct pair of cells on the chess board if it composed of 5 characters where first two characters represent the cell where chess figure was, 3rd character is the dash "-" and the last two characters represent the destination cell.

-----Input-----
The first line contains a single integer T <= 50000, the number of test cases. T test cases follow. The only line of each test case contains a non-empty string composed the characters with ASCII-codes from 32 to 126. The length of the string is not greater than 10.

-----Output-----
For each test case, output a single line containing the word "Error" if the corresponding string does not represent the correct pair of cells on the chess board. Otherwise output "Yes" if this pair of cells represents the correct knight move and "No" otherwise.

-----Example-----
Input:
4
a1-b3
d2-h8
a3 c4
ErrorError

Output:
Yes
No
Error
Error

a=ord('a')
h=ord('h')

N=int(input())
for x in range(N):
 lines=input()
 if (len(lines)==5 and lines[2]=='-'):
  try:
   I1=ord(lines[0])
   I2=int(lines[1])
   F1=ord(lines[3])
   F2=int(lines[4])
   #print I1,I2,F1,F2
   if (a<=F1<=h and a<=I1<=h and 1<=F2<=8 and 1<=I2<=8):
    D2=abs(I2-F2)
    D1=abs(F1-I1)
    #   print D2,D1
    if((D1==1 and D2==2) or (D1==2 and D2==1)):
     print("Yes")
    else:
     print("No")
   else:
    print("Error")
  except ValueError:
   print("Error")
 else:
  print("Error")


Solve in Python:
Chef found a strange string yesterday - a string of signs s, where each sign is either a '<', '=' or a '>'. Let N be the length of this string. Chef wants to insert N + 1 positive integers into this sequence and make it valid. A valid sequence is a sequence where every sign is preceded and followed by an integer, and the signs are correct. That is, if a sign '<' is preceded by the integer a and followed by an integer b, then a should be less than b. Likewise for the other two signs as well.
Chef can take some positive integers in the range [1, P] and use a number in the range as many times as he wants.
Help Chef find the minimum possible P with which he can create a valid sequence.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains the string of signs s, where each sign is either '<', '=' or a '>'.

-----Output-----
For each test case, output a single line containing an integer corresponding to the minimum possible P.

-----Constraints-----
- 1 ≤ T, |s| ≤ 105
- 1 ≤ Sum of |s| over all test cases in a single test file ≤ 106

-----Subtasks-----
Subtask #1 (30 points)
- 1 ≤ T, |s| ≤ 103
- 1 ≤ Sum of |s| over all test cases in a single test file ≤ 104

Subtask #2 (70 points)
- Original constraints

-----Example-----
Input:
4
<<<
<><
<=>
<=<

Output:
4
2
2
3

-----Explanation-----
Here are some possible valid sequences which can be formed with the minimum P for each of the test cases:
1 < 2 < 3 < 4
1 < 2 > 1 < 2
1 < 2 = 2 > 1
1 < 2 = 2 < 3

# cook your dish here
import math
t=0
try:
 t = int(input())
except EOFError as e : pass
for i in range(t):
 myStr = input().replace('=', '')
 if len(myStr) == 0 :
  print(1)
  continue
 ans = 0
 count = 1
 for k in range(len(myStr)-1):
  if myStr[k] == myStr[k+1]:
   count +=1
  else:
   ans = max(count, ans)
   count = 1
  ans = max(count, ans)
 print(ans+1)


Solve in Python:
Chef gives an integer $K$ in the input.  If the given number is beautiful binary number, print it, Else find its previous beautiful binary number. A beautiful binary number is a number whose binary representation does not contain any consecutive 1s.
Note: 1 is also a beautiful binary number.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.

-----Output:-----
For each test case, print a beautiful number.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq K \leq 10^5$

-----Sample Input:-----
3
3
6
8

-----Sample Output:-----
2
5
8

-----EXPLANATION:-----
For 1) 3 is not a beautiful binary number because the binary representation of 3 is "11" which has consecutive 1s.  hence 2 which is less than 3 is printed.
For 3) 8 is already a beautiful binary number with no consecutive 1s in its binary representation. so, print 8 as it is.

pref = []

for i in range(10 ** 5 + 10):
    b = bin(i)[2:]
    if not any(b[j] == b[j+1] == '1' for j in range(len(b) - 1)):
        pref.append(i)
    else:
        pref.append(pref[-1])

for i in range(int(input())):
    print(pref[int(input())])


Solve in Python:
Chef got in the trouble! He is the king of Chefland and Chessland. There is one queen in Chefland and one queen in Chessland and they both want a relationship with him. Chef is standing before a difficult choice…
Chessland may be considered a chessboard with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). Let's denote a unit square in row $r$ and column $c$ by $(r, c)$. Chef lives at square $(X, Y)$ of this chessboard.
Currently, both queens are living in Chessland too. Each queen, when alone on the chessboard, can see all squares that lie on the same row, column or diagonal as itself. A queen from $(x_q, y_q)$ cannot see a square $(r, c)$ if the square $(X, Y)$ is strictly between them. Of course, if the queens can see each other, the kingdom will soon be in chaos!
Help Chef calculate the number of possible configurations of the queens such that the kingdom will not be in chaos. A configuration is an unordered pair of distinct squares $(x_{q1}, y_{q1})$ and $(x_{q2}, y_{q2})$ such that neither of them is the square $(X, Y)$. Two configurations are different if the position of queen $1$ is different or the position of queen $2$ is different.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains four space-separated integers $N$, $M$, $X$ and $Y$.

-----Output-----
For each test case, print a single line containing one integer — the number of configurations such that the kingdom will not be in chaos.

-----Constraints-----
- $1 \le T \le 1000$
- $1 \le X \le N \le 10^2$
- $1 \le Y \le M \le 10^2$
- $2 \le N, M$

-----Example Input-----
2
3 3 2 2
4 4 2 3

-----Example Output-----
24
94

-----Explanation-----
Example case 1: Half of these configurations are:
- $(1, 1), (3, 3)$
- $(1, 1), (2, 3)$
- $(1, 1), (3, 2)$
- $(1, 2), (3, 3)$
- $(1, 2), (3, 2)$
- $(1, 2), (3, 1)$
- $(1, 3), (3, 1)$
- $(1, 3), (3, 2)$
- $(1, 3), (2, 1)$
-...

def C(n):
 return n*(n-1)//2

def sol():
 equal, mini = False, min(N,M)
 total_ways = 2*C(N * M)
 if N==M:
  equal = True
 ways = 0
 if not equal:
  ways = (N*C(M)+M*C(N))
  diag = 0
  for i in range(2, mini+1):
   diag += 2*C(i)
  for i in range(mini+1,max(N,M)):
   diag += C(mini)
  diag *= 2
  ways += diag
  ways *= 2
 else:
  ways = (N*C(M)+M*C(N))
  diag = 0
  for i in range(2, mini):
   diag += 2*C(i)
  diag += C(mini)
  diag *= 2
  ways += diag
  ways *=2
 safe = total_ways - ways
 l, r, t, d = Y-1, M-Y, X-1, N-X
 safe_add, to_remove = 0, 0

 for i in range(1,N+1):
  for j in range(1, M+1):
   if i==X or j==Y or abs(i-X)==abs(j-Y):
    continue
   else:
    to_remove += 1

 if l>0 and r>0 and t>0 and d>0:
  dtl, dtr, dbl, dbr = min(l,t), min(r,t), min(l,d), min(r,d)
  safe_add += dtl*dbr*2 + dtr*dbl*2
  safe_add += t*d*2
  safe_add += l*r*2
 elif l>0 and r>0:
  safe_add += l*r*2
 elif t>0 and d>0:
  safe_add += t*d*2

 safe += safe_add - to_remove*2

 return safe

T = int(input())
for _ in range(T):
 N, M, X, Y = [int(x) for x in input().split()]
 print(sol())


Solve in Python:
Chef got into a fight with the evil Dr Doof. Dr Doof has decided to destroy all even numbers from the universe using his Evil-Destroy-inator. Chef has $N$ integers with him. To stop Doof, Chef has to find an odd number which is an integer multiple of all $N$ numbers that he has with him. Find if it is possible for Chef to prevent Dr Doof from destroying the even numbers.
Formally, given $N$ positive integers, find if there exists an odd number which is an integer multiple of all the given $N$ numbers. If yes, print "YES", otherwise "NO". You can print any letter in any case.

-----Input-----
- First line contains $T$, number of testcases. Each testcase consists of $2$ lines.
- The first line of each test case consists of a positive integer $N$, denoting the number of positive integers Chef has.
- The second line of each test case contains $N$ space separated integers $A_i$ each denoting an integer that Chef has with him.

-----Output-----
For every test case, if there exists such an odd number, print "YES" on a separate line, otherwise "NO". The judge is case insensitive. That means, your code can print any letter in any case ( "Yes", "yes" or "YES" are all accepted).

-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^3$
- $1 \leq A_i \leq 10^3$

-----Sample Input-----
2
5
1 2 5 4 3
1
7

-----Sample Output-----
NO
YES

-----Explanation-----
For test $1$: There exists no odd number.
For test $2$: The possible odd numbers can be $7$, $21$, $49$, $315$, …

# cook your dish here
for _ in range(0,int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 cnt=0
 for i in range(0,n):
  if(l[i]%2==0):
   cnt+=1
   print("NO")
   break
 if(cnt==0):
  print("YES")


Solve in Python:
Chef had a sequence of positive integers with length $N + K$. He managed to calculate the arithmetic average of all elements of this sequence (let's denote it by $V$), but then, his little brother deleted $K$ elements from it. All deleted elements had the same value.
Chef still knows the remaining $N$ elements — a sequence $A_1, A_2, \ldots, A_N$. Help him with restoring the original sequence by finding the value of the deleted elements or deciding that there is some mistake and the described scenario is impossible.
Note that the if it is possible for the deleted elements to have the same value, then it can be proven that it is unique. Also note that this value must be a positive integer.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains three space-separated integers $N$, $K$ and $V$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer — the value of the deleted elements, or $-1$ if there is a mistake.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N, K \le 100$
- $1 \le V \le 10^5$
- $1 \le A_i \le 10^5$ for each valid $i$

-----Subtasks-----
Subtask #1 (100 points): original constraints

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

-----Example Output-----
4
-1
-1

# cook your dish here
for _ in range(int(input())):
 n,k,v=map(int,input().split())
 a=[int(i) for i in input().split()]
 s=(n+k)*v - sum(a)
 if sum(a)>=(n+k)*v or s%k!=0:
  print(-1)
 else:
  print(s//k)


Solve in Python:
Chef had an array A with length N, but some of its elements got lost. Now, each element of this array is either unknown (denoted by -1) or a positive integer not exceeding K.
Chef decided to restore the array A by replacing each unknown element by a positive integer not exceeding K.
However, Chef has M restrictions that must hold for the restored array. There are two types of restrictions:

- I L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = 1 should be satisfied.
- D L R, meaning that for each i such that L < i  ≤ R, the condition Ai - Ai-1 = -1 should be satisfied.

Chef would like to know the number of ways to restore the array while satisfying all restrictions, modulo 109+7.

-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains three space-separated integers N, M and K.
- The second line contains N integers A1, A2, ..., AN.
- Each of the following M lines contains one restriction in the form I L R or D L R.

-----Output-----
For each test case, print a single line containing one integer - the number of ways to restore the array modulo 109+7.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N, M ≤ 100,000
- 1 ≤ K ≤ 1,000,000,000
- 1 ≤ L < R ≤ N
- 1 ≤ Ai ≤ K or Ai = -1 for each valid i
- 1 ≤ sum of N over all test cases ≤ 500,000
- 1 ≤ sum of M over all test cases ≤ 500,000

-----Example-----
Input:

3
4 2 10
2 3 5 4
I 1 2
D 3 4
5 2 10
-1 -1 -1 -1 -1
I 1 3
D 3 5
6 2 2
-1 -1 -1 -1 -1 -1
I 1 4
D 4 6

Output:

1
8
0

# cook your dish here
# cook your dish here
MOD = 10 ** 9 + 7

for t in range(int(input())):
    N, M, K = map(int, input().split())
    A = list(map(int, input().split()))
    I, D = [0] * (N + 2), [0] * (N + 2)
    for i in range(M):
        x, L, R = input().split()
        L, R = int(L), int(R)
        if x == 'I':
            I[L] += 1
            I[R] -= 1
        else:
            D[L] += 1
            D[R] -= 1

    impossibru = mx = mn = 0
    ans = 1
    for i in range(N):
        I[i] += I[i - 1]
        D[i] += D[i - 1]
        if I[i] and D[i]:
            impossibru = 1
            break
        if not I[i] and not D[i]:
            ans = ans * (mx - mn + 1) % MOD
            mn, mx = 1, K
        elif I[i]:
            mx = min(mx + 1, K)
            mn += 1
        elif D[i]:
            mn = max(1, mn - 1)
            mx -= 1
        if mn > mx:
            impossibru = 1
            break
        if A[i] != -1:
            if not mn <= A[i] <= mx:
                impossibru = 1
                break
            mn = mx = A[i]
    ans = ans * (mx - mn + 1) % MOD

    print(0 if impossibru else ans)


Solve in Python:
Chef had an interesting dream last night. He dreamed of a new revolutionary chicken recipe. When he woke up today he tried very hard to reconstruct the ingredient list. But, he could only remember certain ingredients. To simplify the problem, the ingredient list can be represented by a string of lowercase characters 'a' - 'z'.
Chef can recall some characters of the ingredient list, all the others, he has forgotten. However, he is quite sure that the ingredient list was a palindrome.
You are given the ingredient list Chef dreamed last night. The forgotten characters are represented by a question mark ('?'). Count the number of ways Chef can replace the forgotten characters with characters 'a' - 'z' in such a way that resulting ingredient list is a palindrome.

-----Input-----
The first line of input contains a single integer T, the number of test cases. T lines follow, each containing a single non-empty string - the ingredient list as recalled by Chef. Whatever letters he couldn't recall are represented by a '?'.

-----Output-----
For each test case, output a single line containing the number of valid ways the ingredient list could be completed. Since the answers can be very large, output each answer modulo 10,000,009.

-----Example-----
Input:
5
?
??
ab?
a?c
aba

Output:
26
26
1
0
1

-----Constraints-----

1 ≤ T ≤ 20

1 ≤ sum of length of all input strings ≤ 1,000,000

Each input string contains only lowercase roman letters ('a' - 'z') or question marks.

# cook your dish here
for t in range(int(input())):
 s=input()
 n=len(s)
 c,k=1,0
 for i in range(((len(s)-1)//2)+1):
  if s[i]=='?' and s[n-i-1]=='?':
   c=(c*26)%10000009
  elif s[i]=='?' or s[n-i-1]=='?':
   pass
  elif s[i]!=s[n-i-1]:
    k=1
    break
 if k==1:
  print(0)
 else:
  print(c)


Solve in Python:
Chef has  $N$ boxes arranged in a line.Each box has some candies in it,say $C[i]$. Chef wants to distribute all the candies between of his friends: $A$ and $B$, in the following way:
$A$ starts eating candies kept in the leftmost box(box at $1$st place) and $B$ starts eating candies kept in the rightmost box(box at $N$th place). $A$ eats  candies $X$ times faster than $B$ i.e. $A$ eats $X$ candies when $B$ eats only $1$. Candies in each box can be eaten by only the person who reaches that box first. If both reach a box at the same time, then the one who has eaten from more number of BOXES till now will eat the candies in that box. If both have eaten from the same number of boxes till now ,then $A$ will eat the candies in that box.
Find the number of boxes finished by both $A$ and $B$.
NOTE:- We assume that it does not take any time to switch from one box to another.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains three lines of input.
The first line of each test case contains $N$, the number of boxes.
- The second line of each test case contains a sequence,$C_1$ ,$C_2$ ,$C_3$ . . . $C_N$ where $C_i$ denotes the number of candies in the i-th box.
- The third line of each test case contains an integer $X$ .

-----Output:-----
For each testcase, print two space separated integers in a new line - the number of boxes eaten by $A$  and  $B$ respectively.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 200000$
- $1 \leq C_i \leq 1000000$
- $1 \leq X \leq 10$
- Sum of $N$ over all test cases does not exceed $300000$

-----Subtasks-----
Subtask 1(24 points):
- $1 \leq T \leq 10$
- $1 \leq N \leq 1000$
- $1 \leq C_i \leq 1000$
- $1 \leq X \leq 10$
Subtask 2(51 points): original constraints

-----Sample Input:-----
1
5
2 8 8 2 9
2

-----Sample Output:-----
4 1

-----EXPLANATION:-----
$A$ will start eating candies in the 1st box(leftmost box having 2 candies) . $B$ will start eating candies in the  5th box(rightmost box having 9...

#https://www.codechef.com/problems/BIT2B
import math
import bisect
t=int(input())
while t!=0:
 t-=1
 n=int(input())
 candies=[int(x) for x in input().split()]
 rate=int(input())
 a_start_time=[0 for x in range(n)]
 b_start_time=[0 for x in range(n)]
 a_start_time[0]=0
 b_start_time[-1]=0
 sum_candies=candies[0]
 for i in range(1,n):
  a_start_time[i]=sum_candies//rate
  sum_candies+=candies[i]

 for i in range(n-2,-1,-1):
  b_start_time[i]=b_start_time[i+1]+candies[i+1]

 a_count=0
 b_count=0
 if n==1:
  print(1, 0)
  continue
 elif n==2:
  print(1, 1)
  continue
 for i in range(n):
  if(a_start_time[i]<b_start_time[i]):
   a_count+=1
  elif(b_start_time[i]==a_start_time[i]):
   if(a_count>=n-a_count-1):
    a_count+=1
 print(a_count,n-a_count)


Solve in Python:
Chef has  $N$ doggo (dogs) , Lets number them $1$ to $N$.

Chef decided to build houses for each, but he soon realizes that keeping so many dogs at one place may be messy. So he decided to divide them into several groups called doggo communities. Let the total no. of groups be $K$ . In a community, paths between pairs of houses can be made so that doggo can play with each other. But there cannot be a path between two houses of different communities for sure. Chef wanted to make maximum no. of paths such that the total path is not greater then $K$.
Let’s visualize this problem in an engineer's way :)
The problem is to design a graph with max edge possible such that the total no. of edges should not be greater than the total no. of connected components.

-----INPUT FORMAT-----
- First line of each test case file contain $T$ , denoting total number of test cases.
- $ith$ test case contain only one line with a single integer $N$ , denoting the number of dogs(vertex)

-----OUTPUT FORMAT-----
- For each test case print a line with a integer , denoting the maximum possible path possible.

-----Constraints-----
- $1 \leq T \leq 10000$
- $1 \leq N \leq 10^9$

-----Sub-Tasks-----
- $20 Points$
- $1 \leq N \leq 10^6$

-----Sample Input-----
1

4

-----Sample Output-----
2

-----Explanation-----
4 houses can be made with  like this:

community #1  : [1 - 2  ]

community #2 :  [3 - 4 ]

or  [1 - 2 - 3]  , [ 4 ]

In both cases the maximum possible path is 2.

from collections import defaultdict
import sys
import math as mt
import random

sys.setrecursionlimit(10**6)
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()

ans = [0]*(10**6+1)
ans[2] = 1
ans[3] = 1
start = 3
for i in range(4,10**6+1):
    ans[i] = min((start*(start-1))//2,i-start+1)
    if ans[i]==ans[i-1]:
        start+=1

for _ in range(int(input())):
    n = int(input())
    print(ans[n])


Solve in Python:
Chef has $K$ chocolates and he wants to distribute them to $N$ people (numbered $1$ through $N$). These people are standing in a line in such a way that for each $i$ ($1 \le i \le N-1$), person $i$ and person $i+1$ are adjacent.
First, consider some way to distribute chocolates such that for each valid $i$, the number of chocolates the $i$-th person would receive from Chef is $A_i$ and the sum $S_1 = \sum_{i=1}^{N-1} \left|A_i - A_{i+1}\right|$ is minimum possible. Of course, each person must receive a non-negative integer number of chocolates.
Then, Chef wants to create a new sequence $B_1, B_2, \ldots, B_N$ by rearranging (permuting) the elements of the sequence $A_1, A_2, \ldots, A_N$. For each valid $i$, the number of chocolates the $i$-th person actually receives from Chef is $B_i$. Chef wants to distribute the chocolates (choose $B_1, B_2, \ldots, B_N$ by permuting the sequence $A$ and give $B_i$ chocolates to the $i$-th person for each valid $i$) in such a way that $S_2 = \sum_{i=1}^{N-1} \left|B_i – B_{i+1}\right|$ is maximum possible. You need to find the maximum value of $S_2$.
It is guaranteed that $S_2$ does not depend on the exact choice of the sequence $A_1, A_2, \ldots, A_N$, as long as it is a sequence that minimises $S_1$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains a single integer $K$.

-----Output-----
For each test case, print a single line containing one integer — the maximum value of the sum $S_2$.

-----Constraints-----
- $1 \le T \le 10$
- $2 \le N \le 10^5$
- $2 \le K \le 10^{100,000}$

-----Subtasks-----
Subtask #1 (30 points): $2 \le N, K \le 1,000$
Subtask #2 (70 points): original constraints

-----Example Input-----
1
3
2

-----Example Output-----
2

-----Explanation-----
Example case 1: To minimise $S_1$, Chef could give $1$ chocolate to person $1$ and $1$ chocolate to person...

t = int(input())
while(t > 0):
 t = t - 1
 n = int(input())
 k = int(input())
 num_1 = k % n
 num_0 = n - num_1
 ans = 0
 if(num_0 > num_1):
  ans = num_1 * 2
 elif(num_0 < num_1):
  ans = num_0 * 2
 else:
  ans = num_1 * 2 - 1
 print(ans)


Solve in Python:
Chef has $N$ axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their $4N$ vertices are pairwise distinct.
Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining $4N-1$ points and you should find the missing one.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- Then, $4N-1$ lines follow. Each of these lines contains two space-separated integers $x$ and $y$ denoting a vertex $(x, y)$ of some rectangle.

-----Output-----
For each test case, print a single line containing two space-separated integers $X$ and $Y$ ― the coordinates of the missing point. It can be proved that the missing point can be determined uniquely.

-----Constraints-----
- $T \le 100$
- $1 \le N \le 2 \cdot 10^5$
- $|x|, |y| \le 10^9$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$

-----Subtasks-----
Subtask #1 (20 points):
- $T = 5$
- $N \le 20$
Subtask #2 (30 points): $|x|, |y| \le 10^5$
Subtask #3 (50 points): original constraints

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

-----Example Output-----
2 2

-----Explanation-----
The original set of points are:

Upon adding the missing point $(2, 2)$, $N = 2$ rectangles can be formed:

# cook your dish here
t = int(input())
for _ in range(t):
 n = int(input())
 x = []
 y = []
 for i in range(4*n-1):
  a,b = list(map(int, input().split()))
  x.append(a)
  y.append(b)
 xs = set(x)
 ys = set(y)
 for i in xs:
  if x.count(i)%2!=0:
   p = i
   break
 for j in ys:
  if y.count(j)%2!=0:
   q = j
   break
 print(p,q)


Solve in Python:
Chef has $N$ dishes of different types arranged in a row: $A_1, A_2, \ldots, A_N$, where $A_i$ denotes the type of the $i^{th}$ dish. He wants to choose as many dishes as possible from the given list but while satisfying two conditions:
- He can choose only one type of dish.
- No two chosen dishes should be adjacent to each other.
Chef wants to know which type of dish he should choose from, so that he can pick the maximum number of dishes.
Example:

Given $N$=$9$ and $A$=$[1, 2, 2, 1, 2, 1, 1, 1, 1]$.

For type 1, Chef can choose at most four dishes. One of the ways to choose four dishes of type 1 is $A_1$, $A_4$, $A_7$ and $A_9$.

For type 2, Chef can choose at most two dishes. One way is to choose $A_3$ and $A_5$.

So in this case, Chef should go for type 1, in which he can pick more dishes.

-----Input:-----
- The first line contains $T$, the number of test cases. Then the test cases follow.
- For each test case, the first line contains a single integer $N$.
- The second line contains $N$ integers $A_1, A_2, \ldots, A_N$.

-----Output:-----
For each test case, print a single line containing one integer ― the type of the dish that Chef should choose from. If there are multiple answers, print the smallest one.

-----Constraints-----
- $1 \le T \le 10^3$
- $1 \le N \le 10^3$
- $1 \le A_i \le 10^3$
- Sum of $N$ over all test cases doesn't exceed $10^4$

-----Sample Input:-----
3
5
1 2 2 1 2
6
1 1 1 1 1 1
8
1 2 2 2 3 4 2 1

-----Sample Output:-----
1
1
2

-----Explanation:-----
Test case 1:

For both type 1 and type 2, Chef can pick at most two dishes. In the case of multiple answers, we pick the smallest one. Hence the answer will be $1$.
Test case 2:

There are only dishes of type 1. So the answer is $1$.
Test case 3:

For type 1, Chef can choose at most two dishes. For type 2, he can choose three dishes. For type 3 and type 4, Chef can choose the only dish available. Hence the maximum is in type 2 and so the answer is $2$.

t=int(input())
f=0
y=0
for _ in range(t):
 n=int(input())
 seq=[int(x) for x in input().split()]
 prev=seq[0]
 for i in range(1,len(seq)):
  if prev==seq[i]:
   seq[i]=0
  prev=seq[i]
 ans=0
 anss=0
 for el in seq:
  if el!=0:
   c=seq.count(el)
   if ans<c:
    ans=c

    anss=el
   elif ans==c:
    if el<anss:
     anss=el
    else:
     anss=anss
 print(anss)


Solve in Python:
Chef has $N$ markers. There is a cap on each marker. For each valid $i$, the $i$-th marker has colour $a_i$. Initially, for each valid $i$, the colour of the cap on the $i$-th marker is also $a_i$.
Chef wants to rearrange the caps in such a way that no marker has the same colour as its cap. (Obviously, each marker must have exactly one cap.) Can he do that? If he can, find one such way to rearrange the caps. If there are multiple solutions, you may find any one.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $a_1, a_2, \ldots, a_N$.

-----Output-----
- For each test case:
- If Chef cannot successfully rearrange the caps, print a single line containing the string "No" (without quotes).
- Otherwise, print two lines. The first line should contain the string "Yes" (without quotes). The second line should contain $N$ space-separated integers describing a valid rearrangement of caps. For each valid $i$, the $i$-th of these integers should denote the final colour of the cap on the $i$-th marker.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^5$
- $1 \le a_i \le 10^9$ for each valid $i$

-----Example Input-----
2
9
1 1 1 2 2 2 3 3 3
2
1 1

-----Example Output-----
Yes
2 2 2 3 3 3 1 1 1
No

t=int(input())
for _ in range(t):
 n=int(input())
 a=list(map(int,input().split()))
 f={}
 poss=1
 A=[[a[i],i] for i in range(n)]
 for i in range(n):
  if(a[i] in f):
   f[a[i]]+=1
  else:
   f[a[i]]=1
 for i in list(f.values()):
  if(i>n//2):
   poss=0
 if(poss):
  A.sort()

  ans=[0]*n
  j=max(f.values())
  B=A[j:]+A[:j]

  for i in range(n):
   ans[A[i][1]]=B[i][0]

  print("Yes")
  print(*ans)
 else:
  print("No")


Solve in Python:
Chef has $N$ points (numbered $1$ through $N$) in a 2D Cartesian coordinate system. For each valid $i$, the $i$-th point is $(x_i, y_i)$. He also has a fixed integer $c$ and he may perform operations of the following type: choose a point $(x_i, y_i)$ and move it to $(x_i + c, y_i + c)$ or $(x_i - c, y_i - c)$.
Now, Chef wants to set up one or more checkpoints (points in the same coordinate system) and perform zero or more operations in such a way that after they are performed, each of his (moved) $N$ points is located at one of the checkpoints.
Chef's primary objective is to minimise the number of checkpoints. Among all options with this minimum number of checkpoints, he wants to choose one which minimises the number of operations he needs to perform.
Can you help Chef find the minimum number of required checkpoints and the minimum number of operations he needs to perform to move all $N$ points to these checkpoints?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $c$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $x_i$ and $y_i$.

-----Output-----
For each test case, print a single line containing two integers ― the minimum number of checkpoints and the minimum number of moves.

-----Constraints-----
- $1 \le T \le 5$
- $1 \le N \le 5 \cdot 10^5$
- $|x_i|, |y_i| \le 10^9$ for each valid $i$
- $0 < c \le 10^9$
- the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$

-----Example Input-----
1
3 1
1 1
1 0
3 2

-----Example Output-----
2 2

-----Explanation-----
Example case 1: One optimal solution is to set up checkpoints at coordinates $(1, 1)$ and $(1, 0)$. Since the points $(1, 1)$ and $(1, 0)$ are already located at checkpoints, Chef can just move the point $(3, 2)$ to the checkpoint $(1, 0)$ in two moves: $(3, 2) \rightarrow (2, 1) \rightarrow (1, 0)$.

for _ in range(int(input())):
 n,c = map(int , input().split())
 pts_line,summation = {},0
 for _ in range(n):
  x,y = map(int , input().split())
  if((y - x, x % c) in pts_line):
   pts_line[(y - x,x % c)].append(x)
  else:
   pts_line[(y - x,x % c)] = [x]
 for pt in pts_line:
  arc = sorted(pts_line[pt])
  for metre in arc:
   summation += abs(metre - arc[len(arc)//2])//c
 print(len(pts_line),summation)


Solve in Python:
Chef has $N$ small boxes arranged on a line from $1$ to $N$. For each valid $i$, the weight of the $i$-th box is $W_i$. Chef wants to bring them to his home, which is at the position $0$. He can hold any number of boxes at the same time; however, the total weight of the boxes he's holding must not exceed K at any time, and he can only pick the ith box if all the boxes between Chef's home and the ith box have been either moved or picked up in this trip.
Therefore, Chef will pick up boxes and carry them home in one or more round trips. Find the smallest number of round trips he needs or determine that he cannot bring all boxes home.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $W_1, W_2, \ldots, W_N$.

-----Output-----
For each test case, print a single line containing one integer ― the smallest number of round trips or $-1$ if it is impossible for Chef to bring all boxes home.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N, K \le 10^3$
- $1 \le W_i \le 10^3$ for each valid $i$

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

-----Example Output-----
-1
1
2
3

-----Explanation-----
Example case 1: Since the weight of the box higher than $K$, Chef can not carry that box home in any number of the round trip.
Example case 2: Since the sum of weights of both boxes is less than $K$, Chef can carry them home in one round trip.
Example case 3: In the first round trip, Chef can only pick up the box at position $1$. In the second round trip, he can pick up both remaining boxes at positions $2$ and $3$.
Example case 4: Chef can only carry one box at a time, so three round trips are required.

for _ in range(int(input())):
 n,k = list(map(int,input().split()))
 arr = list(map(int,input().split()))

 count = 0

 flag = True
 curr_sum = 0
 for i in arr:
  if i>k:
   flag = False
  else:
   curr_sum+=i

   if curr_sum>k:
    curr_sum = i
    count+=1

 if curr_sum<=k:
  count+=1
 if flag==False:
  print(-1)
 else:
  print(count)


Solve in Python:
Chef has N laddus of K sweetness each. Chef wants to eat all laddus, but Chef is restricted with the given condition that he must not eat two adjacent laddus. Chef starts calculating the maximum sweetness that he will get from the laddus. Find the maximum sweetness that chef gets at the end of all calculations.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, two integers $N, K$.

-----Output:-----
For each test case, output in a single line answer as Maximum sweetness the chef will have.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^5$
- $1 \leq K \leq 10^5$

-----Sample Input:-----
2
1 2
4 3

-----Sample Output:-----
2
6

-----EXPLANATION:-----
For 1) Chef will get only 1 laddu with sweetness 2.
For 2) Chef will have multiple ways as
[1,3], [2,4], [1,4] with sweetness 6
[1],[2],[3],[4] with sweetness 3.
Maximum sweetness will be 6.

# cook your dish here
t=int(input())

while t:
    t-=1

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

    if n%2==0:

        print((n//2)*k)
    else:
        print(((n//2)+1)*k)


Solve in Python:
Chef has N subordinates. In order to complete a very important order he will choose exactly K of them. He can't choose less than K since it will be not enough to complete the order in time. On the other hand if he chooses more than K subordinates he can't control them during the operation. Help him to find the number of ways he can choose the team to complete this very important order.

-----Input-----
The first line contains a single positive integer T <= 100, the number of test cases. T test cases follow. The only line of each test case contains two integers N and K, where 0 <= N, K < 2^64. It is guaranteed that the answer will be less than 2^64.

-----Output-----
For each test case, output a single line containing the number of ways to choose the required team.

-----Example-----
Input:
3
2 1
3 3
10 5

Output:
2
1
252

#!/usr/bin/python
import decimal
import sys

def C(N, K):
 if (K > N):
  return 0
 if (N - K < K):
  K = N - K;

 res = 1

 i = 1
 while (i <= K):
  res = res * (N - K + i)
  res = int(res / i)
  i = i + 1
 return res

T = int(sys.stdin.readline())

for t in range(T):
 (N, K) = list(map(int, sys.stdin.readline().split()))
 print(C(N, K))


Solve in Python:
Chef has a binary array in an unsorted manner. Cheffina challenges chef to find the transition point in the sorted (ascending) binary array. Here indexing is starting from 0.
Note: Transition point always exists.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains two lines of input, $N$.
- N space-separated binary numbers.

-----Output:-----
For each test case, output in a single line answer.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$

-----Sample Input:-----
1
5
0 1 0 0 1

-----Sample Output:-----
3

-----EXPLANATION:-----
binary array in sorted form will look like = [0, 0, 0, 1, 1]

# cook your dish here
t=int(input())
for i in range(t):
    n=int(input())
    l=list(map(int,input().split()))
    l.sort()
    x=l.index(1)
    print(x)


Solve in Python:
Chef has a calculator which has two screens and two buttons. Initially, each screen shows the number zero. Pressing the first button increments the number on the first screen by 1, and each click of the first button consumes 1 unit of energy.
Pressing the second button increases the number on the second screen by the number which is currently appearing on the first screen. Each click of the second button consumes B units of energy.
Initially the calculator has N units of energy.
Now chef wonders what the maximum possible number is, that he gets on the second screen of the calculator, with the limited energy.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
Each test case is described using a single line containing two integers, N and B.

-----Output-----
For each test case, output a single line containing the answer to this test case.

-----Constraints-----
- 1 ≤ T ≤ 10,000
- 1 ≤ N, B ≤ 1,000,000,000

-----Subtasks-----
- Subtask 1 (20 points): 1 ≤ N, B ≤ 1,000
- Subtask 2 (80 points): Original constraints

-----Example-----
Input:
3
10 2
8 5
6 1

Output:
12
3
9

-----Explanation-----
Example case 1. There are 10 units of energy available. Pressing second button takes 2 units of energy. Chef can achieve 12 on the second screen as follows.

- Press first button to get scores (1, 0). 9 units of energey is left.
- Press first button to get scores (2, 0). 8 units of energy remaining.
- Press first button to get scores (3, 0). 7 units of energy remaining.
- Press first button to get scores (4, 0). 6 units of energy remaining.
- Press second button to get scores (4, 4). 4 units of energy remaining.
- Press second button to get scores (4, 8). 2 units of energy remaining.
- Press second button to get scores (4, 12). 0 units of energy remaining.

from math import *
for j in range(int(input())):
 n,b=list(map(int,input().split()))
 a=n/(2*b)
 a1=ceil(a)
 a2=floor(a)
 d=(n-a1*b)*a1
 e=(n-a2*b)*a2
 print(max(d,e))


Solve in Python:
Chef has a circular plot of land of radius $R$ on which he wants to construct a swimming pool.
He wants the swimming pool to be square in shape with maximum possible area,so that he along
with his friends can enjoy themselves during their summer vacations.
Help Chef to find out the maximum area of the swimming pool that can be constructed in his
circular plot.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input,  $R$ i.e the radius of the plot.

-----Output:-----
For each testcase, output in a single line answer displaying the maximum possible area of the swimming pool.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq R \leq 10^8$

-----Sample Input:-----
2

5

10

-----Sample Output:-----
50

200

# cook your dish here
t=int(input())
for i in range(t):
    n=int(input())
    print(n*(n*2))


Solve in Python:
Chef has a circular sequence $A$ of $N$ non-negative integers $A_1, A_2, \ldots, A_N$ where $A_i$ and $A_{i+1}$ are considered adjacent, and elements $A_1$ and $A_N$ are considered adjacent.
An operation on position $p$ in array $A$ is defined as replacing $A_p$ by the bitwise OR of elements adjacent to $A_p$. Formally, an operation is defined as:
- If $p = 1$, replace $A_1$ with $A_N | A_{2}$
- If $1 < p < N$, replace $A_p$ with $A_{p-1} | A_{p+1}$
- If $p = N$, replace $A_N$ with $A_{N-1} | A_1$
Here, '|' denotes the bitwise OR operation.
Now, Chef must apply operations at each position exactly once, but he may apply the operations in any order.
Being a friend of Chef, you are required to find a sequence of operations, such that after applying all the $N$ operations, the bitwise OR of the resulting array is $K$, or determine that no such sequence of operations exist.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$ denoting the number of elements, and the required bitwise OR after operations.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output:-----
For each test case, if no valid sequence of operations exist, print -1.
Otherwise, print $N$ space-separated integers in which $i$-th integer denote the position chosen in the $i$-th operation. If there are multiple valid sequences of operations, you may print any valid sequence.

-----Constraints-----
- $1 \le T \le 10^5$
- $3 \le N \le 2*10^5$
- $0 \le A_i, K \le 10^9$
- It's guaranteed that the total length of the arrays in one test file doesn't exceed $10^6$

-----Sample Input:-----
5
3 6
2 1 6
3 6
2 1 5
3 7
2 4 6
3 7
1 2 4
3 7
1 2 6

-----Sample Output:-----
2 1 3
-1
-1
-1
2 3 1

-----Explanation:-----
In the first test case, initially, the sequence is {2, 1, 6}.
- Chef applies the operation on the $2^{nd}$ index, so the...

t=int(input())
def check():
    pref = [0]*n
    pref[0]=a[0]
    suff = [0]*n
    suff[-1]=a[-1]
    for i in range (1,n):
        pref[i] = pref[i-1]|a[i]
        suff[n-i-1] = suff[n-i]|a[n-i-1]
    if suff[1]==k:
        return 0
    elif pref[n-2]==k:
        return n-1
    else:
        for i in range (1,n-1):
            if pref[i-1]|suff[i+1] == k:
                return i
        return -1
while(t):
    t-=1
    n,k=[int(i) for i in input().split()]
    a=[int(i) for i in input().split()]
    ans = []
    arr = [0]*n
    for i in range (n):
        if k|a[i] != k:
            a[i] = a[i-1]|a[(i+1)%(n)]
            ans.append(i+1)
            arr[i]=1

    x = 0
    count = 0
    for i in range (n):
        x|=a[i]

    if x!= k:
        print(-1)
    else:
        y = check()
        if y == -1:
            print(-1)
        else:
            for i in range (y,n+y):
                if arr[i%n]==0:
                    arr[i%n]==1
                    ans.append((i%n)+1)
            print(*ans)


Solve in Python:
Chef has a garden with $N$ plants arranged in a line in decreasing order of height. Initially the height of the plants are $A_1, A_2, ..., A_N$.
The plants are growing, after each hour the height of the $i$-th plant increases by $i$ millimeters. Find the minimum number of integer hours that Chef must wait to have two plants of the same height.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space separated integers $A_1,A_2,..A_N$.

-----Output:-----
For each test case print a single line containing one integer, the minimum number of integer hours that Chef must wait to have two plants of the same height.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^5$
- $0\leq A_i \leq 10^{18}$
- $A_i >A_{i+1}$, for each valid $i$
- The Sum of $N$ over all test cases does not exceed $10^6$

-----Sample Input:-----
1
3
8 4 2

-----Sample Output:-----
2

-----EXPLANATION:-----
After $2$ hours there are two plants with the same height.
$[8,4,2] \rightarrow [9,6,5] \rightarrow [10,8,8]$.

# cook your dish here
for _ in range(int(input())):
 size = int(input())
 a = [int(x) for x in input().split(" ")]
 b = []
 for i in range(len(a)-1):
  b.append(a[i]-a[i+1])
 print(min(b))


Solve in Python:
Chef has a natural number N. Cheffina challenges chef to check whether the given number is divisible by the sum of its digits or not. If the given number is divisible then print "Yes" else "No".

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.

-----Output:-----
For each test case, output in a single line answer.

-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$

-----Sample Input:-----
2
16
27

-----Sample Output:-----
No
Yes

from sys import*
input=stdin.readline
t=int(input())
for _ in range(t):
    s=input()
    n=int(s)
    n1=n
    l=list(s)
    s1=0
    while n1!=0:
        s1+=n1%10
        n1//=10
    if n%s1==0:
        print("Yes")
    else:
        print("No")


Solve in Python:
Chef has a nice complete binary tree in his garden. Complete means that each node has exactly two sons, so the tree is infinite. Yesterday he had enumerated the nodes of the tree in such a way:
- Let's call the nodes' level a number of nodes that occur on the way to this node from the root, including this node. This way, only the root has the level equal to 1, while only its two sons has the level equal to 2.
- Then, let's take all the nodes with the odd level and enumerate them with consecutive odd numbers, starting from the smallest levels and the leftmost nodes, going to the rightmost nodes and the highest levels.
- Then, let's take all the nodes with the even level and enumerate them with consecutive even numbers, starting from the smallest levels and the leftmost nodes, going to the rightmost nodes and the highest levels.
- For the better understanding there is an example:
1
/           \
2                   4
/   \                /       \
3       5           7        9
/ \      /  \          /  \       /  \
6  8 10 12      14 16   18 20

Here you can see the visualization of the process. For example, in odd levels, the root was enumerated first, then, there were enumerated roots' left sons' sons and roots' right sons' sons.
You are given the string of symbols, let's call it S. Each symbol is either l or r. Naturally, this sequence denotes some path from the root, where l means going to the left son and r means going to the right son.
Please, help Chef to determine the number of the last node in this path.

-----Input-----
The first line contains single integer T number of test cases.
Each of next T lines contain a string S consisting only of the symbols l and r.

-----Output-----
Per each line output the number of the last node in the path, described by S, modulo 109+7.

-----Constraints-----
- 1 ≤ |T| ≤ 5
- 1 ≤ |S| ≤ 10^5
- Remember that the tree is infinite, so each path described by appropriate S is a correct...

mod=1000000007
for _ in range(int(input())):
    s=input().strip()
    level=1
    ans=1
    for a in s:
        if level%2!=0:
            if a=="l":
                ans=2*ans
            else:
                ans=2*ans+2
        else:
            if a=="l":
                ans=2*ans-1
            else:
                ans=2*ans+1
        ans=ans%mod
        level+=1

    print(ans)


Solve in Python:
Chef has a number N, Cheffina challenges the chef to check the divisibility of all the permutation of N by 2. If any of the permutations is divisible by 2 then print 1 else print 0.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.

-----Output:-----
For each test case, output in a single line answer 1 or 0.

-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$

-----Sample Input:-----
2
19
385

-----Sample Output:-----
0
1

# cook your dish here
t = int(input())
for _ in range(t):
    p = input()
    flag = False
    z = ['0','2','4','6','8']
    for ele in p:
        # print(ele)
        if ele in z:
            print(1)
            flag = True
            break
    if flag == False:
        print(0)


Solve in Python:
Chef has a number N, Cheffina challenges the chef to check the divisibility of all the permutation of N by 3. If any of the permutations is divisible by 3 then print 1 else print 0.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, two integers $N$.

-----Output:-----
For each test case, output in a single line answer 1 or 0.

-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$

-----Sample Input:-----
2
18
308

-----Sample Output:-----
1
0

from sys import stdin, stdout
input = stdin.readline
from collections import defaultdict as dd
import math
def geti(): return list(map(int, input().strip().split()))
def getl(): return list(map(int, input().strip().split()))
def gets(): return input().strip()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')

def solve():
    for _ in range(geta()):
        n=geta()
        if n%3==0:
            print(1)
        else:
            print(0)

def __starting_point():
    solve()

__starting_point()


Solve in Python:
Chef has a number N, Cheffina challenges the chef to check the divisibility of all the permutation of N by 5. If any of the permutations is divisible by 5 then print 1 else print 0.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input,$N$.

-----Output:-----
For each test case, output in a single line answer 1 or 0.

-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$

-----Sample Input:-----
2
19
385

-----Sample Output:-----
0
1

t=int(input())
while(t>0):
    n=input()
    if(('5' in n) or ('0' in n)):
        print(1)
    else:
        print(0)
    t-=1
# cook your dish here


Solve in Python:
Chef has a pepperoni pizza in the shape of a $N \times N$ grid; both its rows and columns are numbered $1$ through $N$. Some cells of this grid have pepperoni on them, while some do not. Chef wants to cut the pizza vertically in half and give the two halves to two of his friends. Formally, one friend should get everything in the columns $1$ through $N/2$ and the other friend should get everything in the columns $N/2+1$ through $N$.
Before doing that, if Chef wants to, he may choose one row of the grid and reverse it, i.e. swap the contents of the cells in the $i$-th and $N+1-i$-th column in this row for each $i$ ($1 \le i \le N/2$).
After the pizza is cut, let's denote the number of cells containing pepperonis in one half by $p_1$ and their number in the other half by $p_2$. Chef wants to minimise their absolute difference. What is the minimum value of $|p_1-p_2|$?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains a string with length $N$ describing the $i$-th row of the grid; this string contains only characters '1' (denoting a cell with pepperonis) and '0' (denoting a cell without pepperonis).

-----Output-----
For each test case, print a single line containing one integer — the minimum absolute difference between the number of cells with pepperonis in the half-pizzas given to Chef's friends.

-----Constraints-----
- $1 \le T \le 1,000$
- $2 \le N \le 1,000$
- $N$ is even
- the sum of $N \cdot N$ over all test cases does not exceed $2 \cdot 10^6$

-----Example Input-----
2
6
100000
100000
100000
100000
010010
001100
4
0011
1100
1110
0001

-----Example Output-----
2
0

-----Explanation-----
Example case 1: Initially, $|p_1-p_2| = 4$, but if Chef reverses any one of the first four rows from "100000" to "000001", $|p_1-p_2|$ becomes $2$.
Example case 2:...

# cook your dish here
T = int(input())
for _ in range(T):
 N = int(input())
 mini = 10000000
 count1,count2=0,0
 u = []
 save = []
 for i in range(N):
  a = input()
  u.append(a)
  x = a[:N//2].count('1')
  y = a[N//2:].count('1')
  count1+=x
  count2+=y
  save.append(x-y)
 if(count1==count2):
  print(0)
  continue
 for i in save:
  mini = min(abs(count1-2*i-count2),mini)
 print(mini)


Solve in Python:
Chef has a recipe book. He wishes to read it completely as soon as possible so that he could try to cook the dishes mentioned in the book.
The pages of the book are numbered $1$ through $N$. Over a series of days, Chef wants to read each page. On each day, Chef can choose to read any set of pages such that there is no prime that divides the numbers of two or more of these pages, i.e. the numbers of pages he reads on the same day must be pairwise coprime. For example, Chef can read pages $1$, $3$ and $10$ on one day, since $(1, 3)$, $(3, 10)$ and $(1, 10)$ are pairs of coprime integers; however, he cannot read pages $1$, $3$ and $6$ on one day, as $3$ and $6$ are both divisible by $3$. Since chef might get bored by reading the same recipe again and again, Chef will read every page exactly once.
Given $N$, determine the minimum number of days Chef needs to read the entire book and the pages Chef should read on each of these days.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $N$.

-----Output-----
For each test case:
- First, print a line containing a single integer $D$ ― the minimum number of days required to read the book. Let's number these days $1$ through $D$.
- Then, print $D$ lines describing the pages Chef should read. For each valid $i$, the $i$-th of these lines should contain an integer $C_i$ followed by a space and $C_i$ space-separated integers ― the numbers of pages Chef should read on the $i$-th day.
If there are multiple solutions with the minimum number of days, you may print any one.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^6$

-----Subtasks-----
Subtask #1 (20 points): $N \le 100$
Subtask #2 (80 points): original constraints

-----Example Input-----
1
5

-----Example Output-----
2
3 1 2 5
2 3 4

-----Explanation-----
Example case 1:
- On the first day, Chef should read three pages: $1$, $2$ and...

for _ in range(int(input())):
    n=int(input())
    if n%2==0:
        print(n//2)
        for i in range(1,n,2):
            print(2,i,i+1)
    else:
        if n==1:
            print(1)
            print(1,1)
        else:
            print(n//2)
            print(3,1,2,3)
            for i in range(4,n+1,2):
                print(2,i,i+1)


Solve in Python:
Chef has a rectangular matrix A of nxm integers. Rows are numbered by integers from 1 to n from top to bottom, columns - from 1 to m from left to right. Ai, j denotes the j-th integer of the i-th row.
Chef wants you to guess his matrix. To guess integers, you can ask Chef questions of next type: "How many integers from submatrix iL, iR, jL, jR are grater than or equal to x and less than or equal to y?". By submatrix iL, iR, jL, jR we mean all elements Ai, j for all iL ≤ i ≤ iR and jL ≤ j ≤ jR.
Also Chef can answer not more than C questions of next type: "What is the sum of integers from submatrix iL, iR, jL, jR?"
As soon as you think you know the Chefs matrix, you can stop asking questions and tell to the Chef your variant of the matrix. Please see "Scoring" part to understand how your solution will be evaluated.

-----Input-----
The first line of the input contains three space-separated integers n, m and C denoting the sizes of the matrix and the maximum number of the second-type questions. After that the judge will answer your questions and evaluate the resuts. Read more about that in the "Interaction with the judge" part of the statement.

-----Interaction with the judge-----
To ask a first-type question you should print to the standard output one line containing seven space-separated integers 1 iL iR jL jR x y. To ask a second-type question you should print one line containing five space-separated integers 2 iL iR jL jR. After that you should read from the standard input one integer - answer to the question. To end the game you should print 3 and starting from next line print n lines, each of them contains m space-separated integers - your variant of the matrix A. After that your program must stop. Remember to flush the output after every line you print.

-----Constraints-----
- 1 ≤ n, m ≤ 2.5 * 105
- 1 ≤ n * m ≤ 2.5 * 105
- 103 ≤ C ≤ 104
- 1 ≤ Ai, j ≤ 50
- 1 ≤ iL ≤ iR ≤ n
- 1 ≤ jL ≤ jR ≤ m
- 1 ≤ x ≤ y ≤ 50
- 0 ≤ number of asked questions ≤ 5 * 105
- 1 ≤ Bi, j ≤ 50
- 1 ≤ a1, a2, a3 ≤ 10

----- Scoring...

import sys
n,m,c=list(map(int,input().split()))
li=[]
max=0
for i in range(1,51):
       print(1,1,n,1,m,i,i)
       sys.stdout.flush()
       ans=int(input())
       if ans>max:
              max=ans
              deal=i

print(3)
for i in range(n):
       print(" ".join([str(deal)]*m))


Solve in Python:
Chef has a rectangular piece of paper. He puts it on a big board in such a way that two sides of the paper are horizontal and two are vertical, and then he performs a sequence of $N$ operations. You are given a string $S$ with length $N$; for each valid $i$, the $i$-th character of $S$ determines the type of the $i$-th operation:
- 'R': Pick up the paper from the right side and fold it onto the left side.
- 'L': Pick up the paper from the left side and fold it onto the right side.
- 'U': Pick up the paper from the upper side and fold it onto the bottom side.
- 'D': Pick up the paper from the bottom side and fold it onto the upper side.
The paper is folded in such a way that there is still a flat rectangular sheet of paper lying on the table after each operation, but it consists of multiple layers of the original sheet. The lengths of the horizontal and vertical sides of the resulting sheet (after performing these $N$ operations) are $W$ and $H$ respectively. Let's build an Euclidean coordinate system on the paper, where the point $(0, 0)$ corresponds to the bottom left corner and $(W, H)$ to the upper right corner.
Chef then draws $M$ points on this folded sheet of paper. The ink used to draw them soaks deep into the paper, so each point is drawn on all layers of the paper (and also on both faces of each layer).
Finally, Chef completely unfolds the paper. He's asking you to compute the distance between the nearest pair of points.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains four space-separated integers $N$, $M$, $W$ and $H$.
- The second line contains a single string $S$.
- Each of the following $M$ lines contains two space-separated integers $X$ and $Y$ denoting the coordinates of one point.

-----Output-----
For each test case, print a single line containing one real number ― the minimum distance. Your answer will be considered correct if its absolute or...

# cook your dish here folding paper
from collections import Counter
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def dist(a,b):return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
for _ in range(val()):
 n,m,w,h=li()
 s=Counter(st())
 l=[]
 for i in range(m):
  l.append(li())
 ans=float('inf')
 l.sort(key=lambda x:x[0])
 for j in range(1,50):
  for i in range(j,m):
   ans=min(ans,dist(l[i-j],l[i]))
 for i in l:
  if s['D'] or s['U']>1:ans=min(ans,2*i[1])
  if s['U'] or s['D']>1:ans=min(ans,2*(h-i[1]))
  if s['L'] or s['R']>1:ans=min(ans,2*i[0])
  if s['R'] or s['L']>1:ans=min(ans,2*(w-i[0]))
 print(ans)


Solve in Python:
Chef has a sequence $A_1, A_2, \ldots, A_N$. For a positive integer $M$, sequence $B$ is defined as $B = A*M$ that is, appending $A$ exactly $M$ times. For example, If $A = [1, 2]$ and $M = 3$, then $B = A*M = [1, 2, 1, 2, 1, 2]$
You have to help him to find out the minimum value of $M$ such that the length of the longest strictly increasing subsequence is maximum possible.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output:-----
For each test case, print a single line containing one integer ― the minimum value of $M$.

-----Constraints-----
- $1 \le T \le 500$
- $1 \le N \le 2*10^5$
- $1 \le A_i \le 10^9$
- It's guaranteed that the total length of the sequence $A$ in one test file doesn't exceed $2*10^6$

-----Sample Input:-----
3
2
2 1
2
1 2
5
1 3 2 1 2

-----Sample Output:-----
2
1
2

-----Explanation:-----
In the first test case, Choosing $M = 2$ gives $B = [2, 1, 2, 1]$ which has a longest strictly increasing sequence of length $2$ which is the maximum possible.
In the second test case, Choosing $M = 1$ gives $B  = [1, 2]$ which has a longest strictly increasing sequence of length $2$ which is the maximum possible.

from collections import defaultdict
for _ in range(int(input())):
    n = int(input())
    arr = list(map(int,input().split()))
    ans = 1
    d = defaultdict(list)
    for i in range(n):
        d[arr[i]].append(i+1)
    ind = -10**10
    uno = list(set(arr))
    uno.sort()
    for i in uno:
        f = 0
        f2 = 0
        k = 0
        op = d[i]
        for j in op:
            if f2==0:
                f2 = 1
                ck = j
            if j>ind:
                ind = j
                f = 1
                break
        if f==0:
            ind = ck
            ans+=1
    print(ans)


Solve in Python:
Chef has a sequence $A_1, A_2, \ldots, A_N$. This sequence has exactly $2^N$ subsequences. Chef considers a subsequence of $A$ interesting if its size is exactly $K$ and the sum of all its elements is minimum possible, i.e. there is no subsequence with size $K$ which has a smaller sum.
Help Chef find the number of interesting subsequences of the sequence $A$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer ― the number of interesting subsequences.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le K \le N \le 50$
- $1 \le A_i \le 100$ for each valid $i$

-----Subtasks-----
Subtask #1 (30 points): $1 \le N \le 20$
Subtask #2 (70 points): original constraints

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

-----Example Output-----
1

-----Explanation-----
Example case 1: There are six subsequences with length $2$: $(1, 2)$, $(1, 3)$, $(1, 4)$, $(2, 3)$, $(2, 4)$ and $(3, 4)$. The minimum sum is $3$ and the only subsequence with this sum is $(1, 2)$.

import math
t = int(input())
def t_min(li,k):
 x = 0
 for i in range(k):
  x += li[i]
 return x
def cnt(li,x):
 n = 0
 for i in li:
  if x == i:
   n += 1
 return n
def num_of_occur(li,k):
 z = li[k-1]
 y = 0
 for i in range(k):
  if(li[i] == z):
   y += 1
 return y
def factorials(z,y):
 return (math.factorial(z)/(math.factorial(y)*math.factorial((z - y))))

for a in range(t):
 n,k = [int(x) for x in input().split()]
 lis = [int(x) for x in input().split()]
 lis.sort()
 sumn = t_min(lis,k)
 y = num_of_occur(lis,k)
 z = cnt(lis,lis[k-1])
 print(int(factorials(z,y)))


Solve in Python:
Chef has a sequence $A_1, A_2, \ldots, A_N$; each element of this sequence is either $0$ or $1$. Appy gave him a string $S$ with length $Q$ describing a sequence of queries. There are two types of queries:
- '!': right-shift the sequence $A$, i.e. replace $A$ by another sequence $B_1, B_2, \ldots, B_N$ satisfying $B_{i+1} = A_i$ for each valid $i$ and $B_1 = A_N$
- '?': find the length of the longest contiguous subsequence of $A$ with length $\le K$ such that each element of this subsequence is equal to $1$
Answer all queries of the second type.

-----Input-----
- The first line of the input contains three space-separated integers $N$, $Q$ and $K$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- The third line contains a string with length $Q$ describing queries. Each character of this string is either '?', denoting a query of the second type, or '!', denoting a query of the first type.

-----Output-----
For each query of the second type, print a single line containing one integer — the length of the longest required subsequence.

-----Constraints-----
- $1 \le K \le N \le 10^5$
- $1 \le Q \le 3 \cdot 10^5$
- $0 \le A_i \le 1$ for each valid $i$
- $S$ contains only characters '?' and '!'

-----Subtasks-----
Subtask #1 (30 points):
- $1 \le N \le 10^3$
- $1 \le Q \le 3 \cdot 10^3$
Subtask #2 (70 points): original constraints

-----Example Input-----
5 5 3
1 1 0 1 1
?!?!?

-----Example Output-----
2
3
3

-----Explanation-----
- In the first query, there are two longest contiguous subsequences containing only $1$-s: $A_1, A_2$ and $A_4, A_5$. Each has length $2$.
- After the second query, the sequence $A$ is $[1, 1, 1, 0, 1]$.
- In the third query, the longest contiguous subsequence containing only $1$-s is $A_1, A_2, A_3$.
- After the fourth query, $A = [1, 1, 1, 1, 0]$.
- In the fifth query, the longest contiguous subsequence containing only $1$-s is $A_1, A_2, A_3, A_4$ with length $4$. However, we only want subsequences with lengths $\le K$. One of the longest such...

n, q, k = map(int, input().split())
arr = list(map(int, input().split()))
query = list(input())
q_ = len(query)
c1 = query.count('?')
c = arr.count(0)
if c == n:
 for i in range(c1):
  print(0)
else:
 for i in range(q_):
  if (i!=0) and (query[i] == '?' and query[i-1] == '?'):
   print(max_c)
  elif query[i] == '?':
   max_c = cnt = 0
   for j in range(n):
    if (j != n - 1) and (arr[j] == 1 and arr[j + 1] == 1):
     cnt += 1
    else:
     max_c = max(max_c, cnt + 1)
     cnt = 0
    if k < max_c:
     max_c = k
     break
   print(max_c)
  elif query[i] == '!':
   temp = arr[n - 1]
   del arr[n - 1]
   arr.insert(0, temp)


Solve in Python:
Chef has a sequence of $N$ integers, $A_1, A_2, ... , A_N$. He likes this sequence if it contains a  subsequence of $M$ integers, $B_1, B_2, ... , B_M$ within it.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
You will be given a sequence of $N$ integers, $A_1, A_2, ..., A_N$ followed by another sequence of $M$ integers, $B_1, B_2, ..., B_M$. Given these, you have to tell whether Chef likes the sequence of $N$ integers($A_1, A_2, ..., A_N$) or not.
Formally, output "Yes" if
$\exists idx_1, idx_2, ..., idx_M | 1 \le idx_1 < idx_2 < ... < idx_M \le N$ and $A_{idx_i} = B_i \forall i, 1 \le i \le M$
Otherwise output "No". Note that the quotes are for clarity.

-----Input-----
The first line contains a single integer, $T$.
$T$ test cases follow where each test case contains four lines:
- The first line of a test case contains a single integer $N$
- The second line of the test case contains $N$ space separated integers, $A_1, A_2, ..., A_N$
- The third line of the test case contains a single integer $M$.
- The fourth line contains $M$ space separated integers, $B_1, B_2, ..., B_M$
Symbols have usual meanings as described in the statement.

-----Output-----
For each test case, output a single line containing the output. Output is "Yes" if Chef likes the sequence $A$. Output is "No" if Chef dislikes the sequence $A$.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10^3$
- $1 \le M \le 10^3$
- $1 \le A_i, B_i \le 10^9$

-----Sample Input-----
3
6
1 2 3 4 5 6
3
2 3 4
6
22 5 6 33 1 4
2
4 15
4
1 3 4 2
2
1 2

-----Sample Output-----
Yes
No
Yes

-----Explanation:-----
In sample test case $1$, the sequence $1,2,3,4,5,6$ contains the subsequence $2, 3, 4$. The subsequence is present at indices $1, 2, 3$ of the original sequence.
Hence, $1,2,3,4,5,6$ is a sequence which Chef likes it. Therefore, we output "Yes".
In sample test case $2$, the subsequence $4, 15$ is not present in sequence $22, 5, 6, 33, 1, 4$....

# cook your dish here
for _ in range(int(input())):
 n1=int(input())
 l1=list(map(int,input().split()))
 n2=int(input())
 l2=list(map(int,input().split()))
 a=[]
 z=[]
 for i in range(len(l2)):
  if l2[i] in l1:
   for j in range(len(l1)):
    if l2[i] ==l1[j]:
     a.append(j)
     z.append(j)
     z.sort()
 if len(l2)==len(a) and a==z:
  print('Yes')
 else:
  print('No')


Solve in Python:
Chef has a sequence of N$N$ integers A1,A2,...,AN$A_1, A_2, ..., A_N$.
Chef thinks that a triplet of integers (i,j,k)$(i,j,k)$ is good if 1≤i<j<k≤N$1 \leq i < j < k \leq N$ and P$P$ in the following expression contains an odd number of ones in its binary representation:
P=[Ai<<(⌊log2(Aj)⌋+⌊log2(Ak)⌋+2)]+[Aj<<(⌊log2(Ak)⌋+1)]+Ak$P = [ A_i<< (  \lfloor \log_2(A_j) \rfloor + \lfloor \log_2(A_k) \rfloor + 2 ) ] + [A_j << ( \lfloor \log_2(A_k) \rfloor + 1) ] + A_k$
The <<$<<$ operator is called left shift, x<<y$x << y$  is defined as x⋅2y$x \cdot 2^y$.
Help the Chef finding the total number of good triplets modulo 109+7$10^9 + 7$.

-----Input:-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains a single integer N$N$.
- The second line of each test case contains N$N$ space-separated integers A1,A2,...,AN$A_1, A_2, ..., A_N$.

-----Output:-----
For each test case, print a single line containing one integer, the number of good triplets modulo 109+7$10^9+7$.

-----Constraints:-----
- 1≤T≤103$1 \leq T \leq 10^3$
- 1≤N≤105$1\leq N \leq 10^5$
- 1≤Ai≤109$1 \leq A_i \leq 10^9$
- The sum of N$N$ over all testcases is less than 106$10^6$

-----Sample Input:-----
1
4
1 1 2 3

-----Sample Output:-----
1

from math import *
t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(d) for d in input().split()]
    odd,even = 0,0
    for i in range(n):
     if bin(a[i]).count("1")%2 == 1:
      odd += 1
     else:
      even +=1
    total = 0
    if odd >= 3 and even >= 2:
     total += (odd*(odd-1)*(odd-2))//6
     total += odd*(even*(even-1))//2
    elif odd >= 3 and even < 2:
     total +=  (odd*(odd-1)*(odd-2))//6
    elif 0<odd < 3 and even >= 2:
     total +=  odd*(even*(even-1))//2

    print(total%(10**9+7))


Solve in Python:
Chef has a sequence of positive integers $A_1, A_2, \ldots, A_N$. He wants to choose some elements of this sequence (possibly none or all of them) and compute their MEX, i.e. the smallest positive integer which does not occur among the chosen elements. For example, the MEX of $[1, 2, 4]$ is $3$.
Help Chef find the largest number of elements of the sequence $A$ which he can choose such that their MEX is equal to $M$, or determine that it is impossible.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $M$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum number of elements Chef can choose, or $-1$ if he cannot choose elements in such a way that their MEX is $M$.

-----Constraints-----
- $1 \le T \le 100$
- $2 \le M \le N \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$

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

-----Example Output-----
3

-----Explanation-----
Example case 1: The MEX of whole array is 3. Hence, we can choose all the elements.

from sys import stdin, stdout
from collections import defaultdict as D

try:
    for _ in range(int(input())):
        n,m=[int(i) for i in stdin.readline().split()]
        a=[int(i) for i in stdin.readline().split()]
        d = D(lambda:0)
        for i in a:
            d[i] += 1

        k = 1
        for i in range(1, max(a) + 2):
            if d[i] == 0:
                k = i
                break

        if k==m:
            print(n)
        elif k<m:
            print(-1)
        elif k>m:
            print(n - d[m])
except:
    pass


Solve in Python:
Chef has a sequence of positive integers $A_1, A_2, \ldots, A_N$. He wants to split this sequence into two non-empty (not necessarily contiguous) subsequences $B$ and $C$ such that $\mathrm{GCD}\,(B) + \mathrm{GCD}\,(C)$ is maximum possible. Help him find this maximum value.
Note: The greatest common divisor (GCD) of a sequence of positive integers is the largest positive integer that divides each element of this sequence. For example, the GCD of the sequence $(8, 12)$ is $4$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer — the maximum value of $\mathrm{GCD}\,(B) + \mathrm{GCD}\,(C)$.

-----Constraints-----
- $1 \le T \le 10$
- $2 \le N \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$

-----Subtasks-----
Subtask #1 (20 points): $2 \le N \le 20$
Subtask #2 (80 points): original constraints

-----Example Input-----
1
4
4 4 7 6

-----Example Output-----
9

-----Explanation-----
Example case 1: For example, the sequence $A$ can be divided into subsequences $B = (4, 4, 6)$ and $C = (7)$.

# cook your dish here
import math
for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    newa=list(set(a))
    if len(newa)==1:
        print(newa[0]*2)
    elif len(newa)==2:
        print(sum(newa))
    else:
        newa.sort()
        m1=newa.pop()
        m2=newa.pop()
        gcd=newa[0]
        for i in range(1,len(newa)):
            gcd=math.gcd(gcd,newa[i])
            if gcd==1:
                break
        s1=math.gcd(gcd,m1)
        s2=math.gcd(gcd,m2)
        print(max(s1+m2,s2+m1))


Solve in Python:
Chef has a string of size $N$ which consists only lowercase English alphabet. The chef doesn't like the consonant alphabet at all. So he is thinking of changing every single consonant alphabet to any vowel alphabet. There is some cost for performing this operation.
- Number all alphabet [a,b,c,……,z] as [1,2,3,…..,26]
- So if you want to change c to e then cost will be |e-c| = |5-3| = 2
You need the answer at what minimum cost chef can change every single consonant alphabet to any vowel alphabet.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains of a single line of input, a string of lowercase alphabet.

-----Output:-----
For each test case, output in a single line answer.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq |s| \leq 10^2$

-----Sample Input:-----
2
aeiou
dbcc

-----Sample Output:-----
0
6

-----EXPLANATION:-----
In the first test case, all characters are already vowel so we don't need to change.
In the second tect case
|e-d|=|5-4|=1
|a-b|=|1-2|=1
|a-c|=|1-3|=2
|a-c|=|1-3|=2
1+1+2+2=6

# cook your dish here
t=int(input())
for i in range(t):
    s=input()
    a="aeiou"
    cnt=0
    for i in range(len(s)):
        x=s[i]
        arr=[]
        for j in range(5):
            z=abs(ord(x)-ord(a[j]))
            arr.append(z)
        cnt+=min(arr)
    print(cnt)


Solve in Python:
Chef has a strip of length $N$ units and he wants to tile it using $4$ kind of tiles

-A Red tile of $2$ unit length

-A Red tile of $1$ unit length

-A Blue tile of $2$ unit length

-A Blue tile of $1$ unit length
Chef is having an infinite supply of each of these tiles. He wants to find out the number of ways in which he can tile the strip. Help him find this number.
Since this number can be large, output your answer modulo 1000000007 ($10^9 + 7$).

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, an integer $N$.

-----Output:-----
For each testcase, output in a single line your answer modulo 1000000007.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^{18}$

-----Sample Input:-----
1
2

-----Sample Output:-----
6

-----EXPLANATION:-----

It can be seen that for a strip of length $2$, there are $6$ possible configurations.
$NOTE : $ 2 tiles of 1 unit length are different from 1 tile of 2 unit length.


Solve in Python:
Chef has an array A = (A1, A2, ..., AN), which has N integers in it initially. Chef found that for i ≥ 1, if Ai > 0, Ai+1 > 0, and Ai+2 exists, then he can decrease both Ai, and Ai+1 by one and increase Ai+2 by one. If Ai+2 doesn't exist, but Ai > 0, and Ai+1 > 0, then he can decrease both Ai, and Ai+1 (which will be the currently last two elements of the array) by one and add a new element at the end, whose value is 1.
Now Chef wants to know the number of different arrays that he can make from A using this operation as many times as he wishes. Help him find this, and because the answer could be very large, he is fine with you reporting the answer modulo 109+7.
Two arrays are same if they have the same number of elements and if each corresponding element is the same. For example arrays (2,1,1) and (1,1,2) are different.

-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases.
- The first line contains a single integer N denoting the initial number of elements in A.
- The second line contains N space-separated integers: A1, A2, ... , AN.

-----Output-----
For each test case, output answer modulo 109+7 in a single line.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 50
- 0 ≤ Ai ≤ 50

-----Subtasks-----
- Subtask 1 (20 points) : 1 ≤ N ≤ 8, 0 ≤ Ai ≤ 4
- Subtask 2 (80 points) : Original constraints

-----Example-----
Input:
3
3
2 3 1
2
2 2
3
1 2 3

Output:
9
4
9

-----Explanation-----
Example case 1.
We'll list the various single steps that you can take (ie. in one single usage of the operation):
- (2, 3, 1) → (2, 2, 0, 1)
- (2, 2, 0, 1) → (1, 1, 1, 1)
- (1, 1, 1, 1) → (1, 1, 0, 0, 1)
- (1, 1, 0, 0, 1) → (0, 0, 1, 0, 1)
- (1, 1, 1, 1) → (1, 0, 0, 2)
- (1, 1, 1, 1) → (0, 0, 2, 1)
- (2, 3, 1) → (1, 2, 2)
- (1, 2, 2) → (0, 1, 3)

So all the arrays you can possibly get are:
(2, 3, 1), (2, 2, 0, 1), (1, 1, 1, 1), (1, 1, 0, 0, 1), (0, 0, 1, 0, 1), (1, 0, 0, 2), (0, 0, 2, 1), (1, 2, 2), and (0, 1, 3)
Since there are 9 different arrays that you can reach, the answer is 9.