Solve in Python:
Chef has an array A consisting of N elements. He wants to find number of pairs of non-intersecting segments [a, b] and [c, d] (1 ≤ a ≤ b < c ≤ d ≤ N) such there is no number that occurs in the subarray {Aa, Aa+1, ... , Ab} and   {Ac, Ac+1, ... , Ad} simultaneously.
Help Chef to find this number.

-----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 elements in the array.
- The second line contains N space-separated integers A1, A2, ..., AN.

-----Output-----
- For each test case, output a single line containing one integer - number of pairs of non-intersecting segments.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 1000
- 1 ≤ Ai ≤ 109

-----Subtasks-----Subtask 1 (7 points)
- 1 ≤ N ≤ 20Subtask 2 (34 points)
- 1 ≤ N ≤ 300Subtask 3 (59 points)
- Original constraints

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

Output:
5
4

-----Explanation-----
Example case 1.
All possible variants are correct: {[1, 1], [2, 2]}, {[1, 1], [2, 3]}, {[1, 2], [3, 3]}, {[2, 2], [3, 3]}, {[1,1], [3, 3]}.

Example case 2.
Correct segments: {[1, 1], [2, 2]}, {[1, 1], [4, 4]}, {[2, 2], [3, 3]}, {[3, 3], [4, 4]}.

def func():
 count=0
 N=len(A)
 marker=[0 for h in range(N)]
 for i in range(N-1):
  for group_size in range(1,N-i):
   I=set(A[i:i+group_size])
   m=0
   new_element=A[i+group_size-1]
   for j in range(i+group_size,N):
    if(group_size==1):
     if(A[j] not in I):
      m+=1
      marker[j]=0
      #print "hello",A[j],m
     else:
      marker[j]=1
      count+=(m*(m+1)/2)
      #print "oops",count,m
      m=0
    else:
     if(marker[j]==0 and A[j]!=new_element):
      m+=1
     else:
      marker[j]=1
      count+=(m*(m+1)/2)
      m=0
   count+=(m*(m+1)/2)
 print(count)

T=int(input())

for t in range(T):
 N=int(input())
 A=input().split(" ")

 for i in range(N):
  A[i]=int(A[i])

 func()


Solve in Python:
Chef has an array A consisting of N integers (1-based indexing). He asks you to perform the following operation M times:

	for i = 2 to N:
		Ai = Ai + Ai-1

Your task is to find the xth element of the array (i.e., Ax) after performing the above operation M times. As the answer could be large, please output it modulo 109 + 7.

-----Input-----
- The first line of input contains an integer T denoting the number of test cases.
- The first line of each test case contains three space-separated integers — N, x, and M — denoting the size of the array, index of the element you need to find, and the amount of times you need to repeat operation before finding the element, respectively. The second line contains N space-separated integers A1, A2, …, AN.

-----Output-----
For each test case, output a single line containing one integer: Ax modulo 109 + 7.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ x ≤ N ≤ 105
- 1 ≤ M ≤ 1018
- 1 ≤ Ai  ≤ 1018

-----Subtasks-----Subtask 1 (8 points):
- 1 ≤ x ≤ min{2, N}Subtask 2 (24 points):
- 1 ≤ N * M ≤ 106Subtask 3 (68 points):  No additional constraints

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

Output:
5
15

-----Explanation-----
Values in the array A:
- Before the operations: [1, 2, 3]
- After the first operation: [1, 3, 6]
- After the second operation: [1, 4, 10]
- After the third operation: [1, 5, 15]

Since input file can be fairly large (about 8 MB), it's recommended to use fast I/O (for example, in C++, use scanf/printf instead of cin/cout).

p=10**9+7
f=[1]*(100000+1)
for i in range(1,100000+1):
 f[i]=i*f[i-1]
 if f[i]>=p:
  f[i]=f[i]%p

for _ in range(int(input())):
 n,x,m=map(int,input().split( ))
 m=m%p
 a=list(map(int,input().split( )))
 pre=[1]*(x)
 for i in range(1,x):
  pre[i]=pre[i-1]*(m+(i-1))*f[i-1]
  if pre[i]>=p:
   pre[i]=pre[i]%p
  pre[i]=pre[i]//f[i]
 ans=0
 j=0
 for i in range(x-1,-1,-1):
  ans+=a[j]*pre[i]
  if ans>=p:
   ans=ans%p
  j+=1
 print(ans%p)


Solve in Python:
Chef has an array A consisting of N integers. He also has an intger K.
Chef wants you to find out number of different arrays he can obtain from array A by applying the following operation exactly K times.

- Pick some element in the array and multiply it by -1

As answer could be quite large, print it modulo 109 + 7.

-----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 two space separated integers N, K as defined above.
- The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.

-----Output-----
- For each test case, output a single line containing an integer corresponding to the number of different arrays Chef can get modulo 109 + 7.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N, K ≤ 105
- -106 ≤ Ai ≤ 106

-----Subtasks-----
- Subtask #1 (10 points) : N, K ≤ 10
- Subtask #2 (30 points) : N, K ≤ 100
- Subtask #3 (60 points) : N, K ≤ 105

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

Output:
1
3
4

-----Explanation-----
Example case 1.
Chef has only one element and must apply the operation 3 times to it. After applying the operations, he will end up with -100. That is the only array he will get.

Example case 2.
Chef can apply operation to one of three elements. So, he can obtain three different arrays.

Example case 3.
Note that other than applying operation to positions (1, 2), (1, 3), (2, 3), Chef can also apply the operation twice on some element and get the original.

In summary, Chef can get following four arrays.

[1, 2, 1]
[-1, -2, 1]
[-1, 2, -1]
[1, -2, -1]

mod = 10**9 + 7
for t in range(int(input())):
 n, k = list(map(int, input().split()))
 a = list(map(int, input().split()))
 ans = 0
 temp = 1
 limit = min(n,k)+1
 c = a.count(0)
 if (c == 0):
  x = k%2
  for i in range(0, limit):
   if (i%2 == x):
    ans += temp
    ans %= mod
   temp = (temp * (n-i)) / (1+i)
 else:
  n = n-c
  for i in range(0, limit):
   ans += temp
   ans %= mod
   temp = (temp * (n-i)) / (1+i)
 print(ans)


Solve in Python:
Chef has an array of N integers. He wants to play a special game. In this game he needs to make all the integers in the array greater than or equal to 0.
Chef can use two types of operations. The first type is to  increase all the integers of the given array by 1, but it costs X coins. The operation of the second type is to add 1 to only one integer of the given array and to use this operation you need to pay 1 coin. You need to calculate the minimal cost to win this game (to make all integers greater than or equal to 0)

-----Input-----

The first line of the input contains an integer N denoting the number of elements in the given array. The second line contains N space-separated integers A1, A2, ..., AN denoting the given array. The third line contains number X - cost of the first type operation.

-----Output-----
For each test case, output a single line containing minimal cost required to make all the integers greater than or equal to zero.

-----Constraints-----

- 1 ≤ N ≤ 105
- -109 ≤ Ai ≤  109
- 0 ≤ X  ≤ 109

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

Output:
5

-----Explanation-----
Example case 1: Use the first type operation twice and the second type once.

# cook your dish here
n=int(input())
k=n+1
total=0
a=list(map(int,input().split()))
x=int(input())
a.sort(reverse=True)
for i in range(n):
 if a[i]<0:
  k=i
  break
a=a[k:]
if a:
 n=len(a)
 if x>n:
  total-=sum(a)
 else:
  total-=sum(a[n-x:])
print(total)


Solve in Python:
Chef has an array of N natural numbers most of them are repeated. Cheffina challenges chef to find all numbers(in ascending order) whose frequency is strictly more than K.

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

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

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N, K \leq 10^5$
- $1 \leq arr[i] \leq 10^5$

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

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

from collections import Counter
for _ in range(int(input())):
    a,b=map(int,input().split())
    ar=list(map(int,input().split()))
    ar=Counter(ar)
    dr=[]
    for i in ar:
        if(ar[i]>b):
            dr.append(i)
    dr.sort()
    print(*dr)


Solve in Python:
Chef has an array of N natural numbers. Cheffina challenges the chef to choose the two numbers from the array and following the condition as the area of the rectangle formed from the two numbers is maximum. Cheffina also asks the chef to choose two numbers different from the previous two to form the rectangle with a minimum area.

-----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$.
- N space-separated natural numbers.

-----Output:-----
For each test case, output in one line answers maximum and minimum area of a rectangle.

-----Constraints-----
- $1 \leq T \leq 10$
- $4 \leq N \leq 10^5$
- $1 \leq arr[i] \leq 10^6$

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

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

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    a.sort()
    print(a[-1]*a[-2],a[0]*a[1])


Solve in Python:
Chef has an old machine if the chef enters any natural number, the machine will display 1, 2, …n, n-1, n-2, n-3,…1 series and in next line prints sum of cubes of each number in the series. Chef wants to create a computer program which can replicate the functionality of the machine. Help the chef to code.

-----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 50$
- $1 \leq N \leq 50$

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

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

-----EXPLANATION:-----
For 2) series will be 1, 2, 3, 2, 1 and the sum will be = 1 + 8 + 27 + 8+ 1

# cook your dish here
for i in range(int(input())):
    n = int(input())
    s = [x for x in range(1,n+1)]
    su = [n]
    summ = 0
    for i in range(len(s)-1):
        su.append(s[i])
        su.append(s[i])
    for x in range(len(su)):
        summ += su[x] ** 3
    print(summ)


Solve in Python:
Chef has arrived in Dagobah to meet with Yoda to study cooking. Yoda is a very busy cook and he doesn't want to spend time with losers. So he challenges the Chef to a series of games, and agrees to teach the Chef if Chef can win at least P of the games. The total number of games is K. The games will be played on a chessboard of size N*M. That is, it has N rows, each of which has M squares. At the beginning of the game, a coin is on square (1, 1), which corresponds to the top-left corner, and every other square is empty. At every step, Yoda and Chef have to move the coin on the chessboard. The player who cannot make a move loses. Chef makes the first move. They can't move the coin to a square where it had been placed sometime before in the game, and they can't move outside chessboard.

In this game, there are two different sets of rules according to which the game can be played:

-from (x, y) player can move coin to (x+1, y), (x-1, y), (x, y+1), (x, y-1) in his turn, if they are valid squares.

-from (x, y) player can move coin to (x+1, y+1), (x-1, y-1), (x-1, y+1), (x+1, y-1) in his turn, if they are valid squares.

Before every game, the Power of the kitchen chooses one among the two sets of rules with equal probability of 0.5, and the game will be played according to those rules. Chef and Yoda are very wise, therefore they play optimally. You have to calculate the probability that Yoda will teach Chef.

-----Input-----

Input begins with an integer T, the number of test cases

Each test case begins with 4 integers N, M, P, K.

-----Output-----

For each test case, output a line containing the answer for task. The output must have an absolute error at most 0.000001 (10-6).

-----Constraints and Subtasks-----
-  1 ≤ T ≤ 50
-  1 ≤ K

Subtask 1 : 10 points

-  2 ≤ N, M ≤ 5
-  0 ≤ P ≤ K ≤ 5

Subtusk 2 : 10 points
-  2 ≤ N, M ≤ 10
-  0 ≤ P ≤ K ≤ 10^3

Subtusk 3 : 20 points
-  2 ≤ N, M ≤ 100
-  0 ≤ P ≤ K ≤ 10^3

Subtusk 4 : 60 points
-  2 ≤ N, M ≤ 100
-  0 ≤ P ≤ K ≤ 10^6...

# cook your dish here
import math

dp = []
dp.append(0)
for i in range(1,1000005):
	dp.append(math.log(i) + dp[i-1])

t = int(input())
for i in range(t):
	n,m,p,k = input().split()
	n = int(n)
	m = int(m)
	p = int(p)
	k = int(k)

	if p==0 or (n%2==0 and m%2==0):
		ans = 1.0
		print(ans)
	elif n%2==1 and m%2==1:
		ans=0.0
		print(ans)
	else:
		P = 0
		kln2 = k*math.log(2)
		for i in range(p, k+1):
			lnPi = dp[k] - dp[i] - dp[k-i] - kln2
			Pi = pow(math.e, lnPi)
			P += Pi
		print(P)


Solve in Python:
Chef has been working in a restaurant which has  N  floors. He wants to minimize the time it takes him to go from the N-th floor to ground floor. He can either take the elevator or the stairs.
The stairs are at an angle of 45 degrees and Chef's velocity is V1 m/s when taking the stairs down. The elevator on the other hand moves with a velocity V2 m/s. Whenever an elevator is called, it always starts from ground floor and goes to N-th floor where it collects Chef (collecting takes no time), it then makes its way down to the ground floor with Chef in it.

The elevator cross a total distance equal to N meters when going from N-th floor to ground floor or vice versa, while the length of the stairs is sqrt(2) * N because the stairs is at angle 45 degrees.

Chef has enlisted your help to decide whether he should use stairs or the elevator to minimize his travel time. Can you help him out?

-----Input-----
The first line contains a single integer T, the number of test cases. Each test case is described by a single line containing three space-separated integers N, V1, V2.

-----Output-----
For each test case, output a single line with string Elevator or Stairs, denoting the answer to the problem.

-----Constraints-----
- 1 ≤ T ≤  1000
- 1 ≤ N, V1, V2 ≤  100

-----Example-----
Input:
3
5 10 15
2 10 14
7 14 10

Output:
Elevator
Stairs
Stairs

import math
try:
 t = int(input())
 for i in range(t):
  x = list(map(int,input().split()))
  y = x[2]/(math.sqrt(2)*x[1])
  if y>1:
   print("Elevator")
  else:
   print("Stairs")
except:
 pass


Solve in Python:
Chef has bought N robots to transport cakes for a large community wedding. He has assigned unique indices, from 1 to N, to each of them. How it will happen?
Chef arranges the N robots in a row, in the (increasing) order of their indices. Then, he chooses the first M robots and moves them to the end of the queue. Now, Chef goes to the robot at the first position in the row and hands it one cake. He then notes this robot's index (say k) in his notebook, and goes to the kth position in the row. If the robot at this position does not have a cake, he give him one cake, notes his index in his notebook, and continues the same process. If a robot visited by Chef already has a cake with it, then he stops moving and the cake assignment process is stopped.
Chef will be satisfied if all robots have a cake in the end. In order to prepare the kitchen staff for Chef's wrath (or happiness :) ), you must find out if he will be satisfied or not? If not, you have to find out how much robots have a cake, so that the kitchen staff can prepare themselves accordingly.

-----Input-----
- The first line of input contains a single integer T denoting the number of test cases.
- The single line of each test cases contains two space separated integers N and M.

-----Output-----
For each of the T test cases, output a single line:

- If all N robots have a cake, output "Yes" (without quotes).
- Otherwise, output "No" (without quotes) followed by a space and the number of robots which have a cake.

-----Constraints and Subtasks-----
- 1 ≤ T ≤ 10
- 0 ≤ M < NSubtask 1: 25 points
- 1 ≤ N ≤ 10^5Subtask 3: 75 points
- 1 ≤ N ≤ 10^9

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

Output:
No 1
Yes
No 2

-----Explanation-----
In test case 1, we have two robots indexed 1 and 2. They are arranged as (1 2). Chef goes to the first robot, gives him a cake, and moves to position 1. In the next step, he sees that robot at this position already has a has cake. So Chef stops moving, and our answer is "No 1".
In test case 2, we again have two robots indexed 1 and 2....

def gcd(n,m):
 if m==0:
  return n
 else:
  return gcd(m,n%m)
t=int(input())
while t:
 par=[int(i) for i in input().split(' ')]
 n,m=par[0],par[1]
 g_div=gcd(n,m)
 if g_div==1:
  print("Yes")
 else:
  print("No "+str(int(n/g_div)))
 t=t-1


Solve in Python:
Chef has come to a 2 dimensional garden in which there are N points. Each point has coordinates (x, y), where x can either be 1 or 2 or 3. Chef will now choose every triplet of these N points and make a triangle from it. You need to tell the sum of areas of all the triangles the Chef makes.
Note that some of the triplets might not form proper triangles, and would end up as a line or a point (ie. degenerate), but that is fine because their area will be zero.

-----Input-----
- The first line contains a single integer T, the number of test cases. The description of each testcase follows.
- The first line of each test case contains an integer N denoting the number of points on the plane.
- The next N lines contain 2 space separated integers x and y denoting the coordinates of the points.

-----Output-----
For each test case, output a single line containing the answer. Your answer will be considered correct if the absolute error is less than or equal to 10-2.

-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ N ≤ 2000
- 1 ≤ x ≤ 3
- 1 ≤ y ≤106
- All (x, y) pairs are distinct

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

Output:
1.0
2.0

-----Explanation:-----
Test Case 1: There is only one triangle which has non-zero area, and it's area is 1, hence the output.
Test Case 2: Let the points be A(1,1), B(2,2), C(2,1), D(3,3). There are 3 non degenerate triangles possible.

-  area ABC = 0.5
-  area BCD = 0.5
-  area ACD = 1
Total area = 2

# cook your dish here
# Author: Dancing Monkey | Created: 09.DEC.2018

import bisect
for _ in range(int(input())):
 n = int(input())
 x1 , x2, x3 = [], [], []
 for i in range(n):
  x, y = list(map(int, input().split()))

  if x == 1: x1.append(y)
  if x == 2: x2.append(y)
  if x == 3: x3.append(y)

 x1.sort()
 x2.sort()
 x3.sort()

 y1, y2, y3 = len(x1), len(x2), len(x3)
 area = 0
 for i in range(y1):
  for j in range(i+1, y1):
   area += abs(x1[i] - x1[j])*(y2 + (2*y3))

 for i in range(y3):
  for j in range(i+1, y3):
   area += abs(x3[i] - x3[j])*(y2 + (2*y1))

 for i in range(y2):
  for j in range(i+1, y2):
   area += abs(x2[i] - x2[j])*(y1 + y3)

 area /= 2

 s1 = [0]
 for i in range(y2): s1.append(s1[-1] + x2[i])
 # print(s1)
 s2 = [0]
 for i in range(y2):s2.append(s2[-1] + x2[y2 - 1 - i])
 # print(s2)

 for i in x1:
  for j in x3:
   p1 = (i + j) / 2
   p = bisect.bisect_left(x2, p1)
   # print('p', p)
   l = p
   h = y2 - l
   # print(l, h)

   area += p1*(l) - s1[l]
   # print('dfg', area)
   area += s2[h] - p1*(h)

 print(format(area, 'f'))
 # print()


Solve in Python:
Chef has created a special dividing machine that supports the below given operations on an array of positive integers.
There are two operations that Chef implemented on the machine.
Type 0 Operation

Update(L,R):
	for i = L to R:
		a[i] = a[i] / LeastPrimeDivisor(a[i])

Type 1 Operation

Get(L,R):
	result = 1
	for i = L to R:
		result = max(result, LeastPrimeDivisor(a[i]))
	return result;

The function LeastPrimeDivisor(x) finds the smallest prime divisor of a number. If the number does not have any prime divisors, then it returns 1.
Chef has provided you an array of size N, on which you have to apply M operations using the special machine. Each operation will be one of the above given two types. Your task is to implement the special dividing machine operations designed by Chef. Chef finds this task quite easy using his machine, do you too?

-----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 two space-separated integers N, M, denoting the size of array A and the number of queries correspondingly.

The second line of each test case contains N space-separated integers A1, A2, ..., AN denoting the initial array for dividing machine.
Each of following M lines contain three space-separated integers  type, L, R - the type of operation (0 - Update operation, 1 - Get operation), and the arguments of function, respectively

-----Output-----
For each test case, output answer of each query of type 1 (Get query) separated by space. Each test case from the same file should start from the new line.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ Ai ≤ 106
- 1 ≤ L ≤ R ≤ N
- 0 ≤ type ≤ 1
-  Sum of M over all test cases in a single test file does not exceed 106

-----Subtasks-----
Subtask #1: (10 points)
- 1 ≤ N, M ≤ 103

Subtask #2: (25 points)
- 1 ≤ N, M ≤ 105
-  Ai is a prime number.

Subtask #3: (65 points)
- 1 ≤ N, M ≤ 105

-----Example-----
Input:
2
6 7
2 5 8 10 3 44
1 2 6
0 2 3
1 2 6
0 4...

import math
n=1001
a=[True]*n
l=[]
for i in range(2,33):
 if(a[i]):
  for j in range(i*i,n,i):
   a[j]=False
for pr in range(2,1001):
 if(a[pr]):
  l.append(pr)
t=int(input())
for j in range(t):
 n,m=list(map(int,input().strip().split()))
 arr=[int(num) for num in input().strip().split()]
 Matrix =[]
 index=[0]*100000
 factors=[0]*100000
 ans=''
 for r in range(len(arr)):
  li=[]
  for val in l:
   while((arr[r]%val)==0):
    arr[r]=arr[r]/val
    li.append(val)
    factors[r]+=1
  if(arr[r]!=1):
   li.append(arr[r])
   arr[r]=1
   factors[r]+=1
  Matrix.append(li)
 for k in range(m):
  opr=[int(o) for o in input().strip().split()]
  L=opr[1]
  R=opr[2]
  if(opr[0]==0):
   for ran in range(L-1,R):
    if(index[ran]<factors[ran]):
     index[ran]+=1
  else:
   result=1
   for ran in range(L-1,R):
    if(index[ran]<factors[ran]):
     result=max(result,Matrix[ran][index[ran]])
   ans+=str(result)
   ans+=' '
 print(ans[:-1])


Solve in Python:
Chef has decided to retire and settle near a peaceful beach. He had always been interested in literature & linguistics. Now when he has leisure time, he plans to read a lot of novels and understand structure of languages. Today he has decided to learn a difficult language called Smeagolese. Smeagolese is an exotic  language whose alphabet is lowercase and uppercase roman letters. Also every word on this alphabet is a meaningful word in Smeagolese. Chef, we all know is a fierce learner - he has given himself a tough exercise. He has taken a word and wants to determine all possible anagrams of the word which mean something in Smeagolese.  Can you help him ?

-----Input-----
Input begins with a single integer T, denoting the number of test cases. After that T lines follow each containing a single string S - the word chef has chosen. You can assume that 1 <= T <= 500 and 1 <= |S| <= 500. You can also assume that no character repeats more than 10 times in the string.

-----Output-----
Output one line per test case - the number of different words that are anagrams of the word that chef has chosen. As answer can get huge, print it modulo 10^9 + 7

-----Example-----
Input:
4
ab
aa
aA
AAbaz

Output:
2
1
2
60
Description:
In first case "ab" & "ba" are two different words. In third case, note that A & a are different alphabets and hence "Aa" & "aA" are different words.

e=10**9+7

def fact(n):
 ans=1
 for i in range(2,n+1):
  ans=(ans*i)%e
 return ans

t=int(input())
for _ in range(t):
 s=input()
 n=len(s)
 d={}
 for i in s:
  try:
   d[i]+=1
  except:
   d[i]=1
 x=fact(n)
 for i in list(d.values()):
  y= fact(i)
  y = pow(y,e-2,e)
  x=(x*y)%e
 print(x)


Solve in Python:
Chef has decided to start home delivery from his restaurant. He hopes that he will get a lot of orders for delivery, however there is a concern. He doesn't have enough work forces for all the deliveries.  For this he has came up with an idea - he will group together all those orders which have to be delivered in nearby areas.

In particular, he has identified certain bidirectional roads which he calls as fast roads. They are short and usually traffic free, so the fast travel is possible along these roads. His plan is that he will send orders to locations A and B together if and only if it is possible to travel between A and B using only fast roads. Your task is, given the configuration of fast roads, identify which orders are to be sent together.

-----Input-----
First line of input contains an integer T, the number of test cases. Then T test cases follow. First line of each test case contains two space separated integers N and M, denoting number of locations and the number of fast roads. Then M lines follow each containing two space separated integers A and B, denoting that there is a fast road between locations A and B. Assume that locations are indexed by numbers from 0 to N-1.

Next line contains an integer Q denoting the number of queries. Each of the next Q lines contain two integers X and Y. For each query you have to find out if orders meant for locations X and Y are to be sent together or not.

Note that there might be multiple fast roads between same pair of locations, also there might be a fast road that links a location to itself.

-----Output-----
For each test case print Q lines - one for each query. Output "YO" if the orders are to be
delivered together and "NO" otherwise (quotes for clarity).

-----Constraints-----
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ M ≤ 1000
0 ≤ A, B, X, Y ≤ N-1
1 ≤ Q ≤ 3000

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

Output:
YO
NO
YO

-----Warning!-----
There are large input and output files in this problem. Make sure you use fast enough I/O methods.

from collections import defaultdict

class Graph:

    def __init__(self,vertices):

        self.graph = defaultdict(list)
        self.DFSList = defaultdict(list)

        for i in range(0,vertices):
        	self.graph[i]=[]
        	self.DFSList[i]=[]

    def addEdge(self,u,v):
        if u!=v:
        	self.graph[u].append(v)
        	self.graph[v].append(u)

    def DFSUtil(self,v,visited,n):

        visited[v]= True
        self.DFSList[n].append(v)

        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited,n)

    def DFS(self,v):

        visited = [False]*(len(self.graph))
        self.DFSUtil(v,visited,v)

t=int(input())
for z in range(0,t):
	n,m=map(int,input().split())
	g = Graph(n)

	for M in range(0, m):
		u,v = map(int,input().split())
		g.addEdge(u,v)

	for i in range(0,n):
		g.DFS(i)

	q = int(input())
	for Q in range(0, q):
		u,v = map(int,input().split())
		if v in g.DFSList[u]:
			print("YO")
		else:
			print("NO")


Solve in Python:
Chef has found a new game and now he wants you to help him to get as much points as possible.
Rules of the game: There are different types of game pieces -  geometric shapes composed of some amount of square blocks. In the picture below you can see all the types of figures and enumeration.
The playing field is 10 cells width and 10 cells height. On each step of the game you are given exactly three game pieces. After that you need to put each of them to the game field such that after your move no two figures on the field are overlapped(you cannot rotate figures). If your move results in one or more horizontal or/and vertical lines of 10 units without gaps, those lines disappear. Notice that you put these three figures one by one and if you place the first figure and there are some lines ready to disappear, then they will disappear and only after that you place other figures.
The game ends when you can't put no more figures on the game field.

-----Input-----
Each line of input contains three integers figure1, figure2 , figure3 denoting the type of the figures appeared on this step. If the game has ended - in the next line of input will be "-1 -1 -1".

-----Interaction with the judge-----
In each step you should read from the standard input all information about figures that appear in this step. After receiving this input, you should print one line containing nine space-separated parameters id1, r1, c1, id2, r2, c2, id3, r3 and c3. Integers {id1, id2, id3} is the permutation of {1, 2, 3} and denote the order in which you will put these three figures. Integer ri denotes the number of the row of the lowest block of idith figure after you put it and ci denotes the number of the column of the leftmost block of idith figure after you put it. The rows are numbered from 1 to 10 from top to bottom and columns are numbered from 1 to 10 from left to right. Remember to flush the output after every line you print.
To finish the game(if you don't know where to put figures or it's impossible to put some figures) you...


Solve in Python:
Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams.

Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry.

However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group.

Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid.

-----Input:-----
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test contains two space-separated integers N and K. The next line contains N space-separated integers W1, W2, ..., WN.

-----Output:-----
For each test case, output the maximum possible difference between the weights carried by both in grams.

-----Constraints:-----
- 1 ≤ T ≤ 100
- 1 ≤ K < N ≤ 100
- 1 ≤ Wi ≤ 100000 (105)

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

Output:
17
2

-----Explanation:-----
Case #1: The optimal way is that Chef gives his son K=2 items with weights 2 and 4. Chef carries the rest of the items himself. Thus the difference is: (8+5+10) − (4+2) = 23 − 6 = 17.

Case #2: Chef gives his son 3 items and he carries 5 items himself.

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

 l = list(map(int,input().split()))
 l.sort()
 a = max(sum(l[k:])-sum(l[:k]),sum(l[:k])-sum(l[k:]))
 l.sort(reverse=True)
 b = max(sum(l[k:])-sum(l[:k]),sum(l[:k])-sum(l[k:]))
 print(max(a,b))


Solve in Python:
Chef has invited Alice for his birthday party. Now, Alice is thinking about what to give Chef as a present. She should obviously choose a sequence ― what could possibly be a better birthday gift than a sequence!
After some thinking, Alice chose a sequence of integers $A_1, A_2, \ldots, A_N$. However, she does not want to simply give this sequence to Chef. Instead, she decided to give Chef a sequence $B_1, B_2, \ldots, B_N$, where $B_i = \bigvee_{j=1}^i A_j$ for each valid $i$ and $\bigvee$ denotes the bitwise OR operation. Chef can try to generate a sequence $A$ from $B$, but there could be more than one such possible sequence.
Now, Alice is wondering how many sequences $A$ correspond to the given sequence $B$. Since this number could be very large, compute it modulo $10^9 + 7$. Note that it is not guaranteed that the given sequence $B$ was generated from some 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 a single integer $N$.
- The second line contains $N$ space-separated integers $B_1, B_2, \ldots, B_N$.

-----Output-----
For each test case, print a single line containing one integer ― the number of possible sequences $A$ modulo $10^9 + 7$.

-----Constraints-----
- $1 \le T \le 25$
- $1 \le N \le 5 \cdot 10^4$
- $0 \le B_i < 2^{30}$ for each valid $i$

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

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

-----Explanation-----
Example case 1: There are two possible options for $A$: $(2, 1)$ and $(2, 3)$.

m=pow(10,9)+7
for _ in range(int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 t=1
 for i in range(n-1):
  if(l[i]<=l[i+1] and l[i]&l[i+1]==l[i]):
   y=bin(l[i]).count('1')
   t=(t*pow(2,y,m))%m
  else:
   t=0
   break
 print(t%m)


Solve in Python:
Chef has just finished the construction of his new garden. He has sown the garden with patches of the most beautiful carpet grass he could find. He has filled it with patches of different color and now he wants to evaluate how elegant his garden is.
Chef's garden looks like a rectangular grid of cells with N rows and M columns. So there are N x M cells in total.	In each cell Chef planted grass of some color.
The elegance of the garden is defined by the number of squares, composed of at least four  garden cells, with edges parallel to the sides of the garden, that have four corner cells of the same color.
Given the description of Chef's garden, calculate how many such squares exist.
Input format
The first line contains the number T, the number of test cases. In the following lines,	T test cases follow (without any newlines between them.)
The first line of each test case contains N and M, separated by a single space.
Each of the next N lines contains M characters without any spaces between them, and without any leading or trailing spaces.
Each character describes the color of the corresponding cell in the garden and belongs to the set of lowercase and uppercase lettes of the English alphabet.
One letter in lowercase and uppercase describes different colors.
Output format
For each test case, print the number of squares that conform to the definition in the	problem statement.
Constraints
1 ≤ T ≤ 50

1 ≤ N, M ≤ 50

Sample input
3
2 2
aa
aA
3 3
aba
bab
aba
4 4
aabb
aabb
bbaa
bbaa

Sample output
0
1
4

Explanation
In the first case the only avaliable square does not conform to the definition in the problem statement because 'a' and 'A' describes different colors.
In the second case, you can select the 4 a's at the corners of the garden.
In the third case, you can only make four squares, from the four 2x2 segments	that are of the same color.

# cook your dish here
import sys
import math

def main(grid):
    ans=0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            first_point=grid[i][j]
            for k in range(j+1,len(grid[0])):
                second_point=grid[i][k]
                if first_point==second_point:
                    dist=k-j
                    if i+dist<len(grid):
                        thrid_point=grid[i+dist][j]
                        fourth_point=grid[i+dist][k]
                        if second_point==thrid_point and second_point==fourth_point:
                            ans+=1
    return ans

test=int(input())
for _ in range(test):
    n,m=input().split()
    n=int(n)
    arr=[]
    for b in range(n):
        arr.append(list(input()))
    print(main(arr))


Solve in Python:
Chef has just found a recipe book, where every dish consists of exactly four ingredients.
He is going to choose some two dishes and prepare them for dinner.
Of course, he likes diversity and wants to know whether the two dishes are similar.
Two dishes are called similar if at least half of their ingredients are the same.
In other words, at least two of four ingredients of the first dish should also be present in the second dish.
The order of ingredients doesn't matter.
Your task is to examine T pairs of dishes.
For each pair, check if the two dishes are similar and print "similar" or "dissimilar" accordingly.

-----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 four distinct strings, denoting ingredients needed for the first dish.
Each ingredient is represented by a string of length between 2 and 10 inclusive, consisting of lowercase English letters.

The second line of each test case describes the second dish in the same format.

-----Output-----
For each test case, output a single line containing the answer — "similar" if at least half of the ingredients are same, and "dissimilar" otherwise (without the quotes).

-----Constraints-----
- 1 ≤ T ≤ 200
- The length of each string will be between 2 and 10 inclusive.

-----Example-----
Input:
5
eggs sugar flour salt
sugar eggs milk flour
aa ab ac ad
ac ad ae af
cookies sugar grass lemon
lemon meat chili wood
one two three four
one two three four
gibberish jibberish lalalalala popopopopo
jibberisz gibberisz popopopopu lalalalalu

Output:
similar
similar
dissimilar
similar
dissimilar

-----Explanation-----
Test case 1. The first dish consists of ingredients: eggs, sugar, flour, salt, while the second dish consists of: sugar, eggs, milk, flour. Three of four ingredients are present in both dishes (eggs, sugar, flour) so the two dishes are similar.
Test case 2. This example shows that strings in the input don't necessarily represent...

n=int(input())
for i in range(0,n):
 l1=list(input().split())
 l2=list(input().split())
 l3=[]
 for item in l1:
  if(item in l2):
   l3.append(item)

 if(len(l3)>=2):
  print("similar")
 else:
  print("dissimilar")


Solve in Python:
Chef has just learned a new data structure - Fenwick tree. This data structure holds information about array of N elements and can process two types of operations:

- Add some value to ith element of the array
- Calculate sum of all elements on any prefix of the array

Both operations take O(log N) time. This data structure is also well known for its low memory usage. To be more precise, it needs exactly the same amount of memory as that of array.

Given some array A, first we build data structure in some other array T. Ti stores the sum of the elements Astart, Astart + 1, ..., Ai. Index start is calculated with formula start = Fdown(i) = (i & (i + 1)). Here "&" denotes bitwise AND operation.
So, in order to find a sum of elements A0, A1, ..., AL you start with index L and calculate sum of TL + TFdown(L)-1 + TFdown(Fdown(L)-1)-1 + ... + TFdown(Fdown(...(Fdown(L)-1)-1)-1. Usually it is performed with cycle that goes from L down to 0 with function Fdown and sums some elements from T. Chef wants to verify that the time complexity to calculate sum of A0, A1, A2, ..., AL is O(log L). In order to do so, he wonders how many times he has to access array T to calculate this sum. Help him to find this out.
Since Chef works with really big indices. The value of L can be very large and is provided to you in binary representation as concatenation of strings L1, L2 repeated N times and string L3.

-----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 three non-empty strings L1, L2, L3 and an integer N. Strings will contain only characters 0 and 1. To obtain binary representation of index L concatenate L1 with L2 repeated N times and with L3. You are guaranteed that the index will be positive.

-----Output-----
For each test case, output a single line containing number of times Fenwick tree data structure will access array T in order to compute sum of A0, A1, A2, ..., AL.

-----Constraints-----
-...

t=int(input())
count=[]

for i in range(t) :
 s = input()
 a,b,c,n = s.split()
 n=int(n)
 d = int(a+b*n+c,2)
 count.append(0)
 while(d>0) :
  d=(d&(d+1))-1
  count[i]+=1

for i in range(t) :
 print(count[i])


Solve in Python:
Chef has just started Programming, he is in first year of Engineering. Chef is reading about Relational Operators.

Relational Operators are operators which check relatioship between two values. Given two numerical values A and B you need to help chef in finding the relationship between them that is,

- First one is greater than second or,
- First one is less than second or,
- First and second one are equal.

-----Input-----
First line contains an integer T, which denotes the number of testcases. Each of the T lines contain two integers A and B.

-----Output-----
For each line of input produce one line of output. This line contains any one of the relational operators

'<' , '>' , '='.

-----Constraints-----

- 1 ≤ T ≤ 10000
- 1 ≤ A, B ≤ 1000000001

-----Example-----
Input:
3
10 20
20 10
10 10

Output:
<
>
=

-----Explanation-----
Example case 1. In this example 1 as 10 is lesser than 20.

# cook your dish here
n=int(input())
for i in range(n):
    x,y=map(int,input().split())
    if x==y:print("=")
    else:
        a=">" if x>y else "<"
        print(a)


Solve in Python:
Chef has many friends, but his best friend is Hemant. They both love to watch anime.
In fact, their weekends are meant for that only. Also, Hemant is highly into games, of which Chef is unaware. Hemant once gave a game to Chef and asked him to determine the winner of the game. Since the Chef is busy, and you are also his friend, he asked you to help him.
The Game is played between two players, $A$ and $B$. There are $N$ marbles. $A$ and $B$ plays alternately, and $A$ goes first. Each player can choose $1$ marble or $even$ number of marbles in his turn. The player who is not able to choose any marbles loses the game.

-----Input:-----
- The first line consists of a single integer $T$ denoting the number of test cases.
- The Second line contains an integers $N$, denoting the number of marbles.

-----Output:-----
For each test case, print the name of the player who loses the game.

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

-----Sample Input:-----
3
1
3
7

-----Sample Output:-----
B
A
B

for _ in range(int(input())):
    n=int(input())
    if n%2==0:
        print("B")
    else:
        if n==1:
            print("B")
        elif n==3:
            print("A")
        else:
            print("B")


Solve in Python:
Chef has provided with a sequence of integers of length $N$ arranged in an unsorted fashion.
The elements of the sequence are ordered as ${A1,A2,A3.....A'N}$
The task of the chef is to identify the highest and lowest value among the given sequence. It is assured that the sequence given contains the highest and the lowest value always
Please help chef in finding the desired value.

-----Input:-----
- First line will contain $N$, number of elements in the sequence.
- Next line contains  $N$ integers of the sequence  .

-----Output:-----
Print the HIGHEST and  LOWEST value of the sequence respectively.

-----Constraints-----
- $1 \leq N \leq 100$
- $2 \leq  {A1,A2,A3.....A'N}  \leq 10^4$

-----Sample Input:-----
5
3 2 7 9 4

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

-----EXPLANATION:-----
This list is :
[3,2,7,9,4]  so the highest value is 9 and lowest is 2 respectively.

# cook your dish here
try:
    n=int(input())
    num = list(map(int, input().split()[:n]))
    m1=max(num)
    m2=min(num)
    print(m1,m2)

except:
    pass


Solve in Python:
Chef has recently been playing a lot of chess in preparation for the ICCT (International Chef Chess Tournament).
Since putting in long hours is not an easy task, Chef's mind wanders elsewhere. He starts counting the number of squares with odd side length on his chessboard..
However, Chef is not satisfied. He wants to know the number of squares of odd side length on a generic $N*N$ chessboard.

-----Input:-----
- The first line will contain a single integer $T$, the number of test cases.
- The next $T$ lines will have a single integer $N$, the size of the chess board.

-----Output:-----
For each test case, print a integer denoting the number of squares with odd length.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 1000$

-----Sample Input:-----
2
3
8

-----Sample Output:-----
10
120

# cook your dish here
for _ in range(int(input())):
 n=int(input())
 count1=0
 for i in range(1,n+1,2):
  k=n-i+1
  count1+=k*k
 print(count1)


Solve in Python:
Chef has recently learned about number bases and is becoming fascinated.
Chef learned that for bases greater than ten, new digit symbols need to be introduced, and that the convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are 0123456789ABCDEF. Chef thought that this is unsustainable; the English alphabet only has 26 letters, so this scheme can only work up to base 36. But this is no problem for Chef, because Chef is very creative and can just invent new digit symbols when she needs them. (Chef is very creative.)
Chef also noticed that in base two, all positive integers start with the digit 1! However, this is the only base where this is true. So naturally, Chef wonders: Given some integer N, how many bases b are there such that the base-b representation of N starts with a 1?

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single integer N (in base ten).

-----Output-----
For each test case, output a single line containing the number of bases b, or INFINITY if there are an infinite number of them.

-----Constraints-----

-----Subtasks-----Subtask #1 (16 points):
- 1 ≤ T ≤ 103
- 0 ≤ N < 103
Subtask #2 (24 points):
- 1 ≤ T ≤ 103
- 0 ≤ N < 106
Subtask #3 (28 points):
- 1 ≤ T ≤ 103
- 0 ≤ N < 1012
Subtask #4 (32 points):
- 1 ≤ T ≤ 105
- 0 ≤ N < 1012

-----Example-----
Input:4
6
9
11
24

Output:4
7
8
14

-----Explanation-----
In the first test case, 6 has a leading digit 1 in bases 2, 4, 5 and 6: 610 = 1102 = 124 = 115 = 106.

# cook your dish here
n=int(input())
def dig(num,b):
    c=0
    mul=b
    while(True):
        if(num//mul!=0):
            mul=mul*b
            c+=1
        else:
            break
    return c
for q in range(n):
    num=int(input())
    res=0
    for i in range(3,num):
        po=dig(num,i)
        if((2*(i**po)-1)>=num):
            res+=1
    if(num==2):
        res=res+1
    if(num>2):
        res=res+2
    if(num==1):
        print("INFINITY")
    else:
        print(res)


Solve in Python:
Chef has some numbers. His girlfriend Chefina feels good when chef gives her a particular pattern number also called as Armstrong number.
Armstrong number is a number whose sum of its all individual digit raise to the power of the number of digit in that number is equal to that number itself
eg.. 153 = 1^3 + 5^3 + 3^3 (153 is an Armstrong number)
1634 = 1^4 + 6^4 + 3^4 + 4^4 (1634 is an Armstrong number)
As a love guru of chef you have to help chef to find Armstrong numbers Among the numbers which chef has initially so that Chefina feels good

-----Input:-----
First line will contain a positive Integer $T$ which is the number of testcases
Next $T$ lines follows an Integer $N$.

-----Output:-----
For Every n You have to print "FEELS GOOD" without qoutes if it is an armstrong number otherwise Print "FEELS BAD" without quotes

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

-----Sample Input:-----
3
153
11
1634

-----Sample Output:-----
FEELS GOOD
FEELS BAD
FEELS GOOD

-----EXPLANATION:-----
For test case 1 --> 153 = 1^3 + 5^3 + 3^3 (153 is an armstrong number)

# cook your dish her
for _ in range(int(input())):
    num = int(input())
    s = 0
    temp = num
    while temp > 0:
       digit = temp % 10
       s += digit ** len(str(num))
       temp //= 10

    if num == s:
       print("FEELS GOOD")
    else:
       print("FEELS BAD")


Solve in Python:
Chef has the string s of length n consisted of digits 4 and 7.
The string s is called balanced
if there exits such integer x (1 ≤ x ≤ n) that the number of digits 4 in substring s[1; x) is equal to the number of digits 7 in substring s(x; n],
where s[1; x) is the substring from the 1st digit to (x-1)th digit of s, and s(x; n] is the substring from the (x+1)th digit to nth digit of s.
For example, s = 747474 is a balanced string, because s[1; 4) = 747 has one 4 and s(4; 6] = 74 has one 7.
Note that x can be 1 or n and s[1; 1) and s(n; n] denote an empty string.

In one turn Chef can choose any pair of consecutive digits and swap them.
Find for Chef the total number of different balanced string that can be obtained from string s using any (even 0) number of turns.
Print the result modulo 1000000007.

-----Input-----

The first line of the input contains one integer T, the number of test cases.
Then T lines follow, each of which contains string s for the corresponding test.

-----Output-----
T lines, each of which contains single integer - the answer for the corresponding test modulo 109+7.

-----Constraints-----

1 ≤ T ≤ 10

1 ≤ n ≤ 5000

-----Example-----
Input:
2
47
4477

Output:
1
4

from math import factorial
def Ncr(n,r):
    if r<0:return 0
    return factorial(n)/(factorial(n-r)*factorial(r))
def solve(m,n):
    modulo=10**9+7
    if m==n:
        return (Ncr(2*n-1,n-1)+Ncr(2*n-2,n-2))%modulo
    elif m>n:
        return (Ncr(m+n,n)-Ncr(m+n-2,n-1))%modulo
    else:
        return (Ncr(m+n,m)-Ncr(m+n-2,m-1))%modulo

t=int(input())
for i in range(t):
    inp=list(map(int,input()))
    m=inp.count(4)
    n=inp.count(7)
    print(solve(m,n))


Solve in Python:
Chef has three baskets and two of them have multiple balls(Natural numbers written on them). The first basket has N balls, the second basket has M balls and the third basket is empty. Chef starts choosing all the unique balls(only occurring once in both the baskets) and puts into the third basket and throw the repetitive ones. Print numbers on the balls of the third basket in ascending order.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains three lines of input.
- First-line has two integers $N, M$.
- Second-line with N space-separated numbers.
- Third-line with M space-separated numbers.

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

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

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

-----Sample Output:-----
1 5 6

t = int(input())
for i in range(t):
    n, m = map(int, input().split())
    arr1 = list(map(int, input().split()))
    arr2 = list(map(int, input().split()))
    hmap = {}
    for i in range(n):
        if arr1[i] in hmap:
            hmap[arr1[i]] += 1
        else:
            hmap[arr1[i]] = 1

    for i in range(m):
        if arr2[i] in hmap:
            hmap[arr2[i]] += 1
        else:
            hmap[arr2[i]] = 1
    ans = []
    #print(hmap)
    for key in hmap:
        if hmap[key]==1:
            ans.append(key)
    ans.sort()
    for x in ans:
        print(x,end=' ')
    print()


Solve in Python:
Chef has two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. You should choose $N+M-1$ pairs, each in the form $(A_x, B_y)$, such that the sums $A_x + B_y$ are all pairwise distinct.
It is guaranteed that under the given constraints, a solution always exists. If there are multiple solutions, you may find any one.

-----Input-----
- The first line of the input contains two space-separated integers $N$ and $M$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- The third line contains $M$ space-separated integers $B_1, B_2, \ldots, B_M$.

-----Output-----
Print $N+M-1$ lines. Each of these lines should contain two space-separated integers $x$ and $y$ denoting that you chose a pair $(A_{x+1}, B_{y+1})$.

-----Constraints-----
- $1 \le N, M \le 2 \cdot 10^5$
- $|A_i| \le 10^9$ for each valid $i$
- $|B_i| \le 10^9$ for each valid $i$
- $A_1, A_2, \ldots, A_N$ are pairwise distinct
- $B_1, B_2, \ldots, B_M$ are pairwise distinct

-----Subtasks-----
Subtask #1 (25 points): $1 \le N, M \le 10^3$
Subtask #2 (75 points): original constraints

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

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

-----Explanation-----
The chosen pairs and their sums are:
- $A_3 + B_2 = 100+3 = 103$
- $A_1 + B_1 = 10+4 = 14$
- $A_2 + B_1 = 1+4 = 5$
- $A_1 + B_2 = 10+3 = 13$
Since all sums are distinct, this is a correct output.

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

l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))

a = l1.index(min(l1))
b = l2.index(max(l2))

for i in range(m):
    print(a,i)

for i in range(n):
    if a!=i:
        print(i,b)


Solve in Python:
Chef has two piles of stones with him, one has n1 stones and the other has n2 stones. Fired up by boredom, he invented a game with the two piles.

Before the start of the game Chef chooses an integer m.

In the j-th move:

-  He chooses a number xj such that 1 ≤ xj ≤ m, and removes xj stones from both the piles (this is only possible when both the piles have ≥ xj stones).
-  The number chosen must be unique over all the moves in the game. That is, for all k < j, xj ≠ xk.

The game stops when Chef is unable to make any more moves.

Chef wants to make the moves in such a way that the sum of the number of stones remaining in the two piles is minimized. Please help Chef find this.

-----Input-----
- The first line of input contains an integer T denoting the number of test cases.
- Each test case consists of 1 line with three integers — n1, n2 and m — separated by single spaces.

-----Output-----
For each test case, output a single line containing the minimum sum of the number of stones of two piles.

-----Constraints-----
Subtask 1 : (5 pts)
- 1 ≤ T ≤ 100
- 0 ≤ m ≤ 18
- 0 ≤ n1, n2 ≤ 100
Subtask 2 : (25 pts)
- 1 ≤ T ≤ 1000
- 0 ≤ m ≤ 10000
- 0 ≤ n1, n2 ≤ 10000
Subtask 3 : (70 pts)
- 1 ≤ T ≤ 105
- 0 ≤ m ≤ 109
- 0 ≤ n1, n2 ≤ 1018

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

Output:0
1
3

-----Explanation-----
Example case 1. : Remove 1 stone from each of the piles. Now 0 stones are remaining, so chef cannot remove any more stones from the piles. Hence, answer is 0+0 = 0
Example case 2. : Again, remove 1 stone from both the piles to get (0,1) stones. Now chef cannot remove any more stones from pile 1, so he stops. Hence, answer is 0+1 = 1.
Example case 3. : First remove 1 stone from both the piles to get (3,4) stones. Now, remove 2 stones from both the piles so that (1,2) stones are remaining. Now chef cannot remove any more stones owing to the condition that he cannot remove the same number of stones twice. So, the answer is 1+2 = 3.

#t=int(raw_input())
import math
t=eval(input())
while t:
 str=input()
 a,b,r=str.split()
 a=int(a)
 b=int(b)
 r=int(r)
 #print(a,b,r)
 #b=input()
 #r=input()
 t=t-1
 m=min(a,b)
 max_can_remove=(r*(r+1))/2
 ans=0
 if max_can_remove > m:
  ans=abs(a-b)
 else:
  ans=a+b-(2*max_can_remove)
 print(ans)


Solve in Python:
Chef hates unoptimized codes and people who write such codes. One fine day he decided to look through the kitchen's codebase and found a function whose pseudo-code is given here:

input: integer N, list X[1, 2, ..., N], list Y[1, 2, ..., N]

output: integer res

function:

set res = 0;
for i := 1 to N do
for j := 1 to N do
for k := 1 to N do
if (X[i] = X[j]) OR (X[j] = X[k]) OR (X[k] = X[i])
continue
else
set res = max(res, Y[i] + Y[j] + Y[k])
return res

Luckily enough this code gets triggered only if the Head Chef makes a submission. But still there is a possibility that this can crash the judge. So help Chef by writing a new function which does the same thing but is faster.

-----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 an integer N denoting the number of elements in the two lists.
- The i-th of the next N lines contains a pair of space-separated integers denoting the values of X[i] and Y[i] respectively.

-----Output-----
For each test case, output an integer corresponding to the return value of the function.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ X[i], Y[i] ≤ 108

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

Output
0
11

-----Explanation-----
Testcase 2: The maximum is attained when i = 1, j = 2 and k = 5. This leads to res being 3 + 4 + 4 = 11. This value is attained in other iterations as well, but it never exceeds this, and hence this is the answer.

# cook your dish here
for _ in range(int(input())):
 d=dict()
 ls=[]
 for i in range(int(input())):
  ls=list(map(int,input().split()))
  if ls[0] in d:
   d[ls[0]]=max(ls[1],d[ls[0]])
  else:
   d[ls[0]]=ls[1]
 # print(d)
 if len(d)<3:
  print(0)
 else:
  kd=list(d.values())
  kd.sort()
  # print(kd)
  print(kd[-1]+kd[-2]+kd[-3])


Solve in Python:
Chef is a big fan of soccer! He loves soccer so much that he even invented soccer for dogs! Here are the rules of soccer for dogs:
- N$N$ dogs (numbered 1$1$ through N$N$) stand in a line in such a way that for each valid i$i$, dogs i$i$ and i+1$i + 1$ are adjacent.
- Each dog has a skill level, which is either 1$1$ or 2$2$.
- At the beginning of the game, Chef passes a ball to dog 1$1$ (dog 1$1$ receives the ball).
- For each valid i$i$, if dog i$i$ has skill level s$s$, this dog can pass the ball to any dog with number j$j$ such that 1≤|i−j|≤s$1 \le |i-j| \le s$.
- Each dog (including dog 1$1$) may receive the ball at most once.
- Whenever a dog receives the ball, it must either pass it to another dog or finish the game by scoring a goal.
While the dogs were playing, Chef also created a game for developers. He defined the result of a game of soccer for dogs as the sequence of dogs which received the ball in the order in which they received it. The last dog in the sequence is the dog that decided to score a goal; if a dog never received the ball, it does not appear in the sequence. In the game for developers, you should find the number of possible results of soccer for dogs.
Find this number of possible results modulo 109+7$10^9 + 7$. Two results of soccer for dogs (sequences of dogs' numbers) are considered different if these sequences have different lengths or if there is a valid index i$i$ such that the i$i$-th dog in one sequence is different from the i$i$-th dog in the other sequence.

-----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 contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \ldots, A_N$ denoting the skill levels of the dogs.

-----Output-----
For each test case, print a single line containing one integer - the number of different results of soccer for dogs, modulo 109+7$10^9 +...


Solve in Python:
Chef is a brilliant university student that does not attend lectures because he believes that they are boring and coding is life! However, his university follows certain rules and regulations, and a student may only take an exam for a course if he has attended at least 75% of lectures for this course.
Since you are Chef's best friend, you want to help him reach the attendance he needs to take exams. Unfortunately, Chef is still focused on his code and refuses to attend more lectures, so the only option is to have some of his friends mark him as present by proxy. This trick is well-known in the university, but only few have the talent to pull it off.
In a certain course, there is exactly one lesson per day over the course of $D$ days (numbered $1$ through $D$). You are given a string $S$ with length $D$ describing the lessons Chef attended — for each valid $i$, the $i$-th character of this string is either 'A' if Chef was absent on day $i$ or 'P' if Chef was actually present on day $i$.
For each day $d$ when Chef is absent, one of Chef's friends can mark him as present by proxy on this day only if he was present (if he was really present, not just marked as present) on at least one of the previous two days, i.e. days $d-1$ and $d-2$, and on at least one of the following two days, i.e. days $d+1$ and $d+2$. However, it is impossible to mark him as present by proxy on the first two days and the last two days.
Find the minimum number of times Chef has to be marked as present by proxy so that his attendance becomes at least 75% ($0.75$). Chef's attendance is number of days when he was marked as present, either by proxy or by actually being present, divided by $D$.

-----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 $D$.
- The second line contains a single string $S$ with length $D$.

-----Output-----
For each test case, print a single line containing...

# cook your dish here
import math
for t in range(int(input())):
 d=int(input())
 s=input()
 k=math.ceil(75*d/100)
 p=s.count("P")
 if k<=p:
  print(0)
 else:
  req=k-p
  c=0
  for i in range(2,d-2):
   if s[i]=="A":
    if "P" in s[i-2:i+1] and "P" in s[i+1:i+3]:
     c+=1
   if c==req:
    print(c)
    break
  else:
   print(-1)


Solve in Python:
Chef is a private detective. He was asked to investigate a case of murder in the city of Frangton.
Chef arrived in Frangton to find out that the mafia was involved in the case. Chef spent some time watching for people that belong to the clan and was able to build a map of relationships between them. He knows that a mafia's organizational structure consists of a single Don, heading a hierarchical criminal organization. Each member reports exactly to one other member of the clan. It's obvious that there are no cycles in the reporting system of the mafia.
There are N people in the clan, for simplicity indexed from 1 to N, and Chef knows who each of them report to. Member i reports to member Ri.
Now, Chef needs to identfy all potential killers to continue his investigation. Having considerable knowledge about the mafia's activities, Chef knows that the killer must be a minor criminal, that is, one of the members who nobody reports to. Please find the list of potential killers for Chef. Since Don reports to nobody, his Ri will be equal to 0.

-----Input-----
The first line of input contains one integer N.
Next line has N space-separated integers, the ith integer denotes Ri — the person whom the ith member reports to.

-----Output-----
Output a list of space-separated integers in ascending order — the indices of potential killers.

-----Constraints-----
- 1 ≤ N ≤ 105
- 1 ≤ Ri ≤ N except for Don, whose Ri equals to 0.
- It is guaranteed that there are no cycles in the reporting structure.

-----Subtasks-----
- Subtask #1 [50 points]: N ≤ 10000
- Subtask #2 [50 points]: No additional constraints

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

Output:
4 5 6

-----Explanation-----
The reporting structure:

n=eval(input())
reports=set(map(int,input().split()))
print(' '.join(str(i) for i in range(n+1) if i not in reports))


Solve in Python:
Chef is a really nice and respectful person, in sharp contrast to his little brother, who is a very nasty and disrespectful person. Chef always sends messages to his friends in all small letters, whereas the little brother sends messages in all capital letters.
You just received a message given by a string s. You don't know whether this message is sent by Chef or his brother. Also, the communication channel through which you received the message is erroneous and hence can flip a letter from uppercase to lowercase or vice versa. However, you know that this channel can make at most K such flips.
Determine whether the message could have been sent only by Chef, only by the little brother, by both or by none.

-----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 length of the string s and the maximum number of flips that the erroneous channel can make.
- The second line contains a single string s denoting the message you received.

-----Output-----
For each test case, output a single line containing one string — "chef", "brother", "both" or "none".

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 100
- 0 ≤ K ≤ N
- s consists only of (lowercase and uppercase) English letters

-----Example-----
Input

4
5 1
frauD
5 1
FRAUD
4 4
Life
10 4
sTRAWBerry

Output

chef
brother
both
none

-----Explanation-----
Example case 1: Only one flip is possible. So it is possible that Chef sent "fraud" and the channel flipped the last character to get "frauD". However, it is not possible for the brother to have sent "FRAUD", because then it would need 4 flips. Hence the answer is "chef".
Example case 2: Only one flip is possible. So it is possible that the brother sent "FRAUD" and the channel didn't flip anything. However, it is not possible for Chef to have sent "fraud", because then it would need 5 flips. Hence the answer is "brother".
Example...

# cook your dish here
t=int(input())
for i in range(t):
 n,k=[int(i) for i in input().split()]
 s=input()
 u=0
 l=0
 for i in range(len(s)):
  if(s[i].isupper()):
   u+=1
  else:
   l+=1
 if(u<=k and l<=k):
  print("both")
 elif(l<=k and u>k):
  print("brother")
 elif(u<=k and l>k):
  print("chef")
 else:
  print("none")


Solve in Python:
Chef is a very experienced and well-known cook. He has participated in many cooking competitions in the past — so many that he does not even remember them all.
One of these competitions lasted for a certain number of days. The first day of the competition was day $S$ of the week (i.e. Monday, Tuesday etc.) and the last day was day $E$ of the week. Chef remembers that the duration of the competition (the number of days between the first and last day, inclusive) was between $L$ days and $R$ days inclusive. Is it possible to uniquely determine the exact duration of the competition? If so, what is this duration?

-----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 two space-separated strings $S$ and $E$, followed by a space and two space-separated integers $L$ and $R$.

-----Output-----
For each test case, print a single line containing:
- the string "impossible" if there is no duration consistent with all given information
- the string "many" if there is more than one possible duration
- one integer — the duration of the competition, if its duration is unique

-----Constraints-----
- $1 \le T \le 10,000$
- $1 \le L \le R \le 100$
- $S$ is one of the strings "saturday", "sunday", "monday", "tuesday", "wednesday", "thursday" or "friday"
- $E$ is one of the strings "saturday", "sunday", "monday", "tuesday", "wednesday", "thursday" or "friday"

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

-----Example Input-----
3
saturday sunday 2 4
monday wednesday 1 20
saturday sunday 3 5

-----Example Output-----
2
many
impossible

# cook your dish here
d=["saturday","sunday","monday","tuesday","wednesday","thursday","friday"]
t=int(input())
for i in range(t):
 s,e,l,r=map(str,input().split())
 l,r=int(l),int(r)
 v=(d.index(e)-d.index(s)+8)%7
 c=r+1
 for i in range(l,r+1):
  if i%7==v:
   c=i
   break
 if c>r:
  print('impossible')
 elif c+7<=r:
  print('many')
 else:
  print(c)


Solve in Python:
Chef is again playing a game with his best friend Garry. As usual, the rules of this game are extremely strange and uncommon.
First, they are given a stack of $N$ discs. Each disc has a distinct, non-negative integer written on it. The players exchange turns to make a move. Before the start of the game, they both agree upon a set of positive integers  $S$ of size $K$. It is guaranteed that S contains the integer $1$. In a move, a player can select any value $x$ from $S$ and pop exactly $x$ elements from the top of the stack. The game ends when there are no discs remaining. Chef goes first.
Scoring: For every disc a player pops, his score increases by $2^p$ where $p$ is the integer written on the disc. For example, if a player pops the discs, with integers $p_1, p_2, p_3, \dots, p_m$ written on it, during the entire course of the game, then his total score will be $2^{p_1} + 2^{p_2} + 2^{p_3} + \dots + 2^{p_m}$.
The player with higher score wins the game. Determine the winner if both the players play optimally, or if the game ends in a draw.

-----Input:-----
- First line contains $T$, the number of testcases. Then the testcases follow.
- The first line of each test case contains two space separated integers $N$ and $K$, denoting the size of the stack and the set S respectively.
- Next line contains $N$ space separated integers $A_i$ where $A_1$ is the topmost element, denoting the initial arrangement of the stack.
- The last line of each test case contains $K$ space separated integers each denoting $x_i$.

-----Output:-----
For each testcase, output "Chef" (without quotes) if Chef wins, "Garry" (without quotes) if Garry wins, otherwise "Draw" (without quotes) in a separate line.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$
- $1 \leq K \leq \min(100, N)$
- $0 \leq A_i \leq 10^9$
- $1 \leq x_i \leq N$
- $x_i \neq x_j$ for all $i \neq j$
- $A_i \neq A_j$ for all $i \neq j$
- Set $S$ contains integer $1$.
- Sum of $N$ over all test cases does not exceed $10^5$.

-----Sample...

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

 a = [-1] + a[::-1]
 mx = a.index(max(a))
 dp = [0] * (n + 1)
 for i in range(1, n + 1):
  for x in b:
   if i - x < 0: continue
   if i - x < mx <= i:
    dp[i] = 1
   else:
    dp[i] |= not dp[i - x]

 print('Chef' if dp[-1] else 'Garry')


Solve in Python:
Chef is an advocate for Go Green Initiative. Today he had n trees planted in a row outside his his restaurant. Today, the height of i-th tree is hi feet. The trees grow at a rate of mi feet per day.
Chef knows that trees will look beautiful if they form a zig-zag sequence. The trees will be said to be in Zig-zag sequence if the heights of tree first increases or decreases, then alternates between decreasing/increasing respectively. Formally, the trees will be said to in Zig-zag sequence if one of the following two conditions holds.

- h1 < h2 > h3 < h4 and so on..
- h1 >  h2 < h3 > h4 and so on..

Chef wants to know intervals of time when the heights of the trees will form a zig-zag 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 first line of each test case contains a single integer n, denoting the number of trees.
The ith of following N lines contains two space separated integers hi and mi, denoting the initial height and the growth speed for ith tree.

-----Output-----
For each test case, output an integer Q - the amount of the periods of consecutive moments of time, when the trees for a zig-zag sequence.
On the following Q lines, output the intervals of time when the trees' heights form a zig-zag sequence. For each intervals, output its' smallest and the largest instants of time. If the range is infinite, output Inf as the right bound.
The test cases are designed in such a way that the total output won't exceed 2 MB.

-----Constraints-----

- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 10
- Subtask 1 (23 points): 0 ≤ hi, mi ≤ 10
- Subtask 2 (77 points): 0 ≤ hi, mi ≤ 109
- 1 ≤ sum of n over a test cases in a single test file ≤ 5 × 105

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

Output:1
0 1
2
0 0
2 Inf
0

-----Explanation-----
Example case 1. In the first case 0 2 0 is already a zig-zag sequence, but on the 2nd second it will become 2 6 6 and will never turn back into zig-zag

import math
def calc(h, m, f) :
 l, r = 0, 1234567890
 for i in range(len(h) - 1) :
  if i & 1 : u, v = i, i + 1
  else : u, v = i + 1, i
  if f : u, v = v, u
  H, M = h[u] - h[v], m[v] - m[u]#M * t < H
  if M > 0 : r = min(int(math.floor(1.0 * H / M - 1e-12)), r)
  elif M < 0 : l = max(int(math.ceil(1.0 * H / M + 1e-12)), l)
  elif H <= 0 : return -1, -1
  if l > r : return -1, -1
 return l, r
def printerval(l, r) :
 if r == 1234567890 : r = "Inf"
 print(l, r)

def doit() :
 n, h, m, a, t, al, ar = int(input()), [], [], [], [0], [], []
 for i in range(n) :
  h += [0]; m += [0]; a += [0]
 for i in range(n) :
  h[i], m[i] = list(map(int, input().split()))
 if n == 1 :
  print(1)
  print("0 Inf")
  return
 l1, r1 = calc(h, m, 1)
 l2, r2 = calc(h, m, 0)
 if l1 != -1 and l2 != -1 :
  if l1 > l2 : l1, l2, r1, r2 = l2, l1, r2, r1
  if r1 + 1 == l2 :
   print(1)
   printerval(l1, r2)
  else :
   print(2)
   printerval(l1, r1)
   printerval(l2, r2)
 elif l1 != -1 :
  print(1)
  printerval(l1, r1)
 elif l2 != -1 :
  print(1)
  printerval(l2, r2)
 else : print(0)

for cas in range(int(input())) : doit()


Solve in Python:
Chef is baking a cake.

While baking, in each minute the size of cake doubles as compared to its previous size.

In this cake, baking of cake is directly proportional to its size.
You are given $a$, the total time taken(in minutes) to bake the whole cake.

Let cake be half baked at $k^{th}$ minute.
Your task is to find the value of $k+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 and only line of each test case contains a single integer $a$.

-----Output:-----
For each testcase , print one line, the value of $k+2$.

-----Constraints-----
- $1 \leq T \leq 8 $
- $2 \leq a \leq 10^{128}$

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

2

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

-----Explaination-----
Time was 1 min when cake was half baked by chef so answer is 1+2=3

# cook your dish here
for _ in range(int(input())):
    a=int(input())
    print(a//2+2)


Solve in Python:
Chef is frustrated in this lockown. So to overcome this he plans to travel various mountains.
He is very strange so he sets some conditions for $each$ Type 2 query(mentioned below) (i.e. $1$ $i$) :
- Let Chef has travelled till $ith$ mountain from left to right.
- He does not like to travel the mountain with the height ,of which he has travelled till now. More formally,
Let the height of peak on which he is standing is $a_{i}$ then he can only go to the peak of height $a_{j}$
which is greater than $a_{i}$ and nearest to $ith$ mountain such that there should be no other peak of same height $a_{j}$ till $a_{i}$(height of $ith$ mountain) .

-----Input format:-----
-
The first line contains an integer $T$ denoting the number of test cases.
-
The second line of  consist of a integer $N$ and $Q$ .
-
The third line contains $N$ not necessarily distinct positive integers $a_{0},a_{1}, . . .,a_{n-1}$ denoting the height of
$N$ mountains.
-
Then next $Q$ lines follows where each line consisting of $either$ of $2$ types of queries:
Type 1:  $0$ $A$ $B$ i.e. $a_{A} = B$ (where height of $Ath$ mountain will be updated to $B$)
Type 2:  $1$ $A$ i.e. you have to answer $a_k$ which is greater than $a_{A}$ and nearest to $Ath$ mountain such that there should be no other peak of same height $a_{k}$ till $a_{A}$(height of $Ath$ mountain) .

-----Output format:-----
- For every query of Type 2 there should be an integer $a_{k}$ on next  line for the updated array , If no such $a_{k}$ exists then $a_{k}$= $-1$ , as query of type 1 will have no output .

-----Constraints:-----
- $1\leq T \leq 10^2$
- $1 \leq N,Q \leq 10^4$
- $0\leq a_{i} \leq 10^6$
- $0\leq B \leq 10^6$
- $0\leq A \leq N-1$

-----Subtasks-----
-
1 Point :
$1 \leq T,N,Q \leq 10^2$
$0\leq B,a_{i} \leq 10^2$
-
99 Points : Orginal   Constraints

-----Example:-----

-----Input:-----
1
10 5
1 3 5 4 5 6 7 8  4 5
1 7
1 3
1 1
0 2 7
1 3

-----Output:-----
-1
6
5
5

# cook your dish here
for _ in range(int(input())):
 n, q = list(map(int, input().split()))
 arr = list(map(int, input().split()))
 for i in range(q):
  s = list(map(int, input().split()))
  if s[0] == 0:
   arr[s[1]] = s[2]
  else:
   k = s[1]
   num = arr[k]
   # print(k, num)
   if k == n-1:
    print(-1)
    continue
   for j in range(k+1, n):
    if arr[j] > num and arr[j] not in arr[:k]:
     print(arr[j])
     break
   else:
    print(-1)


Solve in Python:
Chef is given a sequence of prime numbers $A_1, A_2, \ldots, A_N$. This sequence has exactly $2^N$ subsequences. A subsequence of $A$ is good if it does not contain any two identical numbers; in particular, the empty sequence is good.
Chef has to find the number of good subsequences which contain at most $K$ numbers. Since he does not know much about subsequences, help him find the answer. This number could be very large, so compute it modulo $1,000,000,007$.

-----Input-----
- The first line of the input contains two space-separated integers $N$ and $K$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
Print a single line containing one integer ― the number of good subsequences with size at most $K$, modulo $1,000,000,007$.

-----Constraints-----
- $1 \le K \le N \le 10^5$
- $2 \le A_i \le 8,000$ for each valid $i$

-----Subtasks-----
Subtask #1 (40 points): $A_1, A_2, \ldots, A_N$ are pairwise distinct
Subtask #2 (60 points): original constraints

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

-----Example Output-----
18

-----Explanation-----
There is $1$ good subsequence with length $0$, $5$ good subsequences with length $1$, $8$ good subsequences with length $2$ and $4$ good subsequences with length $3$.

# cook your dish here
from collections import Counter
def solve(arr, n, k):
 ans = 0
 dict1 = {}
 mod = 1000000007

 for i in range(n):
  if arr[i] in dict1:
   dict1[arr[i]] += 1
  else:
   dict1[arr[i]] = 1
 l1 = [-1]+list(dict1.keys())
 v = min(k, len(l1))
 dp = [[0 for _ in range(v+1)]for _ in range(len(l1))]
 dp[0][0] = 1
 for i in range(1, len(l1)):
  dp[i][0] = 1
  for j in range(1, v+1):
   dp[i][j] = dp[i-1][j] + dp[i-1][j-1]*dict1[l1[i]]
 for i in range(v+1):
  ans += dp[len(l1)-1][i]
  ans = ans%mod
 return ans

(n, k) = list(map(int, input().strip().split()))
arr = list(map(int, input().strip().split()))
print(solve(arr, n, k))


Solve in Python:
Chef is going to organize a hill jumping competition and he is going to be one of the judges in it. In this competition there are N hills in a row, and the initial height of i-th hill is Ai. Participants are required to demonstrate their jumping skills by doing what the judges tell them.
Judges will give each participant a card which has two numbers, i and k, which means that the participant should start at the i-th hill and jump k times, where one jump should be from the current hill to the nearest hill to the right which is strictly higher (in height) than the current one. If there is no such hill or its distance (i.e. difference between their indices)  is more than 100 then the participant should remain in his current hill.
Please help Chef by creating a program to use it during the competitions. It should read the initial heights of the hill and should support two kinds of operations:
Type 1: Given a two numbers: i and k, your program should output the index of the hill the participant is expected to finish if he starts from the i-th hill (as explained above).
Type 2: Given three numbers: L, R, X, the heights of all the hills between L and R, both end points inclusive, should be increased by X (if X is negative then their height is decreased).

-----Input-----
- First line contains two integers N and Q, denoting the number of hills and number of operations respectively.
- Second line contains N space-separated integers A1, A2, ..., AN denoting the initial heights of the hills.
- Each of the next Q lines describes an operation. If the first integer is equal to 1, it means that the operation is of Type 1, and it will be followed by two integers i and k. Otherwise the first number will be equal to 2, and it means that the operation is of Type 2, and so it will be followed by three integers L, R and X.

-----Output-----
For each operation of Type 1, output the index of the hill in which the participant will finish.

-----Constraints-----
- 1 ≤ N, Q ≤ 100,000
- 1 ≤ Ai ≤ 1,000,000
- 1 ≤ L ≤ R ≤ N
- -1,000,000 ≤...

import sys

ar = list(map(int, input().strip().split(' ')))
n=ar[0]
q=ar[1]
gre=[]
for i1 in range(n+2):
 gre.append(0)
n1= list(map(int, input().strip().split(' ')))
n1.insert(0,0)
for i1 in range(q):
 a = list(map(int, input().strip().split(' ')))
 if a[0]==2:
  l=a[1]
  r=a[2]
  x=a[3]
  gre[l]+=x
  gre[r+1]-=x
 elif a[0]==1:
  i=a[1]
  k=a[2]
  g=gre[i]
  w1=i
  m1=n1[i]+g
  for qw in range(i+1,n+1):
   g+=gre[qw]
   if qw-w1>100:
    break
   if k==0:
    break
   if n1[qw]+g > m1:
    m1=n1[qw]+g
    w1=qw
    k=k-1
  print(w1)


Solve in Python:
Chef is going to start playing Fantasy Football League (FFL) this season. In FFL, each team consists of exactly $15$ players: $2$ goalkeepers, $5$ defenders, $5$ midfielders and $3$ forwards. Chef has already bought $13$ players; he is only missing one defender and one forward.
There are $N$ available players (numbered $1$ through $N$). For each valid $i$, the $i$-th player is either a defender or a forward and has a price $P_i$. The sum of prices of all players in a team must not exceed $100$ dollars and the players Chef bought already cost him $S$ dollars.
Can you help Chef determine if he can complete the team by buying one defender and one forward in such a way that he does not exceed the total price limit?

-----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 $S$.
- The second line contains $N$ space-separated integers $P_1, P_2, \ldots, P_N$.
- The last line contains $N$ space-separated integers. For each valid $i$, the $i$-th of these integers is $0$ if the $i$-th player is a defender or $1$ if the $i$-th player is a forward.

-----Output-----
For each test case, print a single line containing the string "yes" if it is possible to build a complete team or "no" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $13 \le S \le 100$
- $1 \le P_i \le 100$ for each valid $i$

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

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

-----Example Output-----
yes
no

-----Explanation-----
Example case 1: If Chef buys the $1$-st and $3$-rd player, the total price of his team is $90 + 9 = 99$, which is perfectly fine. There is no other valid way to pick two players.
Example case 2: Chef cannot buy two players in such a way that all conditions are satisfied.

for t in range(int(input())):
 n,k=map(int,input().split())
 l1=list(map(int,input().split()))
 l2=list(map(int,input().split()))
 k=100-k
 f=0
 for i in range(n-1):
  for j in range(i+1,n):
   if (l2[i]==0 and l2[j]==1) or (l2[i]==1 and l2[j]==0):
    if l1[i]+l1[j]<=k:
     f=1
     break
   if f==1:
    break
  if f==1:
   break
 if f==0:
  print("no")
 else:
  print("yes")


Solve in Python:
Chef is good at making pancakes. Generally he gets requests to serve N pancakes at once.
He serves them in the form of a stack.
A pancake can be treated as a circular disk with some radius.
Chef needs to take care that when he places a pancake on the top of the stack the radius of the pancake should not exceed the radius of the largest pancake in the stack by more than 1.
Additionally all radii should be positive integers, and the bottom most pancake should have its radius as 1.
Chef wants you to find out in how many ways can he create a stack containing N pancakes.
Input
First line of the input contains T (T <= 1000) denoting the number of test cases.
T lines follow each containing a single integer N (1 <= N <= 1000) denoting the size of the required stack.
Output
For each case the output should be a single integer representing the number of ways a stack of size N can be created. As the answer can be large print it modulo 1000000007.
Example
Input
2
1
2

Output
1
2

bell_nums = [1]
t = [[1]]

def generate_num():
 nonlocal bell_nums
 nonlocal t
 for i in range(1,1001):
  t.append([])
  t[i].append(t[i-1][i-1])
  for j in range(1,i+1):
   t[i].append((t[i][j-1] + t[i-1][j-1]) % 1000000007)
  bell_nums.append(t[i][i])

generate_num()
tc = int(input())
while tc:
 n = int(input())
 print(bell_nums[n-1])
 tc -= 1


Solve in Python:
Chef is in need of money, so he decided to play a game with Ramsay. In this game, there are $N$ rows of coins (numbered $1$ through $N$). For each valid $i$, the $i$-th row contains $C_i$ coins with values $A_{i, 1}, A_{i, 2}, \ldots, A_{i, C_i}$.
Chef and Ramsay alternate turns; Chef plays first. In each turns, the current player can choose one row that still contains coins and take one of the coins remaining in this row. Chef may only take the the first (leftmost) remaining coin in the chosen row, while Ramsay may only take the last (rightmost) remaining coin in the chosen row. The game ends when there are no coins left.
Each player wants to maximise the sum of values of the coins he took. Assuming that both Chef and Ramsay play optimally, what is the maximum amount of money (sum of values of coins) Chef can earn through this game?

-----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 an integer $C_i$, followed by a space and $C_i$ space-separated integers $A_{i, 1}, A_{i, 2}, \ldots, A_{i, C_i}$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum amount of money Chef can earn.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^4$
- $1 \le C_i \le 10$ for each valid $i$
- $1 \le A_{i, j} \le 10^5$ for each valid $i$ and $j$

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

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

-----Example Output-----
8

-----Explanation-----
Example case 1: One optimal sequence of moves is: Chef takes the coin with value $5$, Ramsay takes $4$, Chef takes $2$, Ramsay takes $3$, Chef takes $1$ and Ramsay takes $6$. At the end, Chef has $5+2+1 = 8$ units of money.

for _ in range(int(input())):
 s=0
 l1=[]
 for i in range(int(input())):
  l=list(map(int,input().split()))
  n=l[0]
  l=l[1:]
  if n%2==0:
   s+=sum(l[:n//2])
  else:
   l1.append(l)
 l2,l3=[],[]
 for i in range(len(l1)):
  l2.append(sum(l1[i][:len(l1[i])//2]))
  l2.append(sum(l1[i][:len(l1[i])//2+1]))
  l3.append(l2)
  l2=[]
 l3.sort()
 for i in range(len(l3)):
  if i<len(l3)//2:
   s+=min(l3[i])
  else:
   s+=max(l3[i])
 print(s)


Solve in Python:
Chef is interested to solve series problems. Chef wants to solve a series problem but he can't
solve it till now.Can you help Chef to solve the series problem?
- In series problem, the series goes as follows 1,9,31,73,141 . . . . . . . .
Your task is to find the Nth term of series. For larger value of $N$ answer becomes very large, So your output should be performed $N$th term modulo 1000000007 ($10^9+7$ ).

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

-----Output:-----
For each testcase,  output in a single line answer i.e. The $N$th term of series modulo 1000000007.

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

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

8

10

-----Sample Output:-----
561

1081


Solve in Python:
Chef is learning linear algebra. Recently, he learnt that for a square matrix $M$, $\mathop{\rm trace}(M)$ is defined as the sum of all elements on the main diagonal of $M$ (an element lies on the main diagonal if its row index and column index are equal).
Now, Chef wants to solve some excercises related to this new quantity, so he wrote down a square matrix $A$ with size $N\times N$. A square submatrix of $A$ with size $l\times l$ is a contiguous block of $l\times l$ elements of $A$. Formally, if $B$ is a submatrix of $A$ with size $l\times l$, then there must be integers $r$ and $c$ ($1\le r, c \le N+1-l$) such that $B_{i,j} = A_{r+i-1, c+j-1}$ for each $1 \le i, j \le l$.
Help Chef find the maximum trace of a square submatrix of $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 a single integer $N$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $N$ space-separated integers $A_{i,1}, A_{i,2}, \dots, A_{i, N}$ denoting the $i$-th row of the matrix $A$.

-----Output-----
For each test case, print a single line containing one integer — the maximum possible trace.

-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 100$
- $1 \le A_{i,j} \le 100$ for each valid $i, j$

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

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

-----Example Output-----
13

-----Explanation-----
Example case 1: The submatrix with the largest trace is
6 3
2 7

which has trace equal to $6 + 7 = 13$. (This submatrix is obtained for $r=2, c=1, l=2$.)

for i in range(int(input())):
 h = int(input())
 f = []
 su = []
 for j in range(0,h):
  f.append(list(map(int,input().split())))
 for k in range(0,h):
  s = 0
  s1 = 0
  for l in range(0,k+1):
   s += f[l][h+l-k-1]
   s1 += f[h+l-k-1][l]
  su.append(s)
  su.append(s1)
 print(max(su))


Solve in Python:
Chef is making Window frames for his new office, for this he has  n wooden Logs whose lengths are l1, l2, … ln respectively. Chef Doesn’t want to break any logs or Stick 2 or more logs together.
To make a  h × w Window Frame, he needs two Logs with lengths equal h and two with length .
The Chef wants as much sunlight in as possible and for it he has decided to make from the available logs as many frames as possible. Help him in finding the number of window Frames that he can make.
Note : Chef do not need to use all the logs
Input:
The first line of the input contains a single integer T denoting the number of test cases. The description of each test case follows :.
The first line of each test case contains a single integer n the number of wooden logs.
The second line contains  n space-separated integers l1,l2,l3….ln The length of each wooden log
Output:
The only line in Output Contains single Integer denoting the maximum possible number of Wooden Frames.
Constraints:
1 ≤ T ≤ 10
1 ≤ n ≤ 100
1 ≤ li ≤ 10000
Example Input:
2
4
1 2 1 2
8
1 2 1 3 4 1 5 6
Example Output:
1
0
Explanation :
First Case :  We can build a frame of dimension 1x2 as two logs of each dimension are available.
Second Case :  We can’t build any Frame as no logs of length except 1 have more than one piece.

t=int(input())
while(t>0):
    n=int(input())
    a=list(map(int,input().split()))
    c=0
    for i in a:
        d=a.count(i)
        for j in range(1,d):
            a.remove(i)
        if(d>=2):
            c+=d//2
    print(c//2)
    t-=1


Solve in Python:
Chef is making polygon cakes in his kitchen today!
Since the judge panel is very strict, Chef's cakes must be beautiful and have sharp and precise $internal$ angles in arithmetic progression.
Given the number of sides, $N$, of the cake Chef is baking today and also the measure of its first angle(smallest angle), $A$, find the measure of the $K^{th}$ angle.

-----Input:-----
- The first line contains a single integer $T$, the number of test cases.
- The next $T$ lines contain three space separated integers $N$, $A$ and $K$, the number of sides of polygon, the first angle and the $K^{th}$ angle respectively.

-----Output:-----
For each test case, print two space separated integers $X$ and $Y$, such that the $K^{th}$ angle can be written in the form of $X/Y$ and $gcd(X, Y) = 1$

-----Constraints-----
- $1 \leq T \leq 50$
- $3 \leq N \leq 1000$
- $1 \leq A \leq 1000000000$
- $1 \leq K \leq N$
- It is guaranteed the answer is always valid.

-----Sample Input:-----
1
3 30 2

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

# cook your dish here
def gcd(d,s):
 if s==0:
  return d
 else:
  return gcd(s,d%s)
for _ in range(int(input())):
 n,a,k=[int(x) for x in input().split()]
 d = (360*(n-2)-2*a*n)*(k-1)
 s = n*(n-1)
 k = gcd(d,s)
 d = d//k
 s=s//k
 print(d+s*a,s)


Solve in Python:
Chef is multi-talented. He has developed a cure for coronavirus called COVAC-19. Now that everyone in the world is infected, it is time to distribute it throughout the world efficiently to wipe out coronavirus from the Earth. Chef just cooks the cure, you are his distribution manager.
In the world, there are $N$ countries (numbered $1$ through $N$) with populations $a_1, a_2, \ldots, a_N$. Each cure can be used to cure one infected person once. Due to lockdown rules, you may only deliver cures to one country per day, but you may choose that country arbitrarily and independently on each day. Days are numbered by positive integers. On day $1$, Chef has $x$ cures ready. On each subsequent day, Chef can supply twice the number of cures that were delivered (i.e. people that were cured) on the previous day. Chef cannot supply leftovers from the previous or any earlier day, as the cures expire in a day. The number of cures delivered to some country on some day cannot exceed the number of infected people it currently has, either.
However, coronavirus is not giving up so easily. It can infect a cured person that comes in contact with an infected person again ― formally, it means that the number of infected people in a country doubles at the end of each day, i.e. after the cures for this day are used (obviously up to the population of that country).
Find the minimum number of days needed to make the world corona-free.

-----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 $x$.
- 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 number of days.

-----Constraints-----
- $1 \le T \le 10^3$
- $1 \le N \le 10^5$
- $1 \le a_i \le 10^9$ for each valid $i$
- $1 \le x \le 10^9$
- the sum of $N$ over all test cases does not...

# cook your dish here
T=int(input())
for _ in range(T):
 n,x=map(int,input().split())
 arr=list(map(int,input().split()))
 arr.sort()
 my_max=arr[-1]
 if x>=my_max:
  print(len(arr))
 else:
  count=0
  while x<=my_max:
   for i in arr:
    if 2*i>x and x>=i:
     arr.remove(i)
     break
   x*=2
   count+=1
  print(count+len(arr))


Solve in Python:
Chef is now a corporate person. He has to attend office regularly. But chef does not want to go to office, rather he wants to stay home and discover different recipes and cook them.
In the office where chef works, has two guards who count how many times a person enters into the office building. Though the duty of a guard is 24 hour in a day, but sometimes they fall asleep during their duty and could not track the entry of a person in the office building. But one better thing is that they never fall asleep at the same time. At least one of them remains awake and counts who enters into the office.
Now boss of Chef wants to calculate how many times Chef has entered into the building. He asked to the guard and they give him two integers A and B, count of first guard and second guard respectively.
Help the boss to count the minimum and maximum number of times Chef could have entered into the office building.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of the T test cases follows.
Each test case consists of a line containing two space separated integers A and B.

-----Output-----
For each test case, output a single line containing two space separated integers, the minimum and maximum number of times Chef could have entered into the office building.

-----Constraints-----
- 1 ≤ T ≤ 100
- 0 ≤ A, B ≤ 1000000

-----Example-----
Input:
1
19 17

Output:
19 36

t=int(input())
for x in range(t):
    a,b=map(int,input().split())
    if a>b:
        print(a,a+b)
    else:
        print(b,a+b)


Solve in Python:
Chef is operating a slush machine. The machine produces slush drinks with $M$ flavors (numbered $1$ through $M$); for each valid $i$, the maximum number of drinks with flavour $i$ the machine can produce is $C_i$.
Chef expects $N$ customers to come buy slush drinks today. The customers are numbered $1$ through $N$ in the order in which they buy the drinks. For each valid $i$, the favorite flavour of the $i$-th customer is $D_i$ and this customer is willing to pay $F_i$ units of money for a drink with this flavour, or $B_i$ units of money for a drink with any other flavuor. Whenever a customer wants to buy a drink:
- if it is possible to sell this customer a drink with their favourite flavour, Chef must sell them a drink with this flavour
- otherwise, Chef must sell this customer a drink, but he may choose its flavour
Chef wants to make the maximum possible profit. He is asking you to help him decide the flavours of the drinks he should sell to the customers in order to maximise the profit.

-----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 $M$ space-separated integers $C_1, C_2, \ldots, C_M$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains three space-separated integers $D_i$, $F_i$ and $B_i$.

-----Output-----
For each test case, print two lines:
- The first of these lines should contain a single integer — the maximum profit.
- The second line should contain $N$ space-separated integers denoting the flavours of the drinks Chef should sell, in this order.
If there are multiple solutions, you may find any one.

-----Constraints-----
- $1 \le T \le 1,000$
- $2 \le N, M \le 10^5$
- $1 \le D_i \le M$ for each valid $i$
- $1 \le C_i \le N$ for each valid $i$
- $1 \le B_i < F_i \le 10^9$ for each valid $i$
- $C_1+C_2+\ldots+C_M \ge N$
- the sum of $N$ over all test cases does...

for _ in range(int(input())):

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

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

 k=[0]*n
 ans=0

 for i in range(n):

  d,f,b = list(map(int,input().split()))

  if l[d-1]!=0:
   l[d-1]-=1
   k[i]=d
   ans+=f
  else:
   ans+=b
 j=0
 for i in range(m):

  if l[i]!=0:

   while(j<n and l[i]>0):

    if k[j]==0:
     l[i]-=1
     k[j]=i+1
    j+=1

 print(ans)
 print(*k)