Solve in Python:
Chef is planning a huge party for all of you and has ordered M pizzas. He wants to invite as many people to the party. However, he knows that everyone will have exactly one slice of a pizza (regardless of the size) and he wants to make sure that he has enough pizza slices.
Chef is very lazy and will only make a total of N straight cuts among all the pizzas. Each pizza is also of different size and to avoid the slices getting too small the chef can only make a max of Ai cuts to the ith pizza. He wants to maximize the number of slices of pizza. Since chef is busy with preparing other aspects of the party he wants you to find out the maximum number of slices he can get following the constraints.
If a pizza is not cut at all then it is considered as 1 slice.

-----Input-----
First line contains two integers M and N.
The second line of input contains the array A.

-----Output-----
Output a single integer - the maximum number of slices chef can get.

-----Constraints-----
- 1 ≤ M ≤ 2*105
- 1 ≤ N,Ai ≤ 2*105

-----Subtasks-----
- Subtask 1: 1 ≤ M,N ≤ 100 - 10 points
- Subtask 2: 1 ≤ N ≤ 100,
1 ≤ M ≤ 105 - 20 points
- Subtask 3: Original Constraints - 70 points

-----Example-----
Input:
5 10
1 2 3 4 5
Output:
31

-----Explanation-----
Example case 1. One of the optimal way to cut would be to do {0, 1,  0, 4, 5} cuts.

# cook your dish here
m,n=[int(i) for i in input().split()]
arr=list(map(int,input().split()))
arr=sorted(arr,reverse=True)
ans=0
w=0
q=m
for m in range(q):
    if(arr[m]>n):
        w=1
        break
    ans+=1+(arr[m]*(arr[m]+1))//2
    n-=arr[m]

if(n==0):
    print(ans)
else:
    if(w==1):
        print(ans+q-m+(n*(n+1))//2)
    else:
        print(ans)


Solve in Python:
Chef is playing a game on a sequence of $N$ positive integers, say $A_1, A_2, ... A_N$ The game is played as follows.
- If all the numbers are equal, the game ends.
- Otherwise
- Select two numbers which are unequal
- Subtract the smaller number from the larger number
- Replace the larger number with the result from above
Chef has already figured out that the game always terminates. He also knows, for a given sequence of integers, the game will always terminate on the same value, no matter how the game is played. Chef wants you to simulate the game for him and tell him if the game terminates on $1$.
In fact, there may be many such games. Given a sequence of integers Chef wants to know the number of sub-sequences of the given sequence, for which, playing the above game on the subsuquence will terminate on $1$. A sub-sequence can be obtained from the original sequence by deleting $0$ or more integers from the original sequence. See the explanation section for clarity.

-----Input-----
- The first line of the input contains an integer $T$, the number of test cases. Then follow the description of $T$ test cases.
- The first line of each test case contains a single integer $N$, the length of the sequence.
- The second line contains $N$ positive integers, each separated by a single space.

-----Output-----
For each test case, output a single integer - the number of sub-sequences of the original sequence, such that, playing the game on the sub-sequence results in ending the game with all the values equal to $1$.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 60$
- $1 \le A_i \le 10^4$
- All $A_i$ will be distinct.

-----Sample Input-----
3
4
2 3 5 7
4
3 4 8 16
3
6 10 15

-----Sample Output-----
11
7
1

-----Explanation-----
Test Case 1: The following $11$ sub-sequences are counted.
- $\{ 2, 3 \}$
- $\{ 2, 5 \}$
- $\{ 2, 7 \}$
- $\{ 3, 5 \}$
- $\{ 3, 7 \}$
- $\{ 5, 7 \}$
- $\{ 2, 3, 5 \}$
- $\{ 2, 3, 7 \}$
- $\{ 2, 5, 7 \}$
- $\{ 3, 5, 7 \}$
- $\{ 2, 3, 5, 7 \}$
Test Case 2: The following $7$...

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

def func(pos,cur_gcd):
 if pos==n:
  if cur_gcd==1:
   return 1
  else:
   return 0
 if (pos,cur_gcd) in dp:
  return dp[(pos,cur_gcd)]
 if cur_gcd==1:
  ans=2**(n-pos)
  dp[(pos,cur_gcd)]=ans
  return ans
 ans = func(pos+1,cal(cur_gcd,a[pos])) + func(pos+1,cur_gcd)
 dp[(pos,cur_gcd)]=ans
 return ans

for _ in range(int(input())):
 n = int(input())
 a = list(map(int,input().split()))
 dp = dict()
 ans = 0
 for i,j in enumerate(a):
  ans+=func(i+1,j)
 print(ans)


Solve in Python:
Chef is playing a game on the non-negative x-axis. It takes him $1$ second to reach from $i^{th}$ position to $(i-1)^{th}$ position or $(i+1)^{th}$ position. The chef never goes to the negative x-axis. Also, Chef doesn't stop at any moment of time.
The movement of chef can be described as follows.
- At the start he is standing at $x=0$ at time $0$.
- In the first round, he moves towards $x=1$ and comes back to the $x=0$ position.
- In the second round, he moves towards the $x=2$ and comes back again to $x=0$.
- Generalizing, in the $k^{th}$ round, he moves from $x=0$ to $x=k$ and then returns back to $x=0$ at the end of the round. This goes on as the game progresses.
For Example, the path of Chef for $3^{rd}$ round is given below.
$0 - 1 - 2 - 3 - 2 - 1 - 0$
The overall path followed by Chef would look somewhat like this:
$0 - 1 - 0 - 1 - 2 - 1 - 0 - 1 - 2 - 3 - 2 - 1 - 0 - 1 - 2 - 3 - 4 - 3 - …$
You are given two non-negative integers $N$ and $K$. You have to tell the time at which Chef arrives at $x=N$ for the $K^{th}$ time.
Note - Chef can not skip a position while visiting the positions.

-----Input:-----
- The first line contains $T$ the number of test cases. Then the test cases follow.
- Each test case contains a single line of two integers $N$ and $K$.

-----Output:-----
For each test case, print a single line containing one integer -- the time taken by the chef to arrive at $x=N$ for the $K^{th}$ time by modulo $1,000,000,007$.

-----Constraints-----
- $1 \le T \le 10^5$
- $0 \le N \le 10^9$
- $1 \le K \le 10^9$

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

-----Sample Output:-----
0
1
4
5
46

-----Explanation:-----
Test Case 1:

Chef starts the journey from the $N = 0$ at time $t = 0$ and it's the first time $(K = 1)$, he is here. So, the answer is $0$.
Test Case 2:

Chef starts the journey from the $N = 0$ at time $t = 0$ then goes to $N = 1$ at $t = 1$ and it's the first time $(K = 1)$, he is here. So, the answer is $1$.
Test Case 4:

The path followed by Chef to reach $1$ for the third...

import math
for _ in range(int(input())):
    n, k = list(map(int, input().split()))
    t = math.floor(k/2)
    r = n + t
    s = r*(r+1)
    if k % 2 == 1:
        s -= n
    else:
        s = s - r
        s = s - t
    if n == 0:
        k = k - 1
        s = int(k*(k+1))
    print(s % 1000000007)


Solve in Python:
Chef is playing a game which contains a binary string.
He can perform one operation only:
- Toggle the i_th bit of the string (0 to 1 or 1 to 0)
By performing operations on the string (can be zero times), you have to convert the string with no adjacent bit being the same.
Can you help chef ?

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

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

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

-----Sample Input:-----
1
4
1011

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

for t in range(int(input())):
 n = int(input())
 s = input()
 count1 = count2 = 0
 for i in range(len(s)):
  if i%2 == 0:
   if s[i] != '1':
    count1 += 1
   if s[i] != '0':
    count2 += 1
  if i%2 == 1:
   if s[i] != '0':
    count1 += 1
   if s[i] != '1':
    count2 += 1
 print(min(count1,count2))


Solve in Python:
Chef is playing a game with his brother Chefu. He asked Chefu to choose a positive integer $N$, multiply it by a given integer $A$, then choose a divisor of $N$ (possibly $N$ itself) and add it to the product. Let's denote the resulting integer by $M$; more formally, $M = A \cdot N + d$, where $d$ is some divisor of $N$.
Chefu told Chef the value of $M$ and now, Chef should guess $N$. Help him find all values of $N$ which Chefu could have chosen.

-----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 integers $A$ and $M$.

-----Output-----
For each test case, print two lines. The first line should contain a single integer $C$ denoting the number of possible values of $N$. The second line should contain $C$ space-separated integers denoting all possible values of $N$ in increasing order.
It is guaranteed that the sum of $C$ over all test cases does not exceed $10^7$.

-----Constraints-----
- $1 \le T \le 100$
- $2 \le M \le 10^{10}$
- $1 \le A < M$

-----Subtasks-----
Subtask #1 (50 points):
- $M \le 10^6$
Subtask #2 (50 points): original constraints

-----Example Input-----
3
3 35
5 50
4 65

-----Example Output-----
1
10
0

3
13 15 16

# cook your dish here
def getdiv(m):
 i=1
 res=[]
 while(i*i<=m):
  if(m%i==0):
   res.append(i)
   if(m//i!=i):
    res.append(m//i)
  i+=1
 return res

test=int(input())
for _ in range(test):
 a,m=map(int,input().split())
 div=getdiv(m)
 res=[]
 for i in div:
  n=(m-i)/a
  if(n>=i and n%1==0 and n%i==0):
   res.append(int(n))
 res.sort()
 print(len(res))
 for i in res:
  print(i,end=' ')
 print('')


Solve in Python:
Chef is playing a game with his childhood friend. He gave his friend a list of N numbers named $a_1, a_2 ....  a_N$ (Note: All numbers are unique). Adjust the numbers in the following order:
$(i)$ swap every alternate number with it's succeeding number (If N is odd, do not swap the last number i.e. $a_N$ ).
$(ii)$ add %3 of every number to itself.
$(iii)$ swap the ith number and the (N-i-1) th number.
After this, Chef will give a number to his friend and he has to give the nearest greater and smaller number to it.
If there is no greater or lesser number, put -1.
Help his friend to find the two numbers.

-----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, an integers $N$.
- Next line contains $N$ integers separated by a space.
- Next line contains a number to be found, $M$.

-----Output:-----
For each test case, output in a single line answer given the immediate smaller and greater number separated by a space.

-----Constraints-----
- $1 \leq T \leq 1000$
- $3 \leq N \leq 10^5$
- $1 \leq N_i \leq 10^9$
- $1 \leq M \leq 10^9$

-----Sample Input:-----
1
10
5 15 1 66 55 32 40 22 34 11
38

-----Sample Output:-----
35 41

-----Explaination:-----
Step 1: 15 5 66 1 32 55 22 40 11 34
Step 2: 15 7 66 2 34 56 23 41 13 35
Step 3: 35  13 41 23 56 34 2 66 7 15
35 is the number lesser than 38 and 41 is the number greater than 38 in the given set of numbers.

for _ in range(int(input().strip())):
    n = int(input().strip())
    list1 = list(map(int, input().strip().split()))[:n]
    m = int(input().strip())
    for i in range(n):
        list1[i] = list1[i] + list1[i]%3
    #print(list1)
    l1 = []
    l2 = []
    list2 = sorted(list1)
    for i in range(n-1,0,-1):
        if list2[i]>m:
            l1.append(list2[i])
    for i in range(n):
        if list2[i]<m:
            l2.append(list2[i])
    if len(l1)>0 and len(l2)>0:
        print(max(l2),min(l1))
    elif len(l1)<=0 and len(l2)>0:
        print(max(l2),"-1")
    elif len(l1)>0 and len(l2)<=0:
        print("-1",min(l1))
    else:
        print("-1","-1")


Solve in Python:
Chef is playing a game with two of his friends. In this game, each player chooses an integer between $1$ and $P$ inclusive. Let's denote the integers chosen by Chef, friend 1 and friend 2 by $i$, $j$ and $k$ respectively; then,  Chef's score is
(((Nmodi)modj)modk)modN.(((Nmodi)modj)modk)modN.(((N\,\mathrm{mod}\,i)\,\mathrm{mod}\,j)\,\mathrm{mod}\,k)\,\mathrm{mod}\,N\,.

Chef wants to obtain the maximum possible score. Let's denote this maximum score by $M$. Find the number of ways to choose the triple $(i,j,k)$ so that Chef's score is equal to $M$.

-----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 integers $N$ and $P$.

-----Output-----
For each test case, print a single line containing one integer — the number of ways to obtain the maximum score.

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

-----Subtasks-----
Subtask #1 (10 points):
- $1 \le T \le 100$
- $1 \le N \le P \le 100$
Subtask #2 (90 points): original constraints

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

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

-----Explanation-----
Example case 1: Chef's maximum possible score is $M = 1$. All possible values of $(i, j, k)$ such that the score is $1$ are
$(3, 2, 2)$,
$(3, 2, 3)$,
$(3, 2, 4)$,
$(3, 3, 2)$,
$(3, 3, 3)$,
$(3, 3, 4)$,
$(3, 4, 2)$,
$(3, 4, 3)$,
$(3, 4, 4)$.

R = lambda : list(map(int,input().split()))
t = int(input())
for _ in range(t):
 n,p = R()
 max_no =n-(int(n/2)+1)
 # print(max_no)
 if max_no==0:
  print(p*p*p)
 else:
  ans = 1*(p-max_no)*(p-max_no)+(p-n)*(p-max_no)+(p-n)*(p-n)
  print(ans)


Solve in Python:
Chef is playing with an expression which consists of integer operands and the following binary
Bitwise operators -  AND, OR and XOR. He is trying to figure out that what could be the Maximum possible answer of the expression, given that he can perform the operation in any order i.e not necessarily follow the rule of Precedence of operators while evaluating the expression.
After some time of consistent work Chef starts feeling exhausted and wants you to automate this process for him. Can you help him out?
The expression has Bitwise operators in symbol format:
- &  stands for AND
- |   stands for OR
- ^   stands for XOR
NOTE : It is guaranteed that the expression will always be valid, also each OPERATOR will always be preceded and succeeded by an OPERAND.

-----Input:-----
- The first line of input contains a single integer $T$ denoting the number of test cases.
- The only line of input for each test case is a $string$ which is the Chef's expression to evaluate.

-----Output:-----
For each test case print a single integer i.e the maximum possible value of Chef's expression.

-----Constraints-----
- $1 \leq T \leq 100$.
- The number of OPERATORS in the expression will be atleast 1 and atmost 10.
- Each OPERAND may range from 0 to $10^9$.

-----Subtasks-----
- 10 points : The number of OPERATORS in the expression will be atmost 5.
- 20 points : The number of OPERATORS in the expression will be atmost 8.
- 70 points : Original constraints.

-----Sample Input:-----
2
3^40|10^2

92^95|56&2&3

-----Sample Output:-----
43

95

-----EXPLANATION:-----CASE 2 :
- If we first compute (56 & 2), the expression becomes 92^95|0&3, since (56 & 2) yields $0$.
- Now on computing (95 | 0), the expression becomes 92^95&3.
- Further on computing (95 & 3), the expression becomes 92^3.
- Finally (92 ^ 3) yields 95, which is the maximum value of the expression.

def extract(s):
	arr = []
	news = ''
	for x in s:
		try:
			x = int(x)
			news = news+str(x)
		except:
			arr = [news]+arr
			news = ''
			arr = [x]+arr
	arr = [news]+arr
	return arr
for i in range(int(input())):
	s = input()
	arr = extract(s)
	n = len(arr)//2 + 1
	dp = [[0]*n for j in range(n)]
	for i in range(n):
		dp[i][i] = [int(arr[2*i])]
	n = len(arr)
	for i in range(3, n+1, 2):
		for j in range(0, n-i+1, 2):
			ans = []
			for k in range(j+2, i+j+1, 2):
				for x in dp[j//2][(k-1)//2]:
					for y in dp[k//2][(i+j)//2]:
						if arr[k-1] == '&':
							ans += [x & y]
						if arr[k-1] == '|':
							ans += [x | y]
						if arr[k-1] == '^':
							ans += [x ^ y]
			if i != n:
				dp[j//2][k//2] = ans[:]
			else:
				print(max(ans))


Solve in Python:
Chef is solving mathematics problems. He is preparing for Engineering Entrance exam. He's stuck in a problem.
$f(n)=1^n*2^{n-1}*3^{n-2} * \ldots * n^{1} $
Help Chef to find the value of $f(n)$.Since this number could be very large, compute it modulo $1000000007$.

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

-----Output:-----
For each testcase, output in a single line the value of $f(n)$ mod $1000000007$.

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

-----Subtasks-----
Subtask 1(24 points) :
- $1 \leq T \leq 5000$
- $1 \leq N \leq 5000$
Subtask 2(51 points) : original constraints

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

-----Sample Output:-----
12

#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

M = 10**9+7
f = [1]*(1000001)
for i in range(2,1000001):
 f[i] = (i*f[i-1])%M
for i in range(2,1000001):
 f[i] = (f[i]*f[i-1])%M

for _ in range(inp()):
 n = inp()
 print(f[n])


Solve in Python:
Chef is stuck in a two dimensional maze having N rows and M columns. He needs to get out of the maze as soon as possible and arrive at the kitchen in order to serve his hungry customers. But, he can get out of the maze only if he is able to successfully find any magical path in the given maze.

A path is defined as magical if it starts from any of the cell (a,b) of the maze and ends at the cell (c,d) such that the following conditions are satisfied :-
- |a - c| + |b - d| = 1
- All the cells in the maze are traversed exactly once.
- It is allowed to move only in the four directions - up, down, left and right from the current cell.

-----Input-----
- First line of the input contains an integer T denoting the number of different types of scenarios.
- Each of the next T lines will contain two integers N, M denoting the dimensions of the maze.

-----Output-----
For each of the T scenarios, output a single line containing "Yes" or "No" (without quotes) denoting whether the Chef can get out of the maze or not.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ N, M ≤ 1018

-----Subtasks-----
Subtask #1 : (30 points)
- 1 ≤ T ≤ 100
- 1 ≤ N, M ≤ 10

Subtask #2 : (70 points)

Original Constraints

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

Output:
Yes

-----Explanation-----
Example case 1.

Chef can start from (1,1), move down to (2,1), then move right to (2,2) and finally move upwards to reach (1,2). As, he is able to visit all the cells exactly once and sum of absolute differences of corresponding x and y dimension is 1, we can call this path a magical path.

t=int(input())
for _ in range(t):
 n,m=input().strip().split()
 if (n=='1' and m=='2') or (n=='2' and m=='1'):
  print("Yes")
 elif n=='1' or m=='1':
  print("No")
 elif int(n[-1])%2==0 or int(m[-1])%2==0:
  print("Yes")
 else:
  print("No")


Solve in Python:
Chef is stuck on the minute hand of a giant clock. To escape from this clock he needs to get onto the hour hand which has an exit door.
Since the minute hand and and hour hand are not connected at any point, chef will surely need to make a jump. Since he wants minimum risks, he chooses to jump on the hour hand so that the angle he has to cover is minimum possible.
You will be given a clock time in $UTC$ format denoting time of chef's jump and you have to compute the minimum angle that chef needs to cover while completing the jump.
For some reason chef times his jump only when the number of minutes is a multiple of 5.

-----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 string denoting time in UTC format (e.g. 10:20 i.e. 10 hours and 20 minutes)

-----Output-----
For each test case, print a single line denoting the smallest angle of jump.

-----Constraints-----
- $1 \leq T \leq 10^3$
- $0 \leq hours \leq 23$
- $0 \leq minutes \leq 59$

-----Example Input-----
3
14:20
02:10
09:30

-----Example Output-----
50 degree
5 degree
105 degree

-----Explanation-----
- In the second case, once the hour hand reaches 2 it starts moving towards 3 with the passing of every minute, hence when the minute hand points 10 minutes, the hour hand has already covered some angle towards 3.
In this scenario the two angles made by hour and minute hand are 355 and 5 degrees. Since chef will jump on the side with minimum angle, he chooses the one with 5-degree angle.

# cook your dish here
try:
 for _ in range(int(input())):
  time = input().split(':')
  hour = int(time[0])
  minute = int(time[1])
  if hour == 0:
   hour = 12
  elif hour > 12:
   hour = hour - 12
  mindeg = minute * 6
  hourdeg = (hour * 30) + (minute/60)*30
  x = abs(hourdeg - mindeg)
  if str(x).split('.')[1] == '0':
   if x > 180:
    print(int(360-x),'degree')
   else:
    print(int(x),'degree')
  else:
   if x > 180:
    print(360-x,'degree')
   else:
    print(x,'degree')
except:
 pass


Solve in Python:
Chef is the event manager of his college. He has been assigned the task to manage the upcoming tech fest. There are $K$ rooms where the event can take place, and at a particular time only one event can be organized in a room for a particular time interval.
Each event coordinator has their strictly preferred room $P_i$, and if the room is already occupied he simply cancels that event.Chef wants to maximize the total number of events,and so he allows or disallows certain events in order to achieve the task . Chef is busy handling his events so the chef needs your help .
Given a list of $N$ events with their start time $S_i$,end time $E_i$ and preferred room $P_i$,you need to calculate the maximum number of events that can take place.
Note that the $i$th event wants to occupy the $p_i$ room from [$s_i$, $f_i$) .

-----Input:-----
The first line contains an integer $T$ denoting the number of test cases . Each of the next $T$ lines contains two integers $N$ and $K$ , the number of events and the number of rooms respectively . Each of the next $N$ lines contains three integers $s_i$ ,$e_i$ and $p_i$,the start time ,end time and the preferred room of ith event.

-----Output:-----
Print the maximum number of events that can take place.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^3$
- $1 \leq  K \leq 10^5$
- $1 \leq  Si <  Ei \leq 10^9$
- $1 \leq Pi \leq K$

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

4 2
1 10 1
10 20 2
15 50 2
20 30 2

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

-----EXPLANATION:-----
Chef can allow events 1st ,2nd and 4th,to get the maximum 3.

from sys import stdin, stdout
input = stdin.readline
print2 = stdout.write
def get_list(): return tuple(map(int, stdin.readline().split()))
for _ in range(int(input())):
	n, k = map(int, stdin.readline().split())
	event = sorted([get_list() for _ in range(n)])
	occup = {}
	count = 0
	for e in event:
		if not occup.get(e[2]) or e[0] >= occup[e[2]][1]:
			occup[e[2]] = e
			count += 1
		elif e[1] < occup[e[2]][1]:
			occup[e[2]] = e
	print(count)


Solve in Python:
Chef is the judge of a competition. There are two players participating in this competition — Alice and Bob.
The competition consists of N races. For each i (1 ≤ i ≤ N), Alice finished the i-th race in Ai minutes, while Bob finished it in Bi minutes. The player with the smallest sum of finish times wins. If this total time is the same for Alice and for Bob, a draw is declared.
The rules of the competition allow each player to choose a race which will not be counted towards their total time. That is, Alice may choose an index x and her finish time in the race with this index will be considered zero; similarly, Bob may choose an index y and his finish time in the race with this index will be considered zero. Note that x can be different from y; the index chosen by Alice does not affect Bob's total time or vice versa.
Chef, as the judge, needs to announce the result of the competition. He knows that both Alice and Bob play optimally and will always choose the best option. Please help Chef determine the result!

-----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 A1, A2, ..., AN.
- The third line contains N space-separated integers B1, B2, ..., BN.

-----Output-----
For each test case, print a single line containing the string "Alice" if Alice wins, "Bob" if Bob wins or "Draw" if the result is a draw (without quotes).

-----Constraints-----
- 1 ≤ T ≤ 100
- 2 ≤ N ≤ 100
- 1 ≤ Ai ≤ 1000 for each valid i
- 1 ≤ Bi ≤ 1000 for each valid i

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

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

Output:

Alice
Bob
Draw

-----Explanation-----
Example case 1: Alice will choose the finish time in the last race to be considered zero, which means her sum of finish times is 3 + 1 + 3 + 3 + 0 = 10, while Bob will choose the finish time of his second race to be considered zero, so his...

# cook your dish here
for i in range(int(input())):
 N=int(input())
 ALICE=list(map(int,input().split()))
 BOB=list(map(int,input().split()))
 ALICE[ALICE.index(max(ALICE))]=0
 BOB[BOB.index(max(BOB))]=0
 if sum(ALICE)<sum(BOB):
  print("Alice")
 elif sum(BOB)<sum(ALICE):
  print("Bob")
 else:
  print("Draw")


Solve in Python:
Chef is the leader of Chef's Earth Defense Organization, and his mission is to counter aliens which are threatening the earth. According to information gathered by the organization, there are $N$ alien spaceships (numbered $1$ through $N$) planning to invade the earth. The $i$-th spaceship will appear on the radar at time $C_i$. Each spaceship needs $D$ time to reach earth once it appears on the radar.
Chef's organization owns a huge laser cannon which can destroy one spaceship in one shot. However, once the cannon is used once it needs some amount of cool-down time in order to be used again (first shot doesn't require cool-down time before it is used). This cool-down time, however, is configurable. It has to be set before the first shot, and cannot be changed after that. If Chef sets a lower cool-down time, that would increase the energy consumed by the cannon, and vice-versa - the higher the cool-down time, the lower the energy consumed.
This might be a long battle, and Chef wants to use as little energy as possible. So Chef wants to maximize the cool-down time while still being able to destroy all spaceships before any of them arrive on earth. In particular, the $i$-th spaceship should be shot between the times $C_i$ and $C_i + D$ (both end points inclusive).

-----Input:-----
- The first line of 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 integers $N$ and $D$.
- The second line contains $N$ space-separated integers $C_1, C_2, \ldots, C_N$.

-----Output:-----
For each test case, print a single line containing one real number― the maximum cool-down time possible. Your answer will be considered correct if the absolute or relative error of the answer does not exceed $10^{-6}$.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 10^5$
- $1 \leq C_i \leq 10^9$ for each valid $i$
- $1 \leq D \leq 10^9$
- The sum of $N$ over all test cases does not exceed...

def isValid(arr,mid,n):
 t = 0.0
 for i in range(n):
  if t<arr[i]:
   t = arr[i] + mid
  elif t<=arr[i] + d:
   t = t + mid
  else:
   return False
 return True

for _ in range(int(input())):
 n,d = list(map(int,input().split(' ')))
 arr = [int(num) for num in input().split(' ')]
 duration = []
 ans = -1
 arr.sort()

 left = 0.0
 right = 10000000000
 while right -left >= 10**(-6):
  mid = (left+right)/2
  #print(mid)
  if isValid(arr,mid,n)==True:
   left = mid
   ans = mid
  else:
   right = mid

 print(ans)


Solve in Python:
Chef is the new king of the country Chefland. As first and most important responsibility he wants to reconstruct the road system of Chefland. There are N (1 to N) cities in the country and each city i has a population Pi. Chef wants to build some bi-directional roads connecting different cities such that each city is connected to every other city (by a direct road or through some other intermediate city) and starting from any city one can visit every other city in the country through these roads. Cost of building a road between two cities u and v is Pu x Pv. Cost to build the road system is the sum of cost of every individual road that would be built.
Help king Chef to find the minimum cost to build the new road system in Chefland such that every city is connected to each other.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line contains an integer N denoting the number of cities in the country. Second line contains N space separated integers Pi, the population of i-th city.

-----Output-----
For each test case, print a single integer, the minimum cost to build the new road system on separate line.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ Pi ≤ 106

-----Example-----
Input:
2
2
5 10
4
15 10 7 13

Output:
50
266

for _ in range(int(input())):
 n=int(input())
 ar=[int(x) for x in input().split()]
 if n==1:
  print(ar[0])
 elif n==2:
  print(ar[0]*ar[1])
 else:
  ar.sort()
  an=0
  for i in range(1,n):
   an+=ar[0]*ar[i]
  print(an)


Solve in Python:
Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horses are comparable on their skill i.e. the difference in their skills is less.
There are N horses in the stable. The skill of the horse i is represented by an integer S[i]. The Chef needs to pick 2 horses for the race such that the difference in their skills is minimum. This way, he would be able to host a very interesting race. Your task is to help him do this and report the minimum difference that is possible between 2 horses in the race.

-----Input:-----
First line of the input file contains a single integer T, the number of test cases.

Every test case starts with a line containing the integer N.

The next line contains N space separated integers where the i-th integer is S[i].

-----Output:-----
For each test case, output a single line containing the minimum difference that is possible.

-----Constraints:-----
1 ≤ T ≤ 10
2 ≤ N ≤ 5000
1 ≤ S[i] ≤ 1000000000

-----Example:-----Input:
1
5
4 9 1 32 13

Output:
3

Explanation: The minimum difference can be achieved if we pick horses with skills 1 and 4 for the race.

t=int(input())
for i in range(t):
 n=int(input())
 a=[]
 a=list(map(int, input().split() ))
 a=sorted(a)
 diff=[]
 for i in range(n-1):
  diff.append(a[i+1]-a[i])
 print(min(diff))


Solve in Python:
Chef is very organised in whatever he does and likes to maintain statistics of his work. Chef has expertise in web development and hence is a regular contributor on a forum. Chef sometimes makes multiple contributions in a single day.. Each day chef makes at least 1 contribution he is assigned a shade of green. The greater the number of contribution in a single day the darker shade of green he gets assigned and vice versa. Your job is to find out the number of days chef is assigned a same shade of green and print the number of times chef is assigned a unique shade of green.

-----INPUT-----
The first line of input contains an integer T denoting the number of test cases. T test cases follow.

The first line of each test case contains an integer N denoting the number of days chef has contributed towards the forum.

The next line contains N spaced integers the number of contributions chef has made if he has made any.

-----OUTPUT-----

The output will contain numbers on separate lines that show the number of individual green shades chef has earned in ascending order of intensity of the shades of green.

-----CONSTRAINTS-----
1 <= T <= 25

5 <= N <= 50

1 <= Ai <= 50

-----EXAMPLE-----Input:

1

7

20 6 5 3 3 1 1
Output:

1: 2

3: 2

5: 1

6: 1

20: 1

from collections import Counter
t=int(input())
for i in range(t):
 k=int(input())
 l=list(map(int,input().split()))
 a=Counter(l)
 b=list(a.keys())
 b.sort()
 for x in b:
  s=str(x)+': '+str(a[x])
  print(s)


Solve in Python:
Chef just come up with a very good idea for his business. He needs to hire two group of software engineers. Each group of engineers will work on completely different things and people from different groups don't want to disturb (and even hear) each other. Chef has just rented a whole floor for his purposes in business center "Cooking Plaza". The floor is a rectangle with dimensions N over M meters. For simplicity of description the floor's structure, let's imagine that it is split into imaginary squares of size 1x1 called "cells".
The whole floor is split into rooms (not necessarily rectangular). There are some not noise-resistant walls between some of the cells. Two adjacent cells belong to the same room if they don't have the wall between them. Cells are considered adjacent if and only if they share an edge. Also, we say that relation "belong to the same room" is transitive. In other words we say that if cells A and B belong to the same room and B and C belong to the same room then A and C belong to the same room.
So we end up having a partition of the floor into rooms. It also means, that each point on the floor belongs to some room.
Chef have to distribute the rooms between engineers of two groups. Engineers from the different groups cannot seat in the same room. If engineers from a different groups seat in adjacent rooms, the walls these rooms share have to be noise-resistant. The cost of having one meter of wall isolated is K per month. Due to various reasons Chef has to pay an additional cost for support of each of the room (e.g. cleaning costs money as well). Interesting to know that support cost for a particular room may differ depending on engineers of which group seat in this room.
Chef doesn't know the number of people he needs in each group of engineers so he wants to minimize the money he needs to pay for all the floor rent and support. He will see how it goes and then redistribute the floor or find another floor to rent or whatever. Either way, you don't need to care about this.
Please pay...

import sys

def findRoom(x,y,i):
 R = [(x,y)]
 GRID[x][y] = i
 for n in R:
  GRID[n[0]][n[1]] = i
  if n[0]>0 and GRID[n[0]-1][n[1]]==0 and H[n[0]-1][n[1]]:
   GRID[n[0]-1][n[1]] = i
   R.append((n[0]-1,n[1]))
  if n[0]<N-1 and GRID[n[0]+1][n[1]]==0 and H[n[0]][n[1]]:
   GRID[n[0]+1][n[1]] = i
   R.append((n[0]+1,n[1]))
  if n[1]>0 and GRID[n[0]][n[1]-1]==0 and V[n[0]][n[1]-1]:
   GRID[n[0]][n[1]-1] = i
   R.append((n[0],n[1]-1))
  if n[1]<M-1 and GRID[n[0]][n[1]+1]==0 and V[n[0]][n[1]]:
   GRID[n[0]][n[1]+1] = i
   R.append((n[0],n[1]+1))

def roomPrice(r):
 wall_price_0 = wall_price_1 = 0
 for i in range(R):
  if C[i][r] and T[i] != 1:
   wall_price_0 += C[i][r]*K
  else:
   wall_price_1 += C[i][r]*K
 return [wall_price_0 + Rooms[r][0], wall_price_1 + Rooms[r][1]]

def total_price():
 price = 0
 for r in range(R):
  for i in range(r):
   if C[i][r] and T[i] != T[r]:
    price += C[i][r]*K
    price += Rooms[r][T[r]-1]
 return price

def solve(r):
 if r==R:
  return 0
 wall_price_0 = 0
 wall_price_1 = 0
 for i in range(r):
  if C[i][r] and T[i] != 1:
   wall_price_0 += C[i][r]*K
  else:
   wall_price_1 += C[i][r]*K
 if T[r]!=0:
  return [wall_price_0,wall_price_1][T[r]-1]+Rooms[r][T[r]-1]+solve(r+1)
 T[r] = 1
 result = solve(r+1)+wall_price_0+Rooms[r][0]
 T[r] = 2
 result = min(solve(r+1)+wall_price_1+Rooms[r][1], result)
 T[r] = 0
 return result

f = sys.stdin
N,M,W,K,R = list(map(int, f.readline().split(' ')))
T = [0] * R
GRID = list(map(list,[[0]*M]*N))
H = list(map(list,[[1]*M]*N))
V = list(map(list,[[1]*M]*N))
Walls = []
for _ in range(W):
 x0,y0,x1,y1 = list(map(int, f.readline().split(' ')))
 x0 -= 1
 x1 -= 1
 y0 -= 1
 y1 -= 1
 if x0==x1:
  V[x0][y0] = 0
 else:
  H[x0][y0] = 0
 Walls.append([x0,y0,x1,y1])
Rooms = []
for i in range(R):
 x,y,t1,t2 = list(map(int, f.readline().split(' ')))
 findRoom(x-1,y-1,i+1)
 Rooms.append([t1,t2])
C = list(map(list,[[0]*R]*R))
for w in Walls:
 r1 = GRID[w[0]][w[1]]-1
 r2 = GRID[w[2]][w[3]]-1
 C[r1][r2] += 1
 C[r2][r1] += 1
Stable = [False]*R
for r in range(R):
...


Solve in Python:
Chef just got a box of chocolates as his birthday gift. The box contains $N$ chocolates in a row (numbered $1$ through $N$), where $N$ is even. For each valid $i$, the $i$-th chocolate has a sweetness value $W_i$.
Chef wants to eat all the chocolates in the first half of the box and leave all chocolates in the second half uneaten. Since he does not like chocolates that are too sweet, he will be unhappy if at least one of the chocolates he eats has the maximum sweetness among all the chocolates in the box.
A right cyclic shift by $k$ chocolates ($0 \le k < N$) consists of moving the last $k$ chocolates in the row to the beginning in the same order and moving each of the remaining $N-k$ chocolates $k$ places to the right. Before eating the first half of the chocolates, Chef wants to perform some right cyclic shift in such a way that he will not be unhappy after eating them. Find the number of ways to do this, i.e. the number of valid integers $k$ such that if Chef performs the right cyclic shift by $k$ chocolates and then eats the first half of the chocolates in the box, he does not become unhappy.

-----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 $W_1, W_2, \ldots, W_N$.

-----Output-----
For each test case, print a single line containing one integer ― the number of shifts for which Chef does not become unhappy.

-----Constraints-----
- $1 \le T \le 5$
- $1 \le N \le 10^5$
- $N$ is even
- $1 \le W_i \le 10^5$ for each valid $i$

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

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

-----Explanation-----
Example case 1: The three valid right shifts and the contents of the box for these shifts are:
- shift by $k = 1$: $(1, 1, 1, 2, 1, 1)$
- shift by $k = 2$: $(1, 1, 1, 1, 2, 1)$
- shift by $k = 3$: $(1, 1, 1, 1, 1, 2)$

# cook your dish here
t=int(input())
for i in range(t):
 a=int(input())
 cho =list(map(int, input().split()))
 maxc=max(cho)
 start=cho.index(maxc)
 mid =int(len(cho)/2)
 for j in range(len(cho)-1, 0, -1):
  if(cho[j]==maxc):
   end = j
   break
 ans =((len(cho))-end)-(mid-start)
 print(max(0,ans))


Solve in Python:
Chef likes all arrays equally. But he likes some arrays more equally than others. In particular, he loves Rainbow Arrays.
An array is Rainbow if it has the following structure:
- First a1 elements equal 1.
- Next a2 elements equal 2.
- Next a3 elements equal 3.
- Next a4 elements equal 4.
- Next a5 elements equal 5.
- Next a6 elements equal 6.
- Next a7 elements equal 7.
- Next a6 elements equal 6.
- Next a5 elements equal 5.
- Next a4 elements equal 4.
- Next a3 elements equal 3.
- Next a2 elements equal 2.
- Next a1 elements equal 1.
- ai can be any non-zero positive integer.
- There are no other elements in array.

Help Chef in finding out if the given array is a Rainbow Array or not.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases.
- The first line of each test case 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 elements of array.

-----Output-----
- For each test case, output a line containing "yes" or "no" (without quotes) corresponding to the case if the array is rainbow array or not.

-----Constraints-----
- 1 ≤ T ≤ 100
- 7 ≤ N ≤ 100
- 1 ≤ Ai ≤ 10

-----Subtasks-----
- Subtask 1 (100 points) : Original constraints

-----Example-----
Input
3
19
1 2 3 4 4 5 6 6 6 7 6 6 6 5 4 4 3 2 1
14
1 2 3 4 5 6 7 6 5 4 3 2 1 1
13
1 2 3 4 5 6 8 6 5 4 3 2 1

Output
yes
no
no

-----Explanation-----
The first example satisfies all the conditions.
The second example has 1 element of value 1 at the beginning and 2 elements of value 1 at the end.
The third one has no elements with value 7 after elements with value 6.

t=int(input())
x=[1,2,3,4,5,6,7]
for i in range(t):
 N=int(input())
 a=list(map(int,input().split()))
 rev=a[::-1]
 dup=set(a)
 if rev== a and list(dup) ==x:
  print("yes")
 else:
  print("no")


Solve in Python:
Chef likes prime numbers. However, there is one thing he loves even more. Of course, it's semi-primes! A semi-prime number is an integer which can be expressed as a product of two distinct primes. For example, $15 = 3 \cdot 5$ is a semi-prime number, but $1$, $9 = 3 \cdot 3$ and $5$ are not.
Chef is wondering how to check if an integer can be expressed as a sum of two (not necessarily distinct) semi-primes. Help Chef with this tough task!

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

-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to express $N$ as a sum of two semi-primes or "NO" otherwise.

-----Constraints-----
- $1 \le T \le 200$
- $1 \le N \le 200$

-----Example Input-----
3
30
45
62

-----Example Output-----
YES
YES
NO

-----Explanation-----
Example case 1: $N=30$ can be expressed as $15 + 15 = (3 \cdot 5) + (3 \cdot 5)$.
Example case 2: $45$ can be expressed as $35 + 10 = (5 \cdot 7) + (2 \cdot 5)$.
Example case 3: $62$ cannot be expressed as a sum of two semi-primes.

def sievearray():
  n=200
  sieve=[1 for i in range(n+1)]
  sieve[0]=0
  sieve[1]=0
  i=2
  while i*i<=n:
    if sieve[i]==1:
      for j in range(i*i,n+1,i):
        sieve[j]=0
    i+=1
  return sieve
def semiprime(n):
  i=2
  m2=0
  m1=0
  while i!=n:
    if n%i==0 and sieve[i]==1:
      m1=i
    if n==m1*m2 and m1!=m2:
      return 1
    else:
      m2=m1
      i+=1
  return 0
def sum_of_two(n):
  for i in range(2,n//2+1):
    p=i
    q=n-i
    if semiprime(p) and semiprime(q):
      return 1
try:
    t=0
    t=int(input())
    sieve=sievearray()
except Exception:
    pass
l1=[0 for i in range(0,t)]
for i in range(0,t):
  l1[i]=int(input())
for i in range(0,len(l1)):
  if sum_of_two(l1[i]):
    print("YES")
  else:
    print("NO")


Solve in Python:
Chef likes problems on geometry a lot. Please help him to solve one such problem.
Find all possible triangles with integer sides which has the radius of inscribed circle (also known as incircle) equal to R.
Two triangles are said to be different if they have at least one different side lengths. Formally, let there be two triangles T1, T2. Let a, b, c denote the sides of triangle T1, such that a ≤ b ≤ c. Similarly, Let d, e, f denote the sides of triangle T2, such that d ≤ e ≤ f. Then T1 will said to be different from T2 if either a ≠ d, or b ≠ e or c ≠ f.

-----Input-----
There is a single test case per test file.
The only line of input contains an integer R.

-----Output-----
Output in first line single number - number of triangles satisfying statement.
Order the sides of triangles in non-decreasing order. Output all triangles in non-decreasing order, i.e. order first by smallest sides, otherwise by second smallest sides, if first and second sides equal, then by third.

-----Constraints-----
- 1 ≤ R ≤ 100

-----Subtasks-----
- Subtask #1: (20 points)  1 ≤ R ≤ 3
- Subtask #2: (30 points)  1 ≤ R ≤ 20
- Subtask #3: (50 points)  Original constraints

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

Output:5
5 12 13
6 8 10
6 25 29
7 15 20
9 10 17

R=int(input())
t=[]
for a in range(2*R,200):
  for b in range(a,300):
   for c in range(b,400 ):
     s=(a+b+c)/2.0
     d=s*(s-a)*(s-b)*(s-c)
     if d>=0 and s!=0 and (a+b)>c:
        if R**2==(d/s**2):
         t.append([a,b,c])
         if len(t)>20:
           break
print(len(t))
for i in range(len(t)):
  print(t[i][0],t[i][1],t[i][2])


Solve in Python:
Chef likes problems related to learning new languages. He only knows first N letters of English alphabet. Also he explores all M-letter words formed by the characters he knows. Define cost for a given M-letter word S, cost(S) = P1, S1+P2, S2+...+PM, SM, where Pi, j is i, jth entry of matrix P. Sort all the words by descending cost, if costs are equal, sort them lexicographically. You need to find K-th M-letter word in Chef's order.

-----Input-----
First line contains three positive integer numbers N, M and K.
Next M lines contains N integers per line, denoting the matrix P.

-----Output-----
Output in a single line K-th M-letter in Chef's order.

-----Constraints-----
- 1 ≤ N ≤ 16
- 1 ≤ M ≤ 10
- 1 ≤ K ≤ NM
- 0 ≤ Pi, j ≤ 109

-----Subtasks-----
- Subtask #1: (20 points) 1 ≤ K ≤ 10000
- Subtask #2: (20 points) 1 ≤ M ≤ 5
- Subtask #3: (60 points) Original constraints

-----Example-----
Input:2 5 17
7 9
13 18
10 12
4 18
3 9

Output:aaaba

def dfs(ind,m,n,k):
 if(ind == m):
  return [""]
 else:
  temp = dfs(ind+1,m,n,k)
  ans = []
  if(len(temp)<k):
   for i in temp:
    for j in range(97,97+n):
     ans += [chr(j)+i]
  else:
   for i in temp:
    ans += ["z"+i]
 return ans
n,m,k = list(map(int,input().split()))
p = []
for _ in range(m):
 inp = [int(x) for x in input().split()]
 p += [inp]
max_row = []
for i in p:
 max_row += [max(i)]
ans = dfs(0,m,n,k)
w = []
for i in ans:
 cst = 0
 for j in range(m):
  if(p[j]!="z"):
   cst += p[j][ord(i[j])-97]
  else:
   cst += max_row[j]
 w += [(-cst,i)]
w.sort()
print(w[k-1][1])


Solve in Python:
Chef likes problems which using some math. Now he asks you to solve next one. You have 4 integers, Chef wondering is there non-empty subset which has sum equals 0.

-----Input-----
The first line of input contains T - number of test cases.
Each of the next T lines containing four pairwise distinct integer numbers - a, b, c, d.

-----Output-----
For each test case output "Yes", if possible to get 0 by choosing non-empty subset of {a, b, c, d} with sum equal 0, or "No" in another case.

-----Constraints-----
- 1 ≤ T ≤ 103
- -106 ≤ a, b, c, d ≤ 106

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

Output:
Yes
Yes
No

-----Explanation-----
Example case 1. We can choose subset {0}
Example case 2. We can choose subset {-1, 1}

for i in range(int(input())):
 a,b,c,d= list(map(int,input().split()))
 if a==0 or b==0 or c==0 or d==0:
  print('Yes')
 elif a+b+c+d==0:
  print('Yes')
 elif a+b+c==0 or a+b+d==0 or a+c+d==0 or b+c+d==0:
  print('Yes')
 elif a+b==0 or b+c==0 or c+d==0 or a+c==0 or a+d==0 or b+d==0:
  print('Yes')
 else:
  print('No')


Solve in Python:
Chef likes strings a lot but he likes palindromic strings even more. Today he found an old string s in his garage. The string is so old that some of its characters have faded and are unidentifiable now. Faded characters in the string are represented by '.' whereas other characters are lower case Latin alphabets i.e ['a'-'z'].

Chef being the palindrome lover decided to construct the lexicographically smallest palindrome by filling each of the faded character ('.') with a lower case Latin alphabet. Can you please help him completing the task?

-----Input-----
First line of input contains a single integer T denoting the number of test cases. T test cases follow.
First and the only line of each case contains string s denoting the old string that chef has found in his garage.

-----Output-----
For each test case, print lexicographically smallest palindrome after filling each faded character - if it possible to construct one. Print -1 otherwise.

-----Constraints-----
- 1 ≤ T ≤ 50
- 1 ≤ |s| ≤ 12345
- String s consists of ['a'-'z'] and '.' only.

-----Subtasks-----Subtask #1 (47 points)
- 1 ≤ T ≤ 50, 1 ≤ |S| ≤ 123
Subtask #2 (53 points)
- 1 ≤ T ≤ 50, 1 ≤ |S| ≤ 12345

-----Example-----Input
3
a.ba
cb.bc
a.b

Output
abba
cbabc
-1

-----Explanation-----
In example 1, you can create a palindrome by filling the faded character by 'b'.
In example 2, you can replace the faded character by any character from 'a' to 'z'. We fill it by 'a', as it will generate the lexicographically smallest palindrome.
In example 3, it is not possible to make the string s a palindrome.

import sys
import math

def main(arr):

    n=len(arr)-1

    for i in range(len(arr)//2):

        a=arr[i]
        b=arr[n-i]
        if a!=b and a!="." and b!=".":
            return "-1"
        if a=="." and b==".":

            arr[i]="a"
            arr[n-i]="a"

        else:

            if a!=".":
                arr[n-i]=a
            elif b!=".":
                arr[i]=b

    if arr[len(arr)//2]==".":
        arr[len(arr)//2]="a"
    return "".join(arr)

for _ in range(int(input())):
    arr=list(input())
    print(main(arr))


Solve in Python:
Chef likes strings a lot but he likes palindromic strings more. Today, Chef has two strings A and B, each consisting of lower case alphabets.

Chef is eager to know whether it is possible to choose some non empty strings s1 and s2 where s1 is a substring of A, s2 is a substring of B such that s1 + s2 is a palindromic string. Here '+' denotes the concatenation between the strings.
Note:
A string is a palindromic string if it can be read same both forward as well as backward. To know more about palindromes click here.

-----Input-----
- First line of input contains a single integer T denoting the number of test cases.
- For each test case:

- First line contains the string A
- Second line contains the string B.

-----Output-----
For each test case, Print "Yes" (without quotes) if it possible to choose such strings s1 & s2. Print "No" (without quotes) otherwise.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ |A|, |B| ≤ 1000

-----Subtasks-----
-  Subtask 1: 1 ≤ |A|, |B| ≤ 10 : ( 40 pts )
-  Subtask 2: 1 ≤ |A|, |B| ≤ 1000 : ( 60 pts )

-----Example-----Input
3
abc
abc
a
b
abba
baab

Output
Yes
No
Yes

-----Explanation-----
- Test 1: One possible way of choosing s1 & s2 is s1 = "ab", s2 = "a" such that s1 + s2 i.e "aba" is a palindrome.
- Test 2: There is no possible way to choose s1 & s2 such that s1 + s2 is a palindrome.
- Test 3: You can figure it out yourself.

# cook your dish here
for i in range(int(input())):
 s1=input()
 s2=input()
 c=0
 for i in s1:
  for j in s2:
   if(i==j):
    c+=1
 if(c>0):
  print('Yes')
 else:
  print('No')


Solve in Python:
Chef likes to play with array elements. His teacher has given him an array problem. But now he is busy as Christmas is coming. So, he needs your help. Can you help him to solve this problem.
You are given an array $(A1,A2,A3……AN)$ of length $N$. You have to create an another array using the given array in the following ways:

For each valid i, the ith element of the output array will be the sum of the ith element and (A[i])th element if $A[i]$ is less equal $N$.

Other wise for each valid i following the step below

i) Divide the value of $A[i]$ by 2 untill it will be less than$N$.

ii) then find the difference ($D$) between $N$ and $A[i]$.

iii) the ith element of the output array will be $Dth$ element.

-----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 $A1,A2,…,AN$.

-----Output:-----
- For each testcase, print new array in each line.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$
- $1\leq A1,A2.....AN \leq 10^7$

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

5

2 4 5 7 9

4

5 4 2 3

-----Sample Output:-----
6 11 14 4 2

4 7 6 5

-----EXPLANATION:-----
For 1st test case: A1 = 2+4 =6, A2 = 4+7 =11 , A3 = 5+9 =14 , A4 > N (5) ,So A4/2 = 3 then A4 = A[5 -3] , A4=A[2]=4, And A5 =A[1]=2. Then array becomes 6,11,14,4,2.

for i in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    ans=[0 for i in range(n)]
    for i in range(n):
        if a[i]<=n:
            ans[i]=a[i]+a[a[i]-1]
        else:
            x=a[i]
            while x>=n:
                x//=2
            ans[i]=a[n-x-1]
    print(*ans)


Solve in Python:
Chef likes to play with big numbers. Today, he has a big positive integer N. He can select any two digits from this number (the digits can be same but their positions should be different) and orders them in any one of the two possible ways. For each of these ways, he creates a two digit number from it (might contain leading zeros). Then, he will pick a character corresponding to the ASCII value equal to this number, i.e. the number 65 corresponds to 'A', 66 to 'B' and so on till 90 for 'Z'. Chef is only interested in finding which of the characters in the range 'A' to 'Z' can possibly be picked this way.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The first line of the input contains an integer N.

-----Output-----
For each test case, output a string containing characters Chef can pick in sorted order If the resulting size of string is zero, you should output a new line.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10100000

-----Subtasks-----
- Subtask #1 (40 points) N ≤ 1010
- Subtask #2 (60 points) Original Constraints

-----Example-----
Input:
4
65
566
11
1623455078

Output:
A
AB

ACDFGHIJKLNPQRSTUVW

-----Explanation-----
Example case 1. Chef can pick digits 6 and 5 and create integers 56 and 65. The integer 65 corresponds to 'A'.
Example case 2. Chef can pick digits 6 and 5 and create 'A' as it equals 65. He can pick 6 and 6 (they are picked from position 2 and position 3, respectively) to create 'B' too. Hence answer is "AB".
Example case 3. It's not possible to create any character from 'A' to 'Z'. Hence, we just print a new line.

# cook your dish here
from collections import Counter
t=int(input())
for i in range(t):
 s=input()
 c=Counter(s)
 l=[]
 for item in list(c.keys()):
  if(c[item]>=2):
   l.append(item)
   l.append(item)
  else:
   l.append(item)
 l=[int(k) for k in l]
 ans=""

 for j in range(len(l)):
  for k in range(j+1,len(l)):
   a=10*l[j]+l[k]
   b=10*l[k]+l[j]
   if(a>=65 and a<=90):
    ans+=str(chr(a))
   if(b>=65 and b<=90):
    ans+=str(chr(b))
 c=Counter(ans)
 l=list(c.keys())
 l.sort()
 ans=''
 for item in l:
  ans+=item
 print(ans)


Solve in Python:
Chef likes to solve difficult tasks. This time, he tried to solve the Big Famous Unsolvable $A+B=C$. One of his friends played a prank on Chef and randomly shuffled the bits in $A$ and $B$ (independently in each number). However, the funny thing is that the sum of the resulting numbers remained $C$ even after shuffling.
Chef is now wondering: in how many ways is it possible to shuffle the bits of $A$ and the bits of $B$ such that their sum after shuffling is equal to $C$? Let's denote the integers obtained by shuffling the bits of $A$ and $B$ by $A_s$ and $B_s$ respectively; two ways $(A_{s1}, B_{s1})$ and $(A_{s2}, B_{s2})$ are considered distinct if $A_{s1} \neq A_{s2}$ or $B_{s1} \neq B_{s2}$.
It is allowed to add any number (possibly zero) of leading zeroes, i.e. bits $0$, to $A$ and any number of leading zeroes to $B$ before shuffling the bits.

-----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 three space-separated integers $A$, $B$ and $C$.

-----Output-----
For each test case, print a single line containing one integer — the number of ways to shuffle the bits.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le A, B, C \le 10^9$
- $A+B = C$

-----Subtasks-----
Subtask #1 (50 points): $1 \le A, B, C \le 10^5$
Subtask #2 (50 points): original constraints

-----Example Input-----
2
1 2 3
369 428 797

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

-----Explanation-----
Example case 1: We can consider $A=01$ and $B=10$ in binary. Then, there are two possible ways: swapping the two bits of $A$ and the two bits of $B$ ($A_s=10$, $B_s=01$ in binary, $2$ and $1$ in decimal representation) or not shuffling any bits.

import numpy as np
N = 32;

def calc(i, na, nb, isOne):
 if na < 0 or nb < 0: return 0
 if i == len(c): return not na and not nb and not isOne
 ret = dp[i][na][nb][int(isOne)]

 if ret != -1: return ret
 ret = 0

 if isOne:
  if c[i] == '0':
   ret += calc(i+1, na-1, nb, True)
   ret += calc(i+1, na, nb-1, True)
  else:
   ret += calc(i+1, na, nb, False)
   ret += calc(i+1, na-1, nb-1, True)
 else:
  if c[i] == '0':
   ret += calc(i+1, na, nb, False);
   ret += calc(i+1, na-1, nb-1, True)
  else:
   ret += calc(i+1, na-1, nb, False)
   ret += calc(i+1, na, nb-1, False)

 dp[i][na][nb][int(isOne)] = ret
 return ret

t = int(input())
for _ in range(t):
 a, b, c = list(map(int, input().split()))
 c = "{0:b}".format(c)[::-1]
 x = "{0:b}".format(a).count('1')
 y = "{0:b}".format(b).count('1')
 dp = np.array([-1] * N * N * N * 2).reshape(N, N, N, 2)
 print(calc(0, x, y, False))


Solve in Python:
Chef likes to travel a lot. Every day Chef tries to visit as much cities as possible. Recently he had a quite a few trips of great Chefland for learning various recipes. Chefland had N cities numbered from 1 to N. People in Chefland are very friendly, friendliness of i-th city is given by Fi.

Before starting of each trip, Chef's initial enjoyment is 1 unit. Whenever he visits a city with friendliness Fi, his enjoyment gets multiplied by Fi units.

City 1 is the home city of Chef. He starts each trip from his home city. Before starting a trip, he chooses a parameter R which denotes that he will start from city 1, and go to city 1 + R, then to 1 + 2 * R, then to 1 + 3 * R, till 1 + i * R such that i is largest integer satisfying 1 + i * R ≤ N.

Now, Chef wants you to help him recreate his visit of the cities. Specifically, he will ask you Q queries, each of which can be of following two types.

- 1 p f : friendliness of p-th city changes to f, i.e. Fp = f
- 2 R   : Find out the total enjoyment Chef will have during this trip. As Chef does not like big numbers, he just asks you to output two things, first digit of the enjoyment and value of enjoyment modulo 109 + 7.

-----Input-----
There is a single test case.
First line of input contains a single integer N, denoting number of cities in Chefland.
Second line of the input contains N space separated integer - F1, F2, ..., FN, denoting the friendliness of the cities in order from 1 to N.
Next line contains an integer Q, denoting number of queries.

For each of the next Q queries, each line corresponds to one of the two types of the query. First there will be an integer denoting the type of the query, followed by the actual query. For query of type 1, there will be three space separated integers "1 p f" as defined above. For query of type 2, there will be two space separated integers "2 R ", as defined above.

-----Output-----
For each query of type 2, output two space separated integers, first digit of Chef's enjoyment in this trip followed by the value of...

import math

def solve(array, r):
 i, res, tmp1, tmp2 = 0, 1, 1, 1
 while i * r < len(array):
  res *= array[i * r]
  res %= 10**9 + 7
  tmp1 = array[i * r] / float(10 ** int(math.log(array[i * r], 10)))
  tmp2 *= tmp1
  i += 1
 first_digit = int(tmp2 // 10 ** int(math.log(tmp2, 10)))
 return ' '.join((str(first_digit), str(res)))

def frjump():
 N = int(input())
 friendliness = list(map(int, input().split()))
 Q = int(input())
 for _ in range(Q):
  query = list(map(int, input().split()))
  if query[0] == 1:
   friendliness[query[1]-1] = query[2]
  else:
   types, R = query
   print(solve(friendliness, R))

def __starting_point():
 frjump()
__starting_point()


Solve in Python:
Chef likes to travel very much. He plans some travel routes and wants to know their lengths. He hired you to make these calculations. But be careful, some of the routes are incorrect. There may be some misspelling in city names or there will be no road between some two consecutive cities in the route. Also note that Chef hates to visit the same city twice during his travel. Even the last city should differ from the first. Two consecutive cities in the route should also be different. So you need to check these conditions for the given routes too.

You will be given the list of all cities and all roads between them with their lengths. All roads are one-way. Also you will be given the list of all travel routes that Chef plans. For each route you should check whether it is correct and find its length in this case.

-----Input-----

The first line contains positive integer N, the number of cities. The second line contains space separated list of N strings, city names. All city names are distinct.

The third line contains non-negative integer M, the number of available roads. Each of the next M lines describes one road and contains names C1 and C2 of two cities followed by the positive integer D, the length of the one-way road that connects C1 with C2. It is guaranteed that C1 and C2 will be correct names of two different cities from the list of N cities given in the second line of the input file. For each pair of different cities there is at most one road in each direction and each road will be described exactly once in the input file.

Next line contains positive integer T, the number of travel routes planned by the Chef. Each of the next T lines contains positive integer K followed by K strings, names of cities of the current route. Cities are given in order in which Chef will visit them during his travel.

All strings in the input file composed only of lowercase, uppercase letters of the English alphabet and hyphens. Each string is non-empty and has length at most 20. If some line of the input file contains...

def main():
 n = eval(input())
 city = input().split()
 m = eval(input())
 mapp = {}
 for c in city:
  mapp[c] = [0]*n
 while m:
  m-=1
  road = input().split()
  temp = mapp[road[0]]
  temp[city.index(road[1])] = int(road[-1])
  mapp[road[0]] = temp
 t=eval(input())
 while t:
  t-=1
  dist = 0
  v = [0]*n #visited
  route = input().split()
  if route[0] == '1':
   if route[-1] in city:
    print(dist)
   else:
    print('ERROR')
  else:
   for r in range(1,int(route[0])+1):
    if (route[r] not in city) or v[city.index(route[r])]:
     dist = 'ERROR'
     break
    elif r>1:
     if mapp[route[r-1]][city.index(route[r])]:
      dist+= mapp[route[r-1]][city.index(route[r])]
     else:
      dist = 'ERROR'
      break
    v[city.index(route[r])] = 1
   print(dist)
main()


Solve in Python:
Chef likes toys. His favourite toy is an array of length N. This array contains only integers. He plays with this array every day. His favourite game with this array is Segment Multiplication. In this game, the second player tells the left and right side of a segment and some modulo. The first player should find the multiplication of all the integers in this segment of the array modulo the given modulus. Chef is playing this game. Of course, he is the first player and wants to win all the games. To win any game he should write the correct answer for each segment. Although Chef is very clever, he has no time to play games. Hence he asks you to help him. Write the program that solves this problem.

-----Input-----
The first line of the input contains an integer N denoting the number of elements in the given array. Next line contains N integers Ai separated with spaces. The third line contains the number of games T. Each of the next T lines contain 3 integers Li, Ri and Mi, the left side of the segment, the right side of segment and the modulo.

-----Output-----
For each game, output a single line containing the answer for the respective segment.

-----Constrdaints-----
- 1 ≤ N ≤ 100,000
- 1 ≤ Ai ≤ 100
- 1 ≤ T ≤ 100,000
- 1 ≤ Li ≤ Ri ≤ N
- 1 ≤ Mi ≤ 109

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

Output:
2
2
0
120

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def getPrimeFactors(num):
    arr = [0]*25
    for index,i  in enumerate(primes):
        if i > num:
            break
        while num%i == 0:
            arr[index]+=1
            num //= i
    return arr

def findPower(arr, mod):
    ans = 1
    for index,i in enumerate(arr):
        if i != 0:
            ans*=pow(primes[index], i, mod)
            if ans > mod:
                ans%=mod
    return ans%mod

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

cumarr = []
temp = [0]*25
cumarr.append(temp.copy())

for i in arr:
    for index,p  in enumerate(primes):
        if p > i:
            break
        while i%p == 0:
            temp[index]+=1
            i //= p
    cumarr.append(temp.copy())

for x in range(int(input())):
    l, r, m = map(int, input().strip().split())
    ans = findPower([x-y for x,y in zip(cumarr[r], cumarr[l-1])], m)
    print(ans)


Solve in Python:
Chef lives in a big apartment in Chefland. The apartment charges maintenance fees that he is supposed to pay monthly on time. But Chef is a lazy person and sometimes misses the deadlines. The apartment charges 1000 Rs per month as maintenance fees. Also, they also charge a one-time fine of 100 Rs for each of the late payments. It does not matter how late the payment is done, the fine is fixed to be Rs.100.
Chef has been living in the apartment for N months. Now, he wants to switch the apartment, so he has to pay the entire dues to the apartment. The deadline for the N-th month is also over. From his bank statement, he finds the information whether he paid apartment rent for a particular month for not. You are given this information by an array A of size N, where Ai (can be either 0 or 1) specifies whether he has paid the 1000Rs in the i-th month or not. Assume that Chef paid the fees in the i-th month, then this fees will be considered for the earliest month for which Chef has not yet paid the fees.

For example, assume Chef did not pay any money in first month and 1000Rs in the second month. Then this rent of 1000Rs will be considered for 1st month. But this counts as late payment for the first month's fees, and hence he will have to pay Rs. 100 for that. And since the payment he made in the second month is not accounted for the second month, but rather for the first month, he will incur a fine of Rs.100 even for the second month.

He has not paid any of the fines so far. Can you please help in finding Chef total due (all the fines, plus all the unpaid maintenance fees) that he has to pay to apartment?

-----Input-----
First line of the input contains an integer T denoting number of test cases. The description of T test cases follows.
The first line of each test cases contains an integer N denoting the number of months for which you have to calculate the total amount of money that Chef has to pay at the end of the n month to clear all of his dues.
Next line of each test case contains N space separated...

for i in range(int(input())):
    a=int(input())
    b=input().split()
    if '0' in b:
        print(100*(a-b.index('0'))+b.count('0')*1000)
    else:
        print(0)


Solve in Python:
Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Chef has a positive integer N. He can apply any of the following operations as many times as he want in any order:

-  Add 1 to the number N.

-  Take some digit of N and replace it by any non-zero digit.

-  Add any non-zero leading digit to N.

Find the minimum number of operations that is needed for changing N to the lucky number.

-----Input-----
The first line contains a single positive integer T, the number of test cases. T test cases follow. The only line of each test case contains a positive integer N without leading zeros.

-----Output-----
For each T test cases print one integer, the minimum number of operations that is needed for changing N to the lucky number.

-----Constraints-----

1 ≤ T ≤ 10

1 ≤ N < 10100000

-----Example-----
Input:
3
25
46
99

Output:
2
1
2

for i in range(int(input())):
    count = 0
    num = input().strip()
    for i in num:
        if i!= '4' and i!='7':
            count+=1
    print(count)


Solve in Python:
Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Let F(X) equals to the number of lucky digits in decimal representation of X. Chef wants to know the number of such integers X, that L ≤ X ≤ R and F(X) is a lucky number. Help him and calculate that number modulo 109+7.

-----Input-----
First line contains one integer T, the number of test cases. Each of the following T lines contains two space separated positive integers L and R.

-----Output-----
For each of the T test cases print one integer, the number of such X, that L ≤ X ≤ R and F(X) is a lucky number, modulo 1000000007.

-----Constraints-----

1 ≤ T ≤ 10

1 ≤ L ≤ R ≤ 101000

-----Example-----
Input:
4
1 100
1 10000
1 100000
4444 4447

Output:
0
16
640
2

-----Notes-----
First test case: of course, any number of less than 4 digits can't contain lucky number of lucky digits, so the answer is 0.

Second test case: 16 required numbers are 4444 4447 4474 4477 4744 4747 4774 4777 7444 7447 7474 7477 7744 7747 7774 7777.

Third test case: there are 640 required lucky numbers. Some of them are 4474, 14747, 41474, 77277, 44407, 74749.

Fourth test case: the only two required numbers are 4444 and 4447.

lucky = {4, 774, 7, 744, 777, 74, 747, 44, 77, 47, 474, 444, 477, 447}
from functools import lru_cache
import sys
sys.setrecursionlimit(10 ** 6)
mod = 10 ** 9 + 7
fact = [1]
for i in range(1, 1001):
    fact.append(fact[-1] * i % mod)
inv = [pow(i, mod-2, mod) for i in fact]
C = lambda k, n: fact[n] * inv[n-k] * inv[k] % mod
def f(n):
    n = [int(x) for x in n]
    @lru_cache(None)
    def dp(pos, cnt, free):
        if cnt > 777:
            return 0
        diff = len(n) - pos
        ans = 0
        if free:
            for i in lucky:
                i -= cnt
                if 0 <= i <= diff:
                    ans += C(i, diff) * pow(2, i, mod) * pow(8, diff - i, mod)
                    ans %= mod
            return ans
        if pos == len(n):
            return int(cnt in lucky)
        for i in range(10 if free else n[pos]+1):
            ans += dp(pos+1, cnt + int(i == 4 or i == 7), free or i < n[pos])
            ans %= mod
        return ans
    return dp(0, 0, 0)

t = int(input())
for _ in range(t):
    l, r = input().split()
    l = str(int(l) -1)
    print((f(r) - f(l)) % mod)


Solve in Python:
Chef loves saving money and he trusts none other bank than State Bank of Chefland. Unsurprisingly, the employees like giving a hard time to their customers. But instead of asking them to stand them in long queues, they have weird way of accepting money.
Chef did his homework and found that the bank only accepts the money in coins such that the sum of the denomination with any previously deposited coin OR itself can't be obtained by summing any two coins OR double of any coin deposited before. Considering it all, he decided to start with $1$ Chefland rupee and he would keep choosing smallest possible denominations upto $N$ coins. Since chef is busy with his cooking, can you find out the $N$ denomination of coins chef would have to take to the bank? Also find the total sum of money of those $N$ coins.

-----Input:-----
- First line has a single integer $T$ i.e. number of testcases.
- $T$ lines followed, would have a single integer $N$ i.e. the number of coins the chef is taking.

-----Output:-----
- Output for $i$-th testcase ($1 ≤ i ≤ T$) would have 2 lines.
- First line would contain $N$ integers i.e. the denomination of coins chef would deposit to the bank.
- Second line would contain a single integer i.e. the sum of all the coins chef would deposit.

-----Constraints:-----
- $1 ≤ T ≤ 700$
- $1 ≤ N ≤ 700$

-----Subtasks:-----
- $20$ points: $1 ≤ T, N ≤ 80$
- $70$ points: $1 ≤ T, N ≤ 500$
- $10$ points: $1 ≤ T, N ≤ 700$

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

-----Sample Output:-----
1
1
1 2
3
1 2 4
7
1 2 4 8
15

-----Explanation:-----
For testcase 1: First coin is stated to be 1, hence for $N$ = 1, 1 is the answer.
For testcase 2: Since chef chooses the lowest possible denomination for each $i$-th coin upto $N$ coins, second coin would be 2. Only sum possible with N = 1 would be 1+1 = 2. For N = 2, $\{1+2,  2+2\}$ $\neq$ $2$.
For testcase 3: With first two coins being 1 and 2, next coin couldn't be 3 because 3+1 = 2+2, but $\{4+1,  4+2,  4+4\}$ $\neq$ $\{1+1,  1+2,  2+2\}$

#import sys,math,collections
import math,sys
#from itertools import permutations,combinations

def file():
	sys.stdin = open('input.py', 'r')
	sys.stdout = open('output.py', 'w')

def get_array():
	l=list(map(int, input().split()))
	return l
#file()
def main():
	#a,b=map(int, input().split())
	for _ in...


Solve in Python:
Chef loves to play chess, so he bought a new chessboard with width M$M$ and height N$N$ recently.
Chef considers a chessboard correct if its width (number of columns) is equal to its height (number of rows) and each cell has no side-adjacent cell of the same color (this is the so-called "chess order" which you can see in real-world chessboards). Chef's chessboard does not have to be a correct chessboard (in particular, it may have N≠M$N \neq M$).
A sub-board of Chef's chessboard is a rectangular piece of this board with an arbitrarily chosen top left and bottom right cell (possibly equal to the original chessboard). Every sub-board is also a chessboard.
Chef can invert some cells; inverting a cell means changing its color from white to black or from black to white. After inverting those cells, he wants to cut the maximum correct sub-board out of the original chessboard.
Chef has not yet decided how many cells he would like to invert. Now he wonders about the answers to Q$Q$ question. In the i$i$-th question (1≤i≤Q$1 \le i \le Q$), he is allowed to invert at most ci$c_i$ cells (possibly zero); he would like to know the side length of the largest possible correct sub-board of his chessboard. Help Chef answer these questions.

-----Input-----
- The first line of the input contains two space-separated integers N$N$ and M$M$.
- N$N$ lines follow. For each valid i$i$, the i$i$-th of these lines contains a string with length M$M$ describing the i$i$-th row of Chef's chessboard. Each character of this string is either '0', representing a black cell, or '1', representing a white cell.
- The next line contains a single integer Q$Q$.
- The last line contains Q$Q$ space-separated integers c1,c2,…,cQ$c_1, c_2, \dots, c_Q$.

-----Output-----
For each question, print a single line containing one integer — the maximum size of a correct sub-board.

-----Constraints-----
- 1≤N,M≤200$1 \le N, M \le 200$
- 1≤Q≤105$1 \le Q \le 10^5$
- 0≤ci≤109$0 \le c_i \le 10^9$ for each valid i$i$

-----Subtasks-----
Subtask #1 (20 points):
-...

n,m = [int(i) for i in input().split()]
sqsets = list(range(2,min(n,m)+1))
ci = []
for i in range(n):
    ci.append(list(input()))
cc = [[0 for i in range(m+1)] for j in range(n+1)]
def cache_creation_part(x,y):
    cc[y][x] = cc[y][x - 1] + cc[y - 1][x] - cc[y - 1][x - 1]
    if (y + x) % 2 == 0:
        cc[y][x] += int(ci[y - 1][x - 1] != '1')
    else:
        cc[y][x] += int(ci[y - 1][x - 1] != '0')

def cache_creation(m,n):
    for y in range(1,n+1):
        for x in range(1, m + 1):
            cache_creation_part(x,y)

def operation(x,y,k):
    return cc[y + k][x + k] + cc[y][x] - cc[y + k][x] - cc[y][x + k]

c = 0
kd = {k:c for k in sqsets}
def kd_creation(m,n,sqsets):
    cache_creation(m,n)
    for k in sqsets:
        kd[k] = (10**9)+1
        for y in range(n-k+1):
            for x in range(m-k+1):
                cu = operation(x,y,k)
                kd[k] = min(kd[k], cu, k*k-cu)
kd_creation(m,n,sqsets)
del cc
del ci
del sqsets
tc = int(input())
tc = [int(x) for x in input().split()]
for u in tc:
    p = 0
    for i in kd:
        if kd[i] <= u:
            p = max(i, p)
    print(p)


Solve in Python:
Chef loves to play games. Now he plays very interesting game called "Segment". At the beginning Chef has segment [0, X] and no points on it. On each step Chef chooses the subsegment of maximal length possible such as it contains no points on it. If there are more than one such subsegment Chef chooses the one with the minimal left coordinate. Once Chef chosed the subsegment he put the point in it's middle and the step is over.
Help Chef to define the coordinate of the point he will put on the K-th step.

-----Input-----
- The first line contains integer T - number of test cases.
- Each of next T lines contains two integers X and K.

-----Output-----
- For each test case in a single line print single double number - the coordinate of the K-th point Chef will put. Answer will be considered as correct if absolute difference between the answer and correct answer is less or equal 10^(-6).

-----Constraints-----
- 1 ≤ T ≤ 10^5
- 1 ≤ X ≤ 10^9
- 1 ≤ K ≤ 10^12

-----Subtasks-----
- Subtask 1: T ≤ 10; X, K ≤ 20. Points: 15
- Subtask 2: T ≤ 10; X ≤ 10^6, K ≤ 2*10^5. Points: 25
- Subtask 3: T ≤ 10^5; X ≤ 10^9, K ≤ 10^12. Points: 60

-----Example-----
Input:
4
10 1
10 2
10 3
1000000000 1234567
Output:
5.0000
2.5000
7.5000
177375316.6198730500000000

-----Explanation-----
You can see the points coordinates for the third sample from first two samples.

T = int(input())
for _ in range(T):
 X, K = [int(x) for x in input().split()]

 k, x, y = 1, 2, 1
 while x <= K:
  k, x, y = k + 1, x * 2, x

 print((X/ x) + (K - y) * X/ y)


Solve in Python:
Chef loves to play with arrays by himself. Today, he has an array A consisting of N distinct integers. He wants to perform the following operation on his array A.

- Select a pair of adjacent integers and remove the larger one of these two. This decreases the array size by 1. Cost of this operation will be equal to the smaller of them.

Find out minimum sum of costs of operations needed to convert the array into a single element.

-----Input-----
First line of input contains a single integer T denoting the number of test cases. First line of each test case starts with an integer N denoting the size of the array A. Next line of input contains N space separated integers, where the ith integer denotes the value Ai.

-----Output-----
For each test case, print the minimum cost required for the transformation.

-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ N ≤ 50000
- 1 ≤ Ai ≤ 105

-----Subtasks-----
- Subtask 1 : 2 ≤ N ≤ 15 : 35 pts
- Subtask 2 : 2 ≤ N ≤ 100 : 25 pts
- Subtask 3 : 2 ≤ N ≤ 50000 : 40 pts

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

Output
3
4

-----Explanation-----Test 1 :  Chef will make only 1 move: pick up both the elements (that is, 3 and 4), remove the larger one (4), incurring a cost equal to the smaller one (3).

# cook your dish here
for i in range(int(input())):
 n=int(input())
 lis=list(map(int,input().split()))
 print(min(lis)*(n-1))


Solve in Python:
Chef loves to play with iron (Fe) and magnets (Ma). He took a row of $N$ cells (numbered $1$ through $N$) and placed some objects in some of these cells. You are given a string $S$ with length $N$ describing them; for each valid $i$, the $i$-th character of $S$ is one of the following:
- 'I' if the $i$-th cell contains a piece of iron
- 'M' if the $i$-th cell contains a magnet
- '_' if the $i$-th cell is empty
- ':' if the $i$-th cell contains a conducting sheet
- 'X' if the $i$-th cell is blocked
If there is a magnet in a cell $i$ and iron in a cell $j$, the attraction power between these cells is $P_{i,j} = K+1 - |j-i| - S_{i,j}$, where $S_{i,j}$ is the number of cells containing sheets between cells $i$ and $j$. This magnet can only attract this iron if $P_{i, j} > 0$ and there are no blocked cells between the cells $i$ and $j$.
Chef wants to choose some magnets (possibly none) and to each of these magnets, assign a piece of iron which this magnet should attract. Each piece of iron may only be attracted by at most one magnet and only if the attraction power between them is positive and there are no blocked cells between them. Find the maximum number of magnets Chef can choose.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$.
- The second line contains a single string $S$ with length $N$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum number of magnets that can attract iron.

-----Constraints-----
- $1 \le T \le 2,000$
- $1 \le N \le 10^5$
- $0 \le K \le 10^5$
- $S$ contains only characters 'I', 'M', '_', ':' and 'X'
- the sum of $N$ over all test cases does not exceed $5 \cdot 10^6$

-----Subtasks-----
Subtask #1 (30 points): there are no sheets, i.e. $S$ does not contain the character ':'
Subtask #2 (70 points): original constraints

-----Example Input-----
2
4 5
I::M
9...

def solve(string,k):
 ind = 0
 iron,mag = [],[]
 for i in string:
  if i==':':
   ind+=1
  elif i=='I':
   iron.append(ind)
  elif i=="M":
   mag.append(ind)
  ind+=1
 i,j = 0,0
 li = len(iron)
 lm = len(mag)
 ans = 0
 while i<li and j<lm:
  if abs(iron[i]-mag[j])<=k:
   ans+=1
   i+=1
   j+=1
  else:
   if iron[i]>mag[j]:
    j+=1
   else:
    i+=1
 return ans
for _ in range(int(input())):
 ans = 0
 n,k = list(map(int,input().split()))
 s = input()
 real = [i for i in s.split("X") if len(i)>0]
 ans+=sum(solve(string,k)for string in real)
 print(ans)


Solve in Python:
Chef loves triangles. But the chef is poor at maths. Given three random lengths Chef wants to find if the three sides form a right-angled triangle or not. Can you help Chef in this endeavour?

-----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, three Integers $A,B and C$

-----Output:-----
For each test case, output in a single line "YES" if it is possible to form a triangle using the given numbers or "NO" if it is not possible to form a triangle.

-----Constraints-----
- $1 \leq T \leq 1000000$
- $0 \leq A,B,C \leq 100$

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

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

-----EXPLANATION:-----
3,4,5 forms a right-angled triangle. 1, 3 and 4 does not form a right-angled triangle.

#!/usr/bin/env python3
# coding: utf-8
#Last Modified: 23/Feb/20 12:23:37 PM

import sys

def main():
    def checkValidity(a, b, c):
        if (a + b <= c) or (a + c <= b) or (b + c <= a) :
            return False
        else:
            return True
    def checkrt(a, b, c):
        if a**2 + b**2 == c**2 or a**2+c**2==b**2 or b**2+c**2==a**2:
            return True
        return False
    for tc in range(int(input())):
        a, b, c=get_ints()
        if checkValidity(a, b, c):
            if checkrt(a, b, c):
                print('YES')
            else:
                print('NO')
        else:
            print('NO')

get_array = lambda: list(map(int, sys.stdin.readline().split()))

get_ints = lambda: list(map(int, sys.stdin.readline().split()))

input = lambda: sys.stdin.readline().strip()

main()


Solve in Python:
Chef made $N$ pieces of cakes, numbered them $1$ through $N$ and arranged them in a row in this order. There are $K$ possible types of flavours (numbered $1$ through $K$); for each valid $i$, the $i$-th piece of cake has a flavour $A_i$.
Chef wants to select a contiguous subsegment of the pieces of cake such that there is at least one flavour which does not occur in that subsegment. Find the maximum possible length of such a subsegment of cakes.

-----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 integers $N$ and $K$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum length of a valid subsegment.

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

-----Subtasks-----
Subtask #1 (50 points):
- $N \le 10^3$
- $K = 2$
- the sum of $N$ over all test cases does not exceed $10^4$
Subtask #2 (50 points): original constraints

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

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

for T in range(int(input())):
 n,k=list(map(int,input().split()))
 a=list(map(int,input().split()))
 if(len(set(a))<k):
  print(len(a))
 else:
  f,t,c=[],[],1
  key=a[0]
  for i in range(1,n):
   if(a[i]==key):
    c+=1
   else:
    f.append(c)
    t.append(key)
    key=a[i]
    c=1
  f.append(c)
  t.append(key)
  check=[0]*(k+1)
  i,start,l,m,uni=0,0,0,0,0
  while(i < len(t) and start < len(t)):
   check[t[i]]+=1
   if(check[t[i]]==1):
    uni+=1
   if(uni==k):
    check[t[i]]-=1
    m=max(m,l)
    check[t[start]]-=1
    if(check[t[start]]==0):
     uni-=1
    l-=f[start]
    start+=1
    uni-=1
    continue
   l+=f[i]
   i+=1
  m=max(m,l)
  print(m)


Solve in Python:
Chef made two laddus with sweetness X and Y respectively. Cheffina comes and sees the chef created two laddus with different sweetness (might be same). Cheffina has the magical power to make the sweetness of laddus equal. Cheffina requires 1 unit of power to increase the sweetness of laddu by its original value i.e. 1 unit to convert Z to 2Z and 2 unit to convert Z to 3Z and so on… How many units of power does cheffina want to make the sweetness equal?

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

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

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq X,Y \leq 10^5$

-----Sample Input:-----
2
2 2
4 6

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

-----EXPLANATION:-----
For 1) Sweetness are same so no need to use power.
For 2)
1st laddu
2 Unit power = 4 -> 12
2nd Laddu
1 Unit power = 6 -> 12
After using total 3 unit power sweetness of both laddus are same.

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

    t=math.gcd(n,m)
    #print("t ",t)
    t2=(n*m//t)
    #print("t2 ",t2)
    print(t2//n-1 +t2//m-1)


Solve in Python:
Chef organised a chess tournament, which spanned over $M$ months. There were $N$ players, and player $i$ was rated $R_i$ before the start of the tournament. To see the progress of the players, he noted their rating changes at the end of each month.
After the tournament, FIDE asked Chef to find the number of players whose peak rating and peak ranking did not occur in the same month. In other words, Chef was asked to find the ratings and ranking of each player after each of the $M$ months. Then, using this data, he should find the number of players, such that the month in which they achieved their highest rating over all the months, was different from the month in which they achieved their best rank (based on ratings), over all the months. Note that we do not consider the initial rating/ranking, but only the rating and rankings after each of the $M$ months.
For a particular player, if there are multiple peak rating or peak ranking months, Chef was to consider the earliest of them. If multiple players had the same rating at the end of some month, they were to be given the same rank. For example, if there were $5$ players, and their ratings at the end of some month were $(2600$, $2590$, $2600$, $2600$ and $2590)$, players $1$, $3$ and $4$ were to be given the first rank, while players $2$ and $5$ should be given the fourth rank.
As Chef hates statistics, he asks you, his friend, to help him find this. Can you help Chef?

-----Input:-----
- The first line contains an integer $T$, the number of test cases.
- The first line of each test case contains two space-separated integers $N$ and $M$, the number of players and the number of months that the tournament spanned over.
- The second line of each test case contains $N$ space-separated integers, $R_1, R_2, \ldots, R_N$ denoting the initial ratings of the players, i.e., their ratings before the start of the tournament.
- The next $N$ lines each contain $M$ space-separated integers. The $j^{th}$ integer of the $i^{th}$ line, $C_{i,j}$ denotes the rating change of the...

def getRanking(ratingList,n,m):
 rank = []
 array2d = [[None for i in range(n)] for j in range(m)]
 # print(array2d)
 for i in range(m): #months
  helper2d = [[None for i in range(2)] for j in range(n)]
  # print(helper2d)
  for j in range(n):
   helper2d[j][0] = j+1
   helper2d[j][1] = ratingList[j][i]
  # helper2d = zip(*helper2d)
  helper2d = sorted(helper2d,reverse=True,key=lambda x:x[1])
  arr = [x for x in range(1,n+1)]
  for k in range(1,n):
   if helper2d[k][1] == helper2d[k-1][1]:
    arr[k] = arr[k-1]
  # print(helper2d)
  for l in range(n):
   # print("l and i",l,i)
   array2d[i][helper2d[l][0]-1] = arr[l]
 for l in range(n):
  minimum = float('inf')
  minimumIndex = None
  for o in range(m):
   if minimum > array2d[o][l]:
    minimum = array2d[o][l]
    minimumIndex = o+1

  rank.append(minimumIndex)

  # helper2d = zip(*helper2d)
 # print(array2d)
 # print(arr)
 # print(rank)

 return rank

t = int(input())
for _ in range(t):
 n,m = list(map(int,input().split()))
 r = list(map(int,input().split()))
 c = [ None for j in range(n)]
 for i in range(n):
  c[i] = list(map(int,input().split()))
 ratingList = [None for i in range(n)]
 # print(ratingList)
 for i in range(n):
  temp = []
  temp.append(r[i]+c[i][0])
  for j in range(1,m):
   temp.append(temp[j-1]+c[i][j])
  ratingList[i] = temp
 playerRatings = []
 for i in range(n):
  maximum = float('-inf')
  maximumMonth = None
  for j in range(m):
   if ratingList[i][j] > maximum:
    maximum = ratingList[i][j]
    maximumMonth = j+1
  playerRatings.append(maximumMonth)
 playerRanking = getRanking(ratingList,n,m)
 count = 0
 for i in range(n):
  if playerRanking[i] != playerRatings[i]:
   count += 1
 print(count)
 # print(playerRatings)
 # print(playerRanking)


Solve in Python:
Chef owns an icecream shop in Chefland named scoORZ. There are only three types of coins in Chefland: Rs. 5, Rs. 10 and Rs. 15. An icecream costs Rs. 5.
There are $N$ people (numbered $1$ through $N$) standing in a queue to buy icecream from scoORZ. Each person wants to buy exactly one icecream. For each valid $i$, the $i$-th person has one coin with value $a_i$. It is only possible for someone to buy an icecream when Chef can give them back their change exactly ― for example, if someone pays with a Rs. 10 coin, Chef needs to have a Rs. 5 coin that he gives to this person as change.
Initially, Chef has no money. He wants to know if he can sell icecream to everyone in the queue, in the given order. Since he is busy eating his own icecream, can you tell him if he can serve all these people?

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

-----Output-----
For each test case, print a single line containing the string "YES" if all people can be served or "NO" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10^3$
- $a_i \in \{5, 10, 15\}$ for each valid $i$

-----Subtasks-----
Subtask #1 (40 points): $a_i \in \{5, 10\}$ for each valid $i$
Subtask #2 (60 points): original constraints

-----Example Input-----
3
2
5 10
2
10 5
2
5 15

-----Example Output-----
YES
NO
NO

-----Explanation-----
Example case 1: The first person pays with a Rs. 5 coin. The second person pays with a Rs. 10 coin and Chef gives them back the Rs. 5 coin (which he got from the first person) as change.
Example case 2: The first person already cannot buy an icecream because Chef cannot give them back Rs. 5.
Example case 3: The first person pays with a Rs. 5 coin. The second person cannot buy the icecream because Chef has only one Rs. 5 coin, but he needs to...

for _ in range(int(input().strip())):
    N = int(input().strip())
    A = list(map(int, input().strip().split(" ")))
    coins = [0, 0]
    f = 1
    for i in A:
        if i == 5:
            coins[0] += 1
        elif i == 10 and coins[0] > 0:
            coins[0] -= 1
            coins[1] += 1
        elif i == 15:
            if coins[1] > 0:
                coins[1] -= 1
            elif coins[0] > 1:
                coins[0] -= 2
            else:
                f = 0
                print("NO")
                break
        else:
            f = 0
            print("NO")
            break
    if f:
        print("YES")


Solve in Python:
Chef played an interesting game yesterday. This game is played with two variables $X$ and $Y$; initially, $X = Y = 0$. Chef may make an arbitrary number of moves (including zero). In each move, he must perform the following process:
- Choose any positive integer $P$ such that $P \cdot P > Y$.
- Change $X$ to $P$.
- Add $P \cdot P$ to $Y$.
Unfortunately, Chef has a bad memory and he has forgotten the moves he made. He only remembers the value of $X$ after the game finished; let's denote it by $X_f$. Can you tell him the maximum possible number of moves he could have made in the 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 and only line of each test case contains a single integer $X_f$.

-----Output-----
For each test case, print a single line containing one integer — the maximum number of moves Chef could have made.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le X_f \le 10^9$

-----Example Input-----
3
3
8
9

-----Example Output-----
3
5
6

-----Explanation-----
Example case 2: One possible sequence of values of $X$ is $0 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 5 \rightarrow 8$.

# cook your dish here
import math
t = int(input())
while(t):
 n = int(input())
 res = 0
 x = 0
 y = 0
 while(x <= n):
  tmp = int(math.sqrt(y))
  tmp += 1
  y += tmp * tmp
  x = tmp
  res += 1

 print(res - 1)

 t -= 1


Solve in Python:
Chef published a blog post, and is now receiving many queries about it. On day $i$, he receives $Q_i$ queries. But Chef can answer at most $k$ queries in a single day.
Chef always answers the maximum number of questions that he can on any given day (note however that this cannot be more than $k$). The remaining questions (if any) will be carried over to the next day.
Fortunately, after $n$ days, the queries have stopped. Chef would like to know the first day during which he has some free time, i.e. the first day when he answered less than $k$ questions.

-----Input:-----
- First line will contain $T$, the number of testcases. Then the testcases follow.
- The first line of each testcase contains two space separated integers $n$ and $k$.
- The second line of each testcase contains $n$ space separated integers, namely $Q_1, Q_2, ... Q_n$.

-----Output:-----
For each testcase, output in a single line the first day during which chef answers less than $k$ questions.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq $ sum of $n$ over all testcases $ \leq 10^5$
- $1 \leq k \leq 10^8$
- $0 \leq Q_i \leq 10^8$

-----Subtasks-----
- Subtask 1 - 20% points - Sum of $Q_i$ over all testcases and days $\leq 3 . 10^6$
- Subtask 2 - 80% points - Original constraints

-----Sample Input:-----
2
6 5
10 5 5 3 2 1
1 1
100

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

-----Explanation:-----
Test Case 1
On the first day, chef answers 5 questions and leaves the remaining 5 (out of the 10) for the future days.
On the second day, chef has 10 questions waiting to be answered (5 received on the second day and 5 unanswered questions from day 1). Chef answers 5 of these questions and leaves the remaining 5 for the future.
On the third day, chef has 10 questions waiting to be answered (5 received on the third day and 5 unanswered questions from earlier). Chef answers 5 of these questions and leaves the remaining 5 for later.
On the fourth day, chef has 8 questions waiting to be answered (3 received on the fourth day and 5 unanswered...

for i in range(int(input())):
 n, k = map(int, input().split())
 arr = list(map(int, input().split()))
 s = sum(arr)
 print(max(int(s/k)+1, n))


Solve in Python:
Chef received a new sequence $A_1, A_2, \ldots, A_N$. He does not like arbitrarily ordered sequences, so he wants to permute the elements of $A$ in such a way that it would satisfy the following condition: there is an integer $p$ ($1 \le p \le N$) such that the first $p$ elements of the new (permuted) sequence are strictly increasing and the last $N-p+1$ elements are strictly decreasing.
Help Chef and find a permutation of the given sequence which satisfies this condition or determine that no such permutation exists. If there are multiple solutions, you may find any one.

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

-----Output-----
For each test case:
- If there is no permutation of $A$ that satisfies the given condition, print a single line containing the string "NO" (without quotes).
- Otherwise, print two lines.
- The first of these lines should contain the string "YES" (without quotes).
- The second line should contain $N$ space-separated integers ― the elements of your permuted sequence.

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

-----Subtasks-----
Subtask #1 (50 points):
- $N \le 10^3$
- $A_i \le 2 \cdot 10^3$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^4$
Subtask #2 (50 points): original constraints

-----Example Input-----
5
4
1 3 2 4
4
1 3 2 4
6
1 10 10 10 20 15
5
1 1 2 2 3
4
1 2 3 3

-----Example Output-----
YES
1 2 3 4
YES
4 3 2 1
NO
YES
1 2 3 2 1
NO

for _ in range(int(input())):
 n = int(input())
 a = list(map(int, input().split()))
 b = set()
 c = []
 for i in a:
  if i in b:
   c.append(i)
  else:
   b.add(i)
 b=list(b)
 b.sort()
 c.sort(reverse=True)
 arr=b[:]+c[:]
 flag=0
 for i in range(len(b)-1,n-1):
  if arr[i]==arr[i+1]:
   flag=1
   print("NO")
   break
 if flag == 0:
  print("YES")
  print(*arr)