Solve in Python:
Chef received a permutation $P_1, P_2, \ldots, P_N$ and also an integer $D$ from his good friend Grux, because Grux was afraid he would forget them somewhere. However, since Grux was just playing with the permutation, it was all shuffled, and Chef only likes sorted permutations, so he decided to sort it by performing some swaps.
Chef wants to use the integer $D$ he just received, so he is only willing to swap two elements of the permutation whenever their absolute difference is exactly $D$. He has limited time, so you should determine the minimum number of swaps he needs to perform to sort the permutation, or tell him that it is impossible to sort it his way.

-----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 $D$.
- The second line contains $N$ space-separated integers $P_1, P_2, \ldots, P_N$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum number of swaps, or $-1$ if it is impossible to sort the permutation.

-----Constraints-----
- $1 \le T \le 20$
- $1 \le N \le 200,000$
- $1 \le D \le N$
- $1 \le P_i \le N$ for each valid $i$
- $P_1, P_2, \ldots, P_N$ are pairwise distinct
- the sum of $N$ over all test cases does not exceed $10^6$

-----Subtasks-----
Subtask #1 (20 points): $D = 1$
Subtask #2 (30 points):
- $N \le 1,000$
- the sum of $N$ over all test cases does not exceed $10,000$
Subtask #3 (50 points): original constraints

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

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

-----Explanation-----
Example case 1: Chef can perform the following swaps in this order:
- swap the first and fifth element
- swap the third and fifth element
- swap the second and fourth element

def valid(hash_t,n,d):
 flag = 0
 for i in range(d):
  for j in range(i+1,n,d):
   if (hash_t[j] - hash_t[i+1]) % d != 0:
    flag = 1
    return False

 return True

def num_inversion(hash_t,n,d):
 count = 0
 for i in range(d):
  for j in range(i+1,n,d):
   for k in range(j,n,d):
    if hash_t[j] > hash_t[k]:
     count += 1
 return count

tc = int(input())
while tc:
 n, d = input().split()
 n = int(n)
 d = int(d)
 a = [int(x) for x in input().split(" ")]
 if d == 1:
  count = 0
  for i in range(n):
   for j in range(i+1,n):
    if a[i] > a[j]:
     count += 1
  print(count)
 else :
  hash_t = [0]*(n+1)
  for i in range(n):
   hash_t[a[i]] = i+1

  if not valid(hash_t,n+1,d):
   print(-1)
  else :
   #print("Valid")
   count = num_inversion(hash_t,n+1,d)
   print(count)
 tc -= 1


Solve in Python:
Chef recently developed an affinity for undirected graphs.
He likes pairs of graphs that are similar in structure.
However, Chef discovered that when the vertices of a graph are reorganized, it's often the case that the resulting graph,
although still structurally similar to the original, can look completely different.
Chef wants you to help him find similarities in pairs of graphs.

Chef only considers pairs of graphs where each graph has the same number of vertices (say N).
Chef then labels each vertex of each graph with an integer between 1 and N (inclusive),
using each integer exactly once per graph.
Chef then defines the similarity of the graphs as 2*COMMON/TOTAL, where COMMON is the number of
edges appearing in both graphs
(that is, the number of unordered pairs {A, B} such that in both graphs there exists an edge between the vertex labelled A
and the vertex labelled B), and TOTAL is the total number of edges in both graphs.

Chef's measure of similarity depends on how the vertices are labelled.
Chef wants you to help him find a labelling that maximizes the similarity.
Optimal solutions are not required, but better solutions will earn more points.

-----Input-----

Input will begin with an integer T, the number of test cases.
Each test case will begin with an integer N, the number of vertices in both graphs.
2*N lines follow.  The first N lines describe the first graph, and the next N lines the second graph.
Each graph description consists of N lines of N integers each.
The i-th integer on the j-th line will be 1 if there is an edge between vertices i and j, and 0 otherwise.
The i-th integer on the j-th line will always be equal to the j-th integer on the i-th line,
and the i-th integer on the i-th line will always be 0.

-----Output-----

For each test case, output 2 lines with N integers each.
Each line must contain a permutation of the integers 1 through N, and indicates how Chef should label the corresponding graph.

-----Scoring-----

Your score for each test case is the similarity of the 2 graphs...

import random
t=int(input())
for testCase in range(t):
	n=int(input())
	array1=[]
	array2=[]
	array=[]
	for i in range(n) :
		array1.append(list(map(int,input().split())))
	for i in range(n) :
		array2.append(list(map(int,input().split())))
	for i in range(n) :
		array.append(i)
#	print array2,"     ",array1
	for i in range(n) :
		print(array[i]+1, end=' ')
	print()
	k=0
	max=0
	answer=[]
	temp=[]
	while k < (1<<5) :
		k+=1
		for i in range(n) :
			rand=random.randint(0,len(array)-1)
			temp.append(array[rand])
			array.pop(rand)
		array = temp
		count=0
		for i in range(n) :
			for j in range(n) :
				if(array1[i][j] and array2[array[i]][array[j]]) :
					count+=1
		if(count > max):
			answer=array
			max=count
			#print max,count
	for x in answer :
		print(x+1, end=' ')
	print()


Solve in Python:
Chef recently graduated Computer Science in university, so he was looking for a job. He applied for several job offers, but he eventually settled for a software engineering job at ShareChat. Chef was very enthusiastic about his new job and the first mission assigned to him was to implement a message encoding feature to ensure the chat is private and secure.
Chef has a message, which is a string $S$ with length $N$ containing only lowercase English letters. It should be encoded in two steps as follows:
- Swap the first and second character of the string $S$, then swap the 3rd and 4th character, then the 5th and 6th character and so on. If the length of $S$ is odd, the last character should not be swapped with any other.
- Replace each occurrence of the letter 'a' in the message obtained after the first step by the letter 'z', each occurrence of 'b' by 'y', each occurrence of 'c' by 'x', etc, and each occurrence of 'z' in the message obtained after the first step by 'a'.
The string produced in the second step is the encoded message. Help Chef and find this message.

-----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 the message string $S$.

-----Output-----
For each test case, print a single line containing one string — the encoded message.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 100$
- $|S| = N$
- $S$ contains only lowercase English letters

-----Example Input-----
2
9
sharechat
4
chef

-----Example Output-----
shizxvzsg
sxuv

-----Explanation-----
Example case 1: The original message is "sharechat". In the first step, we swap four pairs of letters (note that the last letter is not swapped), so it becomes "hsraceaht". In the second step, we replace the first letter ('h') by 's', the second letter ('s') by 'h', and so on, so the resulting encoded message is "shizxvzsg".

# cook your dish here
try:
 for _ in range(int(input())):
  n = int(input())
  li = [i for i in input()]
  a = 0
  while a+1<len(li):
   li[a],li[a+1] = li[a+1],li[a]
   a+=2
  li2 = li.copy()
  for i in li2:
   fh = 109
   sh = 110
   li.remove(i)
   if ord(i)>fh:
    li.append(chr(fh-(ord(i)-sh)))
   else:
    li.append(chr(sh+(fh-ord(i))))
  for i in li:
   print(i,end="")
  print()
except:
 pass


Solve in Python:
Chef recently learned about concept of periodicity of strings. A string is said to have a period P, if P divides N and for each i, the i-th of character of the string is same as i-Pth character (provided it exists), e.g. "abab" has a period P = 2, It also has a period of P = 4, but it doesn't have a period of 1 or 3.
Chef wants to construct a string of length N that is a palindrome and has a period P. It's guaranteed that N is divisible by P. This string can only contain character 'a' or 'b'. Chef doesn't like the strings that contain all a's or all b's.
Given the values of N, P, can you construct one such palindromic string that Chef likes? If it's impossible to do so, output "impossible" (without quotes)

-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The only line of each test case contains two space separated integers N, P.

-----Output-----
For each test case, output a single line containing the answer of the problem, i.e. the valid string if it exists otherwise "impossible"  (without quotes). If there are more than possible answers, you can output any.

-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ P, N ≤ 105

-----Subtasks-----
- Subtask #1 (25 points) : P = N
- Subtask #2 (75 points) : No additional constraints

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

Output
impossible
impossible
aba
abba
abaaba

-----Explanation-----
Example 1: The only strings possible are either aaa or bbb, which Chef doesn't like. So, the answer is impossible.
Example 2: There are four possible strings, aa, ab, ba, bb. Only aa and bb are palindromic, but Chef doesn't like these strings. Hence, the answer is impossible.
Example 4: The string abba is a palindrome and has a period of 4.
Example 5: The string abaaba is a palindrome and has a period of length 3.

t = int(input())
for i in range(t):
 n, p= list(map(int, input().split()))
 if p == 1 or p == 2:
  print('impossible')
 else:
  s = ''
  if p%2 == 0:
   s = 'a' + 'b'*(p-2) + 'a'
   s = s*(n//p)
  else:
   s = 'a'*(p//2) + 'b' + 'a'*(p//2)
   s = s*(n//p)
  print(s)


Solve in Python:
Chef recently learned about ratios and proportions. He wrote some positive integers a, b, c, d on a paper. Chef wants to know whether he can shuffle these numbers so as to make some proportion? Formally, four numbers x, y, z, w are said to make a proportion if ratio of x : y is same as that of z : w.

-----Input-----
Only line of the input contains four space separated positive integers - a, b, c, d.

-----Output-----
Print "Possible" if it is possible to shuffle a, b, c, d to make proportion, otherwise "Impossible" (without quotes).

-----Constraints-----
- 1 ≤ a, b, c, d  ≤ 1000

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

Output:
Possible

-----Explanation-----
By swapping 4 and the second 2, we get 1 2 2 4. Note that 1 2 2 4 make proportion as 1 : 2 = 2 : 4. Hence answer is "Possible"

a,b,c,d = list(map(float,input().split()))
li = []
li.append(a)
li.append(b)
li.append(c)
li.append(d)
li = sorted(li)
if li[1]/li[0] == li[3]/li[2]:
 print("Possible")
else:
 print("Impossible")


Solve in Python:
Chef recently opened a big e-commerce website where her recipes can be bought online. It's Chef's birthday month and so she has decided to organize a big sale in which grand discounts will be provided.
In this sale, suppose a recipe should have a discount of x percent and its original price (before the sale) is p. Statistics says that when people see a discount offered over a product, they are more likely to buy it. Therefore, Chef decides to first increase the price of this recipe by x% (from p) and then offer a discount of x% to people.
Chef has a total of N types of recipes. For each i (1 ≤ i ≤ N), the number of recipes of this type available for sale is quantityi, the unit price (of one recipe of this type, before the x% increase) is pricei and the discount offered on each recipe of this type (the value of x) is discounti.
Please help Chef find the total loss incurred due to this sale, if all the recipes are sold out.

-----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 denoting the number of recipe types.
- N lines follow. The i-th of these lines contains three space-separated integers pricei, quantityi and discounti describing the i-th recipe type.

-----Output-----
For each test case, print a single line containing one real number — the total amount of money lost. Your answer will be considered correct if it has an absolute error less than 10-2.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ pricei, quantityi ≤ 100 for each valid i
- 0 ≤ discounti ≤ 100 for each valid i

-----Subtasks-----
Subtask #1 (30 points): 1 ≤ N ≤ 100
Subtask #2 (70 points): original constraints

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

2
2
100 5 10
100 1 50
3
10 10 0
79 79 79
100 1 100

Output:

30.000000000
3995.0081000

-----Explanation-----
Example case 1: There are two recipes.
There are 5 recipes of the first type, each of them has a price of 100 and there is a 10%...

for _ in range(int(input())):
 n = int(input())
 s =0
 for _ in range(n):
  p,q,d=map(int,input().split())
  pi= p + (d/100 *p)
  p_new = pi -(d/100 * pi)
  loss = (p - p_new)*q
  s=s+(loss)
 print(s)


Solve in Python:
Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant.
A set of directions consists of several instructions. The first instruction is of the form "Begin on XXX", indicating the street that the route begins on. Each subsequent instruction is of the form "Left on XXX" or "Right on XXX", indicating a turn onto the specified road.
When reversing directions, all left turns become right turns and vice versa, and the order of roads and turns is reversed. See the sample input for examples.

-----Input-----
Input will begin with an integer T, the number of test cases that follow. Each test case begins with an integer N, the number of instructions in the route. N lines follow, each with exactly one instruction in the format described above.

-----Output-----
For each test case, print the directions of the reversed route, one instruction per line. Print a blank line after each test case.

-----Constraints-----
- 1 ≤ T ≤ 15
- 2 ≤ N ≤ 40
- Each line in the input will contain at most 50 characters, will contain only alphanumeric characters and spaces and will not contain consecutive spaces nor trailing spaces. By alphanumeric characters we mean digits and letters of the English alphabet (lowercase and uppercase).

-----Sample Input-----
2
4
Begin on Road A
Right on Road B
Right on Road C
Left on Road D
6
Begin on Old Madras Road
Left on Domlur Flyover
Left on 100 Feet Road
Right on Sarjapur Road
Right on Hosur Road
Right on Ganapathi Temple Road

-----Sample Output-----
Begin on Road D
Right on Road C
Left on Road B
Left on Road A

Begin on Ganapathi Temple Road
Left on Hosur Road
Left on Sarjapur Road
Left on 100 Feet Road
Right on Domlur Flyover
Right on Old Madras Road

-----Explanation-----
In the first test case, the destination lies on Road D, hence the reversed route begins on Road D. The final turn in the original route is turning left from Road C onto Road D....

a=int(eval(input()))
for i in range(0,a):
    n=eval(input())
    k=n
    word=[]
    for j in range(0,n):
        t=input()
        word.append(t)
        l=[]
    flag=0
    for j in range(k-1,-1,-1):
        l=word[j].split()

        if(j==k-1):
            print("Begin", end=' ')
        elif(right==0):
            print("Right", end=' ')
        elif(right==1):
            print("Left", end=' ')

        if(l[0]=='Left'):
            right=0
        elif(l[0]=='Right'):
            right=1
        for index in range (1,len(l)-1):
            print(l[index], end=' ')
        print(l[index+1])
    print()
      #  print l
#print word[0].split()


Solve in Python:
Chef recently saw the movie Matrix. He loved the movie overall but he didn't agree with some things in it. Particularly he didn't agree with the bald boy when he declared - There is no spoon. Being a chef, he understands the importance of the spoon and realizes that the universe can't survive without it. Furthermore, he is sure there is a spoon; he saw it in his kitchen this morning. So he has set out to prove the bald boy is wrong and find a spoon in the matrix. He has even obtained a digital map already. Can you help him?

Formally you're given a matrix of lowercase and uppercase Latin letters. Your job is to find out if the word "Spoon" occurs somewhere in the matrix or not. A word is said to be occurred in the matrix if it is presented in some row from left to right or in some column from top to bottom. Note that match performed has to be case insensitive.

-----Input-----
The first line of input contains a positive integer T, the number of test cases. After that T test cases follow. The first line of each test case contains two space separated integers R and C, the number of rows and the number of columns of the matrix M respectively. Thereafter R lines follow each containing C characters, the actual digital map itself.

-----Output-----
For each test case print one line. If a "Spoon" is found in Matrix, output "There is a spoon!" else output "There is indeed no spoon!" (Quotes only for clarity).

-----Constraints-----

1 ≤ T ≤ 100

1 ≤ R, C ≤ 100

-----Sample Input-----
3
3 6
abDefb
bSpoon
NIKHil
6 6
aaaaaa
ssssss
xuisdP
oooooo
ioowoo
bdylan
6 5
bdfhj
cacac
opqrs
ddddd
india
yucky

-----Sample Output-----
There is a spoon!
There is a spoon!
There is indeed no spoon!

-----Explanation-----
In the first test case, "Spoon" occurs in the second row. In the second test case, "spOon" occurs in the last column.

import sys

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

while( T ):
 T -= 1
 ins = sys.stdin.readline().split()
 R = int( ins[0] )
 C = int( ins[1] )
 horiwords = []
 vertiwords = [' ']*C
 flag = False
 for i in range( R ):
  horiwords.append( sys.stdin.readline().lower() )
  if 'spoon' in horiwords[i]:
   flag = True

 if not flag:
  for i in range( C ):
   for j in range( R ):
    vertiwords[i] += horiwords[j][i]
   if 'spoon' in vertiwords[i]:
    flag = True
    break

 if( flag ):
  print( 'There is a spoon!' )
 else:
  print( 'There is indeed no spoon!' )


Solve in Python:
Chef recently started working at ABC corporation. Let's number weekdays (Monday through Friday) by integers $1$ through $5$. For each valid $i$, the number of hours Chef spent working at the office on weekday $i$ was $A_i$.
Unfortunately, due to the COVID-19 pandemic, Chef started working from home and his productivity decreased by a considerable amount. As per Chef's analysis, $1$ hour of work done at the office is equivalent to $P$ hours of work done at home.
Now, in order to complete his work properly, Chef has to spend more hours working from home, possibly at the cost of other things like sleep. However, he does not have to do the same work on each day as he would have in the office ― for each weekday, he can start the work for this day on an earlier day and/or complete it on a later day. The only requirement is that his work does not pile up indefinitely, i.e. he can complete his work for each week during the same week. One day has $24$ hours.
If Chef is unable to complete his work for a week during those five weekdays, then he has to work during the weekend too. Chef wishes to know whether he has to work on weekends or if he can complete his work by working only on weekdays. Help him answer that question. (It is possible that Chef would be unable to finish his work even if he worked all the time, but he does not want to know about that.)

-----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 six space-separated integers $A_1$, $A_2$, $A_3$, $A_4$, $A_5$ and $P$.

-----Output-----
For each test case, print a single line containing the string "Yes" if Chef has to work on weekends or "No" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 1,000$
- $0 \le A_i \le 24$ for each valid $i$
- $1 \le P \le 24$

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

-----Example Input-----
2
14 10 12 6 18 2
10 10 10 10 10 3

-----Example...

# cook your dish here
for _ in range(int(input())):
 l=list(map(int,input().split()))
 l=(sum(l)-l[5])*l[5]
 if(l<=(24*5)):
  print('No')
 else:
  print('Yes')


Solve in Python:
Chef recently took a course in linear algebra and learned about linear combinations of vectors. Therefore, in order to test his intelligence, Raj gave him a "fuzzy" problem to solve.
A sequence of integers $B_1, B_2, \ldots, B_M$ generates an integer $K$ if it is possible to find a sequence of integers $C_1, C_2, \ldots, C_M$ such that $C_1 \cdot B_1 + C_2 \cdot B_2 + \ldots + C_M \cdot B_M = K$.
In this problem, Chef has a sequence $A_1, A_2, \ldots, A_N$ and he should answer $Q$ queries. In each query, he is given an integer $K$; the answer to this query is the number of pairs $(l, r)$ such that $1 \le l \le r \le N$ and the subsequence $(A_l, A_{l+1}, \ldots, A_r)$ generates $K$.
Chef has no idea how to solve this problem ― can you help him find the answers to all queries?

-----Input-----
- The first line of the input contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- The third line contains a single integer $Q$.
- The following $Q$ lines describe queries. Each of these lines contains a single integer $K$.

-----Output-----
For each query, print a single line containing one integer ― the number of contiguous subsequences that generate $K$.

-----Constraints-----
- $1 \le N, Q \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$
- $1 \le K \le 10^6$

-----Subtasks-----
Subtask #1 (10 points): $1 \le N \le 1,000$
Subtask #2 (90 points): original constraints

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

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

-----Explanation-----
The sequence $(2, 4)$ has three contiguous subsequences: $(2)$, $(4)$ and $(2, 4)$.
- In the first query, $1$ cannot be generated by any subsequence.
- In the second query, $2$ is generated by subsequences $(2)$ and $(2, 4)$. For example, for the subsequence $(2, 4)$, we can choose $C_1 = 1$ and $C_2 = 0$.
- In the third query, $8$ is generated by all three subsequences.

import math
from collections import defaultdict
n=int(input())
a=[int(i) for i in input().split()]
q=int(input())
k=[int(input()) for i in range(q)]
K=max(k)
op=defaultdict(int)
gcd=defaultdict(int)
smallestgcd=a[0]
for i in a:
 gcd[i]+=1
 smallestgcd=math.gcd(smallestgcd,i)
s=[a[0]]

for i in range(1,n):
 for j in range(len(s)):
  if s[j]!=1 and s[j]!=smallestgcd:
   s[j]=math.gcd(a[i],s[j])
  gcd[s[j]]+=1
 s.append(a[i])
if gcd[1]!=0:
 op=defaultdict(lambda: gcd[1])
for i in gcd:
 j=i
 if j==1:
  continue
 while(j<K+1):
  op[j]+=gcd[i]
  j+=i
for z in range(q):
 print(op[k[z]])


Solve in Python:
Chef solved so many hard questions, now he wants to solve some easy problems for refreshment. Chef asks Cheffina for the new question. Cheffina challanges the chef to print the total number of 1's in the binary representation of N(natural number).

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

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

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

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

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

-----EXPLANATION:-----
For 1) Binary representation of 2 is 10. i.e. only one 1 present in it.
For 2) Binary representation of 5 is 101, i.e. two 1's present in it.

# cook your dish here
for i in range(int(input())):
    n=int(input())
    b=bin(n)
    print(b.count("1"))


Solve in Python:
Chef solved so many hard questions, now he wants to solve some easy problems for refreshment. Chef asks Cheffina for the new question. Cheffina challenges the chef to print the total number of 0's in the binary representation of N(natural number).

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

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

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

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

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

-----EXPLANATION:-----
For 1) Binary representation of 2 is 10. i.e. only one 0 present in it.
For 2) Binary representation of 4 is 100, i.e. two 0's present in it.

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

def solve():
    for _ in range(geta()):
        n=geta()
        n=bin(n).split('b')[1]
        print(n.count('0'))

def __starting_point():
    solve()

__starting_point()


Solve in Python:
Chef spent N days working really hard! He planned loads of tasks: as many as Ai tasks to do on the ith day! Chef's work was brutal, so he only managed to finish Bi tasks on the ith day.
The good news is that Chef has a Time Machine!
The Time Machine has K white buttons and M black buttons. Each button has a positive integer printed on it. Now Chef goes through all N days consequently and presses buttons. Each day Chef can only press one button (either white or black). After using a button once, it becomes inactive.
Pressing a white button with integer x printed on it reduces the number of planned tasks on the day it was pressed by exactly x. Note that this white button can only be pressed if number of planned tasks on the day are greater than or equal to x.
Pressing a black button with integer x printed on it increases the number of completed tasks on the day it was pressed by exactly x. Note that this black button can only be pressed if after pressing it, number of completed tasks don't exceed the number of tasks.
Chef is interested in finding the minimum possible amount of total uncompleted tasks he will still be left with after N days using the Machine in the best way?
Be careful! Time is sensitive! Chef cannot make a day when he completed more tasks then planned, as this may result in a more-work-than-planned paradox, killing all lazy people on the planet!

-----Input-----
- The first line of input contains a single integer T, denoting the number of test cases. Description of T test cases follows.
- The first line of each test case contains three integers — N, K, M — denoting the number of days, white and black buttons appropriately.
- The second line contains N space-separated integers A1, A2, … , AN, denoting the number of planned tasks.
- The third line contains N space-separated integers B1, B2, … , BN, denoting the number of completed tasks.
- The fourth line contains K space-separated integers C1, C2, … , CK, denoting the integers on white buttons.
- The fifth and last line contains M...

t = int(input())
for i in range(t):
 inp1 = str(input()).split()
 N = int(inp1[0])
 K = int(inp1[1])
 M = int(inp1[2])
 A = str(input()).split()
 B = str(input()).split()
 C = str(input()).split()
 D = str(input()).split()
 R = [0]*N
 arr = [0]*(K+M)
 for j in range(K):
  arr[j] = int(C[j])
 for j in range(M):
  arr[j+K] = int(D[j])
 arr.sort()
 arr = arr[::-1]
 for j in range(N):
  R[j] = int(A[j]) - int(B[j])
 R.sort()
 R = R[::-1]
 ii = 0
 fl = 0
 for j in range(N):
  while(1):
   if ii >= K+M:
    fl = 1
    break
   if arr[ii] <= R[j]:
    break
   else:
    ii += 1
  if fl == 1:
   break
  R[j] -= arr[ii]
  ii += 1
 su = sum(R)
 print(su)


Solve in Python:
Chef taught his brother Chefu about right angled triangle and its properties. Chefu says that he has understood everything about right angled triangles. Chef wants to check learning of his brother by asking the following question "Can you find a right angled triangle whose length of hypotenuse  is H and its area is S?"
Chefu is confused how to solve it. I hope you are not. Please solve this by finding a right angled triangle with hypotenuse H and area S. If it not possible to do so, then output -1.

-----Input-----
The first line of the input contains a single integer T denoting the number of test-cases. T test cases follow.
For each test case, there will be a single line containing two space separated integers H and S.

-----Output-----
Output the answer for each test-case in a single line. If it is not possible to find such a triangle, output -1. Otherwise print 3 real numbers corresponding to the lengths of the sides of the triangle sorted in non-decreasing order. Please note that the length of the triangle sides should not differ by more than 0.01 in absolute value from the correct lengths.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ H ≤ 106
- 1 ≤ S ≤ 1012

-----Example-----
Input:4
5 6
6 10
258303 89837245228
616153 77878145466
Output:3.00000 4.00000 5.00000
-1
-1
285168.817674 546189.769984 616153.000000

from math import sqrt
from sys import stdin

def solution( h, s ):
 sqrt1 = h ** 4 - 16 * s ** 2
 if( sqrt1 < 0 ):
  return False
 sqrt2 = h**2 - sqrt( sqrt1 )
 if( sqrt2 < 0 ):
  return False;
 sqrt2 = sqrt( sqrt2 / 2 )
 sqrt3 = h**2 + sqrt( sqrt1 )
 sqrt3 = sqrt( sqrt3 / 2 )
 return [ sqrt2, sqrt3 ]

t = int( stdin.readline() )
while t > 0:
 t -= 1
 h, s = list(map( int, stdin.readline().split() ))
 answer = solution( h,s )
 if( answer == False ):
  print(-1)
 else:
  answer.append( h )
  answer = sorted( answer )
  for i in answer:
   print(i, end=' ')
  print()


Solve in Python:
Chef usually likes to play cricket, but now, he is bored of playing it too much, so he is trying new games with strings. Chef's friend Dustin gave him binary strings $S$ and $R$, each with length $N$, and told him to make them identical. However, unlike Dustin, Chef does not have any superpower and Dustin lets Chef perform only operations of one type: choose any pair of integers $(i, j)$ such that $1 \le i, j \le N$ and swap the $i$-th and $j$-th character of $S$. He may perform any number of operations (including zero).
For Chef, this is much harder than cricket and he is asking for your help. Tell him whether it is possible to change the string $S$ to the target string $R$ only using operations of the given type.

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

-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to change $S$ to $R$ or "NO" if it is impossible (without quotes).

-----Constraints-----
- $1 \le T \le 400$
- $1 \le N \le 100$
- $|S| = |R| = N$
- $S$ and $R$ will consist of only '1' and '0'

-----Example Input-----
2
5
11000
01001
3
110
001

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

-----Explanation-----
Example case 1: Chef can perform one operation with $(i, j) = (1, 5)$. Then, $S$ will be "01001", which is equal to $R$.
Example case 2: There is no sequence of operations which would make $S$ equal to $R$.

# cook your dish here
t=int(input())
for i in range(t):
 l=int(input())
 s=input()
 r=input()
 c1=0
 c2=0
 c3=0
 c4=0
 for i in range(l):
  if(s[i]=='0'):
   c1+=1
  else:
   c2+=1
 for j in range(l):
  if(r[j]=='0'):
   c3+=1
  else:
   c4+=1

 if(c1==c3 and c2==c4):
  print("YES")
 else:
  print("NO")


Solve in Python:
Chef wants to buy a new phone, but he is not willing to spend a lot of money. Instead, he checks the price of his chosen model everyday and waits for the price to drop to an acceptable value. So far, he has observed the price for $N$ days (numbere $1$ through $N$); for each valid $i$, the price on the $i$-th day was $P_i$ dollars.
On each day, Chef considers the price of the phone to be good if it is strictly smaller than all the prices he has observed during the previous five days. If there is no record of the price on some of the previous five days (because Chef has not started checking the price on that day yet), then Chef simply ignores that previous day ― we could say that he considers the price on that day to be infinite.
Now, Chef is wondering ― on how many days has he considered the price to be good? Find the number of these days.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $P_1, P_2, \dots, P_N$.

-----Output-----
For each test case, print a single line containing one integer ― the number of days with a good price.

-----Constraints-----
- $1 \le T \le 100$
- $7 \le N \le 100$
- $350 \le P_i \le 750$ for each valid $i$

-----Subtasks-----
Subtask #1 (30 points): $N = 7$
Subtask #2 (70 points): original constraints

-----Example Input-----
1
7
375 750 723 662 647 656 619

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

-----Explanation-----
Example case 1: Chef considers the price to be good on day $1$, because he has not observed any prices on the previous days. The prices on days $2, 3, 4, 5, 6$ are not considered good because they are greater than the price on day $1$. Finally, the price on day $7$ is considered good because it is smaller than all of the prices on days $2, 3, 4, 5, 6$.

from collections import(deque)
for _ in range(int(input())):
 n = int(input())
 a = list(map(int,input().split()))
 d = deque()
 ma = 100000000
 ans = 0
 for i in range(5):
  while d and a[d[0]]>a[i]:
    d.popleft()
  while d and a[d[-1]]>a[i]:
   d.pop()
  d.append(i)
  if a[i]<ma:
   ma = a[i]
   ans+=1
 for i in range(5,len(a)):
  if a[i]<a[d[0]]:
   ans+=1
   # print(a[i])
  while d and a[d[0]]>a[i]:
    d.popleft()
  while d and a[d[-1]]>a[i]:
   d.pop()
  d.append(i)
  if i-d[0] == 5:
   d.popleft()
 print(ans)


Solve in Python:
Chef wants to gift pairs to his friends this new year. But his friends like good pairs
only.
A pair (a , b) is called a good pair if 1 <= a < b <= N such that GCD(a*b , P) = 1.
Since Chef is busy in preparation for the party, he wants your help to find all the
good pairs.
—————————————————————————————————————
INPUT
• The first line of the input contains a single integer T.
• The first and only line of each test case contain two integer N,P.
————————————————————————————————————————
OUTPUT
For each test case, print a single line containing one integer — the total number of good
pairs
————————————————————————————————————————
CONSTRAINTS
• 1 ≤ T≤ 50
• 2 ≤ N,P ≤10^5
—————————————————————————————————————
Example Input
2
2 3
3 3
————————————————————————————————————————
Example Output
1
1

# cook your dish here

def G(x, y):
   while(y):
       x, y = y, x % y
   return x
# t=int(input())
# l=list(map(int,input().split()))
for _ in range(int(input())):
    n,p=map(int,input().split())

    c=0
    for i in range(1,n+1):
        if G(i,p)==1:
            c+=1
    ans=c*(c-1)//2
    print(ans)


Solve in Python:
Chef wants to host some Division-3 contests. Chef has $N$ setters who are busy creating new problems for him. The $i^{th}$ setter has made $A_i$ problems where $1 \leq i \leq N$.
A Division-3 contest should have exactly $K$ problems. Chef wants to plan for the next $D$ days using the problems that they have currently. But Chef cannot host more than one Division-3 contest in a day.
Given these constraints, can you help Chef find the maximum number of Division-3 contests that can be hosted in these $D$ days?

-----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 three space-separated integers - $N$, $K$ and $D$ respectively.
- The second line of each test case contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$ respectively.

-----Output:-----
For each test case, print a single line containing one integer ― the maximum number of Division-3 contests Chef can host in these $D$ days.

-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^2$
- $1 \le K \le 10^9$
- $1 \le D \le 10^9$
- $1 \le A_i \le 10^7$ for each valid $i$

-----Subtasks-----
Subtask #1 (40 points):
- $N = 1$
- $1 \le A_1 \le 10^5$
Subtask #2 (60 points): Original constraints

-----Sample Input:-----
5
1 5 31
4
1 10 3
23
2 5 7
20 36
2 5 10
19 2
3 3 300
1 1 1

-----Sample Output:-----
0
2
7
4
1

-----Explanation:-----
-
Example case 1: Chef only has $A_1 = 4$ problems and he needs $K = 5$ problems for a Division-3 contest. So Chef won't be able to host any Division-3 contest in these 31 days. Hence the first output is $0$.
-
Example case 2: Chef has $A_1 = 23$ problems and he needs $K = 10$ problems for a Division-3 contest. Chef can choose any $10+10 = 20$ problems and host $2$ Division-3 contests in these 3 days. Hence the second output is $2$.
-
Example case 3: Chef has $A_1 = 20$ problems from setter-1 and $A_2 = 36$ problems from setter-2, and so has a total of $56$ problems....

# cook your dish here
t=int(input())
for i in range(t):
 n,k,d=map(int,input().split())
 if(n==1):
  summ=int(input())
 else:
  a=[]
  a=list(map(int,input().strip().split()))[:n]
  summ=sum(a)

 tot=summ//k
 print(min(d,tot))


Solve in Python:
Chef wants to make a feast. In order to do that, he needs a lot of different ingredients. Each ingredient has a certain tastiness; the tastiness of each ingredient may be any positive integer. Initially, for each tastiness between $K$ and $K+N-1$ (inclusive), Chef has an infinite supply of ingredients with this tastiness.
The ingredients have a special property: any two of them can be mixed to create a new ingredient. If the original ingredients had tastiness $x$ and $y$ (possibly $x = y$), the new ingredient has tastiness $x+y$. The ingredients created this way may be used to mix other ingredients as well. Chef is free to mix ingredients in any way he chooses any number of times.
Let's call a tastiness $v$ ($v > 0$) unreachable if there is no way to obtain an ingredient with tastiness $v$; otherwise, tastiness $v$ is reachable. Chef wants to make ingredients with all reachable values of tastiness and he would like to know the number of unreachable values. Help him solve this problem. Since the answer may be large, compute it modulo $1,000,000,007$ ($10^9+7$).
Note that there is an infinite number of reachable values of tastiness, but it can be proven that the number of unreachable values is always finite for $N \ge 2$.

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

-----Output-----
For each test case, print a single line containing one integer — the number of unreachable values of tastiness, modulo $1,000,000,007$.

-----Constraints-----
- $1 \le T \le 10^5$
- $2 \le N \le 10^{18}$
- $1 \le K \le 10^{18}$

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

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

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

-----Explanation-----
Example case 1: It is possible to obtain ingredients with all values of tastiness.
Example case 2: Ingredients with...


Solve in Python:
Chef wants to organize a contest. Predicting difficulty levels of the problems can be a daunting task. Chef wants his contests to be balanced in terms of difficulty levels of the problems.
Assume a contest had total P participants. A problem that was solved by at least half of the participants (i.e. P / 2 (integer division)) is said to be cakewalk difficulty. A problem solved by at max P / 10 (integer division) participants is categorized to be a hard difficulty.
Chef wants the contest to be balanced. According to him, a balanced contest must have exactly 1 cakewalk and exactly 2 hard problems. You are given the description of N problems and the number of participants solving those problems. Can you tell whether the contest was balanced 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 two space separated integers, N, P denoting the number of problems, number of participants respectively.
The second line contains N space separated integers, i-th of which denotes number of participants solving the i-th problem.

-----Output-----
For each test case, output "yes" or "no" (without quotes) denoting whether the contest is balanced or not.

-----Constraints-----
- 1 ≤ T, N ≤ 500
- 1 ≤ P ≤ 108
- 1 ≤ Number of participants solving a problem ≤ P

-----Subtasks-----
- Subtask #1 (40 points): P is a multiple of 10
- Subtask #2 (60 points): Original constraints

-----Example-----
Input
6
3 100
10 1 100
3 100
11 1 100
3 100
10 1 10
3 100
10 1 50
4 100
50 50 50 50
4 100
1 1 1 1

Output
yes
no
no
yes
no
no

-----Explanation-----
Example case 1.: The problems are of hard, hard and cakewalk difficulty. There is 1 cakewalk and 2 hard problems, so the contest is balanced.
Example case 2.: The second problem is hard and the third is cakewalk. There is 1 cakewalk and 1 hard problem, so the contest is not balanced.
Example case 3.: All the three problems are hard. So the contest is not balanced.
Example case 4.: The problems are...

T=int(input())
for i in range(T):
 N,P=list(map(int,input().split()))
 S=list(map(int,input().split()))[:N]
 c=0
 d=0
 for j in range(len(S)):
  if S[j]>=P//2:
   c+=1
  elif S[j]<=P//10:
   d+=1
 if c==1 and d==2:
  print("yes")
 else:
  print("no")


Solve in Python:
Chef wants to select a subset $S$ of the set $\{1, 2, \ldots, N\}$ such that there are no two integers $x, y \in S$ which satisfy $\frac{x}{y} = M$.
Help Chef find the maximum size of a subset $S$ he can choose and the number of ways in which he can choose a subset $S$ with this maximum size. Since the number of ways to choose $S$ can be very large, calculate it modulo $998,244,353$.

-----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 $M$.

-----Output-----
For each test case, print a single line containing two space-separated integers ― the maximum size of a subset Chef can choose and the number of ways to choose a subset with this maximum size modulo $998,244,353$. Note that only the number of ways to choose a subset should be printed modulo $998,244,353$.

-----Constraints-----
- $1 \le T \le 10,000$
- $2 \le M \le N \le 10^{18}$

-----Example Input-----
3
5 2
10 2
100 3

-----Example Output-----
4 1
6 12
76 49152

-----Explanation-----
Example case 1: The only subset $S$ with the maximum size which Chef can choose is $\{1, 3, 4, 5\}$.

import sys
sys.setrecursionlimit(10**9)
mod = 998244353
def power(a, b):
 res=1
 while(b>0):
  if(b%2):
   res*=a
   res%=mod
  b//=2
  a*=a
  a%=mod
 return res
def solve(a):
 if(a>n):
  return (0,1)
 val = a
 c=1
 p=1
 size=0
 ways=0
 while(1):
  if(val>(n//m)):
   break
  val *= m
  p *= m
  c += 1
 u = n//p
 ans = solve(u+1)
 rem = u//m
 rem -= (a-1)//m
 u -= rem
 size = ((c+1)//2)*(u-a+1)
 if(c%2):
  ways=1
 else:
  ways = power(c//2+1,u-a+1)
 size += ans[0]
 ways *= ans[1]
 ways %= mod
 #print(a,ways,size)
 return (size,ways)
t = int(input())
while(t):
 t -= 1
 n, m = list(map(int,input().split()))
 ans = solve(1)
 print(ans[0],ans[1])


Solve in Python:
Chef wants to serve mankind by making people immortal by preparing a dish, a dish of life - a dish with the best taste in the universe, one with the smell and splash of fresh water flowing down the springs of the mountain, one with the smell of the best lily flowers of the garden, one that has contained the very essence of life in a real sense.
This dish will contain K ingredients that are found only in remote islands amid mountains. For sake of convenience, we enumerate the ingredients by the integers from 1 to K, both inclusive. There are N islands and each of them offers some ingredients. Chef being a little child did not know how to collect the ingredients for the recipe. He went to all the islands and bought all the ingredients offered in each island. Could he possibly have saved some time by skipping some island? If it was not possible for Chef to collect the required ingredients (i.e. all the K ingredients), output "sad". If it was possible for him to skip some islands, output "some", otherwise output "all".

-----Input-----
First line of the input contains an integer T denoting number of test cases. The description of T test cases follow.
The first line of each test case contains two space separated integers N, K.
The i-th of the next lines will contain first an integer Pi, denoting the number of ingredients grown in the i-th island, followed by Pi distinct integers in the range [1, K]. All the integers are space separated.

-----Output-----
For each test case, output a single line containing one of the strings "sad", "all" or "some" (without quotes) according to the situation.

-----Constraints-----
- 1 ≤ T  ≤ 10
- 1 ≤ N, K ≤ 105
- 1 ≤ Pi ≤ K
- Sum of Pi over all test cases ≤ 106

-----Subtasks-----
Subtask #1 (30 points)
- 1 ≤ N, K ≤ 50

Subtask #2 (30 points)
- 1 ≤ K ≤ 50

Subtask #3 (40 points)
- original constraints

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

Output
sad
some
all

-----Explanation-----
Example 1. The ingredient 4 is not available in any...

for _ in range(int(input())):
 n,k = list(map(int,input().split()))
 array = []
 tot = []
 for _ in range(n):
  temp = list(map(int,input().split()))
  aa = temp[0]
  del(temp[0])
  temp.sort()
  temp.insert(0,aa)
  array.append(temp)
 dic = {}
 array.sort(reverse=True)
 for i in array:
  del(i[0])
 for i in range(1,k+1):
  tot.append(i)
  dic[i] = False
 count = 0
 for i in array:
  count += 1
  # print(count,tot)
  for j in i:
   if(dic[j]==True):
    pass
   else:
    tot.remove(j)
    dic[j]=True
  if(len(tot)==0):
   break
 if(len(tot)!=0):
  print("sad")
 elif(count!=n):
  print("some")
 else:
  print("all")


Solve in Python:
Chef wants to teach a lesson of sharing to the students.
There are $N$ students (numbered from $1$ to $N$ from left to right) who are asked to stand in a row. Initially Chef gave $A$$i$ candies to the $i$$th$ child. In one operation any child can give any number of candies to the child standing to his immediate left (i.e. $i$$th$ child can give any amount of candies to the $(i-1)$$th$ child. In particular 1st child cannot give his candies to anyone).
He asked them to minimize the maximum value of candies a student can possess after performing any number of operations (possibly zero).
Help the students finding such maximum value.

-----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.
- First line of each test case contains a single integer $N$ denoting the number of students.
- Second line contains $N$ space-separated integers $A$$1$,$A$$2$,$.....$ $A$$N$ denoting the initial amount of candies chef gave to them.

-----Output:-----
- For each test case, print a single line containing one integer ― maximum value after sharing.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^5$
- $0$ $\leq$ $A$$i$ $\leq$ $10^9$
- Sum of $N$ over all Test Cases does not exceed $10^5$

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

-----Sample Output-----
3
5

-----Explanation-----
-
For First Test Case:
The $5$$th$ student will give $2$ candies to $4$$th$ student and $4$$th$ will give $3$ candies to $3$$rd$ and $3$$rd$ will give $3$ candies to $2$$nd$ and $2$$nd$ will give $2$ candies to $1$$st$. So finally the number of candies that they will have are
$[3,3,3,3,3]$ and the value of maximum candies is $3$.
-
For Second Test Case:
Sharing to the left student will not change the maximum value as $1$$st$ cannot share to anyone. So the maximum value will remain $5$.

from math import ceil

for _ in range(int(input())):
 n = int(input())
 arr = [int(x) for x in input().split()]
 sarr = sum(arr)
 mavg = sarr/n
 while n>1:
  sarr -= arr.pop()
  n-=1
  mavg = max(mavg, sarr/n)
 print(int(ceil(mavg)))


Solve in Python:
Chef wants you to distribute candies among $N$ kids who are sitting in a circle. However, he wants to make some kids jealous of others. Thus, he wants you to distribute candies in such a way that there is a difference of at least $K$ candies between two adjacent kids.
Given the value of $N$ and $K$, you need to find the minimum number of candies you need to satisfy the given conditions, such that, each kid gets at least one candy.

-----Input:-----
- First line will contain $T$, the number of testcases. Then the testcases follow.
- The only line of each testcase contains two space-separated integers $N$ and $K$.

-----Output:-----
For each test case, print a single line containing one integer ― the number of candies you need.

-----Constraints-----
- $1 \leq T \leq  10^6$
- $2 \leq  N \leq  10^3$
- $0 \leq  K \leq 10^4$

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

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

-----EXPLANATION:-----
The minimum number of candies required is $3$. One kid needs to have $1$ candy and the other needs to have $2$ candy to have a difference of $1$ candy between them.

for i in range(int(input())):
    n,k=map(int,input().split())
    if k==0:
        print(n)
    else:
        if n%2==0:
            s=n//2 + (n//2)*(k+1)
            print(s)
        else:
            s=n//2 + 2*(k+1) + (n//2)*(k+1)
            print(s-1)


Solve in Python:
Chef was bored staying at home in the lockdown. He wanted to go out for a change. Chef and Chefu are fond of eating Cakes,so they decided to go the Cake shop where cakes of all possible price are available .
They decided to purchase cakes of equal price and each of them will pay for their cakes. Chef only has coins of denomination $N$ whereas Chefu has that of denomination $M$.
So they want your help to find out the minimum amount to be spent in order to purchase the cakes.

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

-----Output:-----
For each testcase, output in a single line answer the minimum amount to be spent in order to purchase the cake.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N,M \leq 10^7$

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

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

# cook your dish here
def gcd(a,b):
    if a == 0:
        return b
    return gcd(b % a, a)

def lcm(a,b):
    return (a*b) / gcd(a,b)

for _ in range(int(input())):
    n,m=list(map(int,input().split()))
    print(int(lcm(n,m)))


Solve in Python:
Chef will not be able to attend the birthday of his best friend Rock. He promised Rock that this will not be the case on his half birthday. To keep his promise Chef must know Rock’s next half birthday accurately. Being busy, he is assigning this work to you.
Half birthday is the day that occurs exactly between two subsequent birthdays.
You will be provided with Rock’s birthdate and birth month, you will have to figure out his half birthday.
$Note$: Consider every year to be a leap year and all months are displayed in lowercase English characters.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases.
- The description of each of the $T$ test cases contains an integer $d$ followed by a string, denoting month $m$.
- Here $d$ denotes day of a month and $m$ denotes the month of a year respectively.

-----Output:-----
For each test case print an integer $d1$ followed by a string, denoting month $m1$, which overall denotes date and month of Rock’s half birthday.

-----Constraints:-----
- $1 \leq T \leq 10^5$
- $1 \leq d , d1 \leq 31$
- $january \leq m , m1 \leq december$

-----Sample Input:-----
3
15 january
31 august
10 october

-----Sample Output:-----
16 july
1 march
10 april

# cook your dish here
d = {'january':31,'february':29,'march':31,
 'april':30,'may':31,'june':30,'july':31,
 'august':31,'september':30,'october':31,
 'november':30,'december':31}

#l=[[15,'january'],[31,'august'],[10,'october']]
l2 = list(d.keys())
for _ in range(int(input())):
 l=input().split()
 l[0]=int(l[0])
 a = l[1]
 ind = l2.index(a)
 b = 183 - (d[l[1]] - l[0])
 while b!=0:
  if ind!=11:
   ind+=1
  else:
   ind = 0
  if b<=d[l2[ind]]:
   print(b,l2[ind])
   break
  b-=d[l2[ind]]


Solve in Python:
Chef works as a cook in a restaurant. Each morning, he has to drive down a straight road with length K$K$ to reach the restaurant from his home. Let's describe this road using a coordinate X$X$; the position of Chef's home is X=0$X = 0$ and the position of the restaurant is X=K$X = K$.
The road has exactly two lanes (numbered 1$1$ and 2$2$), but there are N$N$ obstacles (numbered 1$1$ through N$N$) on it. For each valid i$i$, the i$i$-th obstacle blocks the lane Li$L_i$ at the position X=Xi$X = X_i$ and does not block the other lane.
When driving, Chef cannot pass through an obstacle. He can switch lanes in zero time at any integer X$X$-coordinate which does not coincide with the X$X$-coordinate of any obstacle. However, whenever he switches lanes, he cannot switch again until driving for at least D$D$ units of distance, and he can travel only in the direction of increasing X$X$. Chef can start driving in any lane he wants. He can not switch lanes at non-integer  X$X$-coordinate.
Sometimes, it is impossible to reach the restaurant without stopping at an obstacle. Find the maximum possible distance Chef can travel before he has to reach an obstacle which is in the same lane as him. If he can avoid all obstacles and reach the restaurant, the answer is K$K$.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains three space-separated integers N$N$, K$K$ and D$D$.
- The second line contains N$N$ space-separated integers X1,X2,…,XN$X_1, X_2, \ldots, X_N$.
- The third line contains N$N$ space-separated integers L1,L2,…,LN$L_1, L_2, \ldots, L_N$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum distance Chef can travel.

-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N≤105$1 \le N \le 10^5$
- 2≤K≤109$2 \le K \le 10^9$
- 1≤D≤109$1 \le D \le 10^9$
- 1≤Xi≤K−1$1 \le X_i \le K-1$ for each valid i$i$
- Xi<Xi+1$X_i <...

for _t in range(int(input())):
    n, k, d = list(map(int, input().split()))
    xs = list(map(int, input().split()))
    ls = list(map(int, input().split()))
    my_x = 0
    my_l = 3 - ls[0]
    for x, l_ in zip(xs, ls):
     # print(my_x, my_l)
     if l_ == my_l:
      if x <= my_x:
       # crash
       print(x)
       break
      my_l = 3 - my_l
      my_x = max(x + 1, my_x + d)
     else:
      my_x = max(x + 1, my_x)
    else:
     print(k)


Solve in Python:
Chef works in a similar way to a travelling salesman ― he always travels to new cities in order to sell his delicious dishes.
Today, Chef is planning to visit $N$ cities (numbered $1$ through $N$). There is a direct way to travel between each pair of cities. Each city has a specific temperature; let's denote the temperature in the $i$-th city by $C_i$. Chef has a fixed temperature tolerance $D$ with the following meaning: for each pair of cities $a$ and $b$, he may travel from city $a$ directly to city $b$ only if $|C_a-C_b| \le D$, otherwise he would catch a heavy flu because of the sudden change in temperature.
Chef starts from city $1$. Is he able to visit all $N$ cities in such a way that each city is visited exactly once?
Notes:
- Chef is not able to travel through a city without visiting it.
- City $1$ is visited at the beginning.
- It is not necessary to be able to travel directly to city $1$ from the last city Chef visits.

-----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 $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 the string "YES" (without quotes) if Chef can visit all cities or "NO" (without quotes) if he cannot.

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

-----Subtasks-----
Subtask #1 (20 points):
- $N \le 1,000$
- the sum of $N$ over all test cases does not exceed $10,000$
Subtask #2 (80 points): original constraints

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

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

t=int(input())
for _ in range(t):
 n,d=map(int,input().split())
 a=list(map(int,input().split()))
 v={i:0 for i in a}
 v[a[0]]=1
 x=a[0]
 poss=1
 poss2,poss3=True,True
 a.sort()
 for i in range(n-1):
  if(a[i+1]-a[i]>d):
   poss=0
   break
 if(poss):
  st=a.index(x)
  if st!=n-1 and st!=0 and poss:
   for i in range(st):
    if (a[i+2]-a[i])>d:
     poss2=False
     break
   if poss2==False:
    for i in range(st-1,n-2):
     if (a[i+2]-a[i])>d:
      poss3=False
      break
 if((poss2 or poss3) and poss):
  print("YES")
 else:
  print("NO")


Solve in Python:
Chef would like go shopping to buy ingredients for his special dish. The local grocery store has some special discount offers. If you want to buy some set of ingredients you will pay for all ingredients except the cheapest one. Chef would like to spend as little money as possible. You have to help him. :)

The store is pretty small and stocks only one unit of each ingredients. Opposite each ingredient is a hanging price tag corresponding to it. The salesman walked away for a minute, giving Chef an opportunity to swap some price tags. He would like to swap some tags to minimize his purchase cost.

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

The first line of each test case contains a single integer N denoting the number of ingredients Chef needs to buy. The second line contains N space-separated integers A1, A2, ... , AN denoting the value  written on the price tags opposite the needed ingredients. The third line contains a single integer M denoting the number of special offers. The following M lines lists inventory of special offers, one offer per line. Each line contains an integer Ci followed by Ci integers denoting the indices of ingredients constituting the ith discount offer.

-----Output-----
For each test case, output a single line containing the minimal purchase cost.

-----Constraints-----
- T ≤ 5
- 1 ≤ N ≤ 15
- 1 ≤ Ai ≤ 106
- 0 ≤ M ≤ 2N-1
- 2 ≤ Ci ≤ N
- Subtask 1 (15 points):  1 ≤ N ≤  5
- Subtask 2 (25 points):  1 ≤ N ≤ 10
- Subtask 3 (60 points):  1 ≤ N ≤ 15

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

Output:
6

from itertools import permutations as p
def disc(a,b):
 for ai in a:
  for bi in b:
   if ai==bi:
    return False
 return True

for i in range(eval(input())):
 n = eval(input())
 arr = list(map(int,input().split()))
 perms = list(p(arr))
 m = eval(input())
 offer = {}
 for i in range(m):
  dup = list(map(int,input().split()))
  try:
   offer[dup[0]].append(dup[1:])
  except:
   offer[dup[0]] = [dup[1:]]
 ans = sum(arr)
 if n==1:
  print(ans)
 elif n==2:
  try:
   if len(offer[2])>=1:
    ans -= min(arr)
  except:
   pass
  print(ans)
 elif n==3:
  try:
   if len(offer[3])>=1:
    ans -= min(arr)
  except:
   pass
  try:
   if len(offer[2])>=1:
    value = 9999999999
    for item in perms:
     cur = 0
     cur += item[0]
     cur += max(item[1],item[2])
     if cur<value:
      value = cur
    if value<ans:
     ans = value
  except:
   pass
  print(ans)
 elif n==4:
  try:
   if len(offer[4])>=1:
    ans -= min(arr)
  except:
   pass
  #print ans
  try:
   if len(offer[3])>=1:
    value = 9999999999
    for item in perms:
     cur = 0
     cur = sum(item)
     cur -= min(item[1],item[2],item[3])
     if cur<value:
      value = cur
    if value<ans:
     ans = value
  except:
   pass
  #print ans
  try:
   if len(offer[2])>=1:
    value = 9999999999
    for item in perms:
     cur = 0
     cur = sum(item)
     cur -= min(item[1],item[2])
     if cur<value:
      value = cur
    if value<ans:
     ans = value
    #print ans
   #print offer[2]
   if len(offer[2])>=2:
    flg = False
    end = len(offer[2])
    for i in range(end):
     for j in range(i+1,end):
      if disc(offer[2][i],offer[2][j]):
       flg = True
       break
    #print flg
    if flg:
     value = 9999999999
     for item in perms:
      cur = 0
      cur = sum(item)
      cur -= min(item[1],item[0])
      cur -= min(item[2],item[3])
      if cur<value:
       value = cur
     if value<ans:
      ans = value
  except:
   pass
  print(ans)
 elif n==5:
  try:
   if len(offer[5])>=1:
    ans -= min(arr)
  except:
   pass
  try:
   if...


Solve in Python:
Chef's company wants to make ATM PINs for its users, so that they could use the PINs for withdrawing their hard-earned money. One of these users is Reziba, who lives in an area where a lot of robberies take place when people try to withdraw their money.
Chef plans to include a safety feature in the PINs: if someone inputs the reverse of their own PIN in an ATM machine, the Crime Investigation Department (CID) are immediately informed and stop the robbery. However, even though this was implemented by Chef, some people could still continue to get robbed. The reason is that CID is only informed if the reverse of a PIN is different from that PIN (so that there wouldn't be false reports of robberies).
You know that a PIN consists of $N$ decimal digits. Find the probability that Reziba could get robbed. Specifically, it can be proven that this probability can be written as a fraction $P/Q$, where $P \ge 0$ and $Q > 0$ are coprime integers; you should compute $P$ and $Q$.

-----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$ denoting the length of each PIN.

-----Output-----
For each test case, print a single line containing two space-separated integers — the numerator $P$ and denominator $Q$ of the probability.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10^5$

-----Subtasks-----
Subtask #1 (10 points): $N \le 18$
Subtask #2 (20 points): $N \le 36$
Subtask #3 (70 points): original constraints

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

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

-----Explanation-----
Example case 1: A PIN containing only one number would fail to inform the CID, since when it's input in reverse, the ATM detects the same PIN as the correct one. Therefore, Reziba can always get robbed — the probability is $1 = 1/1$.

# cook your dish here
import math
for _ in range(int(input())):
 n = int(input())
 r = n-math.ceil(n/2)
 print(1,10 ** r)


Solve in Python:
Chef's daily routine is very simple. He starts his day with cooking food, then he eats the food and finally proceeds for sleeping thus ending his day. Chef carries a robot as his personal assistant whose job is to log the activities of Chef at various instants during the day. Today it recorded activities that Chef was doing at N different instants. These instances are recorded in chronological order (in increasing order of time). This log is provided to you in form of a string s of length N, consisting of characters 'C', 'E' and 'S'. If s[i] = 'C', then it means that at the i-th instant Chef was cooking, 'E' denoting he was eating and 'S' means he was sleeping.
You have to tell whether the record log made by the robot could possibly be correct or not.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains string s.

-----Output-----
For each test case, output a single line containing "yes" or "no" (without quotes) accordingly.

-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ N ≤ 105

-----Subtasks-----
- Subtask #1 (40 points) : 1 ≤ N ≤ 100
- Subtask #2 (60 points) : original constraints

-----Example-----
Input:
5
CES
CS
CCC
SC
ECCC

Output:
yes
yes
yes
no
no

-----Explanation-----
Example case 1. "CES" can correspond to a possible record of activities of Chef. He starts the day with cooking, then eating and then sleeping.
Example case 2. "CS" can also correspond to a possible record of activities of Chef. He starts the day with cooking, then eating and then sleeping. Robot recorded his cooking and sleeping in order. He might not have recorded his eating activity.
Example case 4. "SC" can not correspond to Chef's activities. Here it means that Chef slept first, then he cooked the food, which is impossible for Chef to do on some particular day.

def routne(s):
 flag=0
 for i in range(len(s)-1):
  if ord(s[i])>ord(s[i+1]):
   flag=0
   return "no"
  else:
   flag=1
 if flag==1:
  return "yes"
 else:
  return "no"
for i in range(int(input())):
 a=input()
 print(routne(a))


Solve in Python:
Chef's dog Snuffles has so many things to play with! This time around, Snuffles has an array A containing N integers: A1, A2, ..., AN.
Bad news: Snuffles only loves to play with an array in which all the elements are equal.
Good news: We have a mover of size D. !
A mover of size D is a tool which helps to change arrays. Chef can pick two existing elements Ai and Aj from the array, such that i + D = j and subtract 1 from one of these elements (the element should have its value at least 1), and add 1 to the other element. In effect, a single operation of the mover, moves a value of 1 from one of the elements to the other.
Chef wants to find the minimum number of times she needs to use the mover of size D to make all the elements of the array A equal. Help her find this out.

-----Input-----
- The first line of the input contains an integer T, denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains two integers N and D, denoting the number of elements in the array and the size of the mover.
- The second line of each testcase contains N space-separated integers: A1, A2, ..., AN, denoting the initial elements of the array.

-----Output-----
- For each test case, output a single line containing the minimum number of uses or -1 if it is impossible to do what Snuffles wants.

-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ N ≤ 105
- 1 ≤ D < N
- 1 ≤ Ai ≤ 109

-----Subtasks-----
- Subtask 1 (30 points) : N ≤  103
- Subtask 2 (70 points) : Original constraints

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

Output:
3
2
-1

-----Explanation-----
Testcase 1:
Here is a possible sequence of usages of the mover:
- Move 1 from A3 to A1
- Move 1 from A3 to A1
- Move 1 from A2 to A4
At the end, the array becomes (3, 3, 3, 3, 3), which Snuffles likes. And you cannot achieve this in fewer moves. Hence the answer is 3.
Testcase 2:
Here is a possible sequence of usages of the mover:
- Move 1 from A2 to A1
- Move 1 from A2 to A3
At the end, the array...

T=int(input())
for i in range(0,T):
 (N,D)=input().split()
 N=int(N)
 D=int(D)
 L=[int(i) for i in input().split()]
 A=0
 flag=''
 MOVE=0
 s=0
 s=sum(L)
 if (s%len(L))!=0:
  print(-1)
  flag=False
 else:
  A=s/len(L)
  for i in range(N):
   if L[i]>A and (i+D)<N:
    diff=L[i]-A
    L[i]=L[i]-diff
    L[i+D]=L[i+D]+diff
    MOVE=MOVE+diff

   elif L[i]<A and (i+D)<N:
    diff=A-L[i]
    #if L[i+D]>=diff:
    L[i]=L[i]+diff
    L[i+D]=L[i+D]-diff
    MOVE=MOVE+diff
  for i in L:
   if i!=A and flag!=False:
    print(-1)
    flag=False
    break
  if flag!=False:
   print(int(MOVE))


Solve in Python:
Chef's friend Alex runs a movie theatre. Due to the increasing number of platforms for watching movies online, his business is not running well. As a friend, Alex asked Chef to help him maximise his profits. Since Chef is a busy person, he needs your help to support his friend Alex.
Alex's theatre has four showtimes: 12 PM, 3 PM, 6 PM and 9 PM. He has four movies which he would like to play ― let's call them A, B, C and D. Each of these movies must be played exactly once and all four must be played at different showtimes. For each showtime, the price of a ticket must be one of the following: Rs 25, Rs 50, Rs 75 or Rs 100. The prices of tickets for different showtimes must also be different.
Through his app, Alex receives various requests from his customers. Each request has the form "I want to watch this movie at this showtime". Let's assume that the number of people who come to watch a movie at a given showtime is the same as the number of requests for that movie at that showtime.
It is not necessary to accommodate everyone's requests ― Alex just wants to earn the maximum amount of money. There is no restriction on the capacity of the theatre. However, for each movie that is not watched by anyone, Alex would suffer a loss of Rs 100 (deducted from the profit).
You are given $N$ requests Alex received during one day. Find the maximum amount of money he can earn on that day by choosing when to play which movies and with which prices.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. Each of these lines contains a character $m$, followed by a space and an integer $t$, describing a request to see the movie $m$ at the showtime $t$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum profit Alex can earn (possibly negative).
Finally, print a line containing one integer ― the total...

from pprint import pprint
from numpy import where
arr =[]
from sys import stdin,stdout
for _ in range(int(stdin.readline())):
 t = int(stdin.readline())
 a = []
 for i in range(4):
  temp = []
  for j in range(4):
   temp.append(0)
  a.append(temp)
 s = 0
 for __ in range(t):
  mov , time = input().split()
  time = int(time)
  if mov == 'A':
   if time == 12:
    a[0][0]+=1
   elif time ==3:
    a[0][1]+=1
   elif time == 6:
    a[0][2]+=1
   else:
    a[0][3]+=1
  elif mov =='B':
   if time == 12:
    a[1][0]+=1
   elif time == 3:
    a[1][1]+=1
   elif time == 6:
    a[1][2]+=1
   else:
    a[1][3]+=1
  elif mov =='C':
   if time == 12:
    a[2][0]+=1
   elif time == 3:
    a[2][1]+=1
   elif time == 6:
    a[2][2]+=1
   else:
    a[2][3]+=1
  else:
   if time == 12:
    a[3][0]+=1
   elif time == 3:
    a[3][1]+=1
   elif time == 6:
    a[3][2]+=1
   else:
    a[3][3]+=1
 ma = -1
 cakes =[]
 for k in range(4):
  mai,maj=-1,-1
  for i in range(4):
   for j in range(4):
    if a[i][j] > ma:
     ma = a[i][j]
     mai = i
     maj = j
  for z in range(4):
   for x in range(4):
    if z==mai or x == maj:
     a[z][x]=0
  cakes.append(ma)
  ma = -1
 cakes = sorted(cakes,reverse=True)
 for i in range(4):
  if cakes[i]==0:
   s-=100
  else:
   if i==0:
    s+= cakes[i]*100
   elif i==1:
    s+= cakes[i]*75
   elif i==2:
    s+= cakes[i]*50
   elif i==3:
    s+= cakes[i]*25
 print(s)
 arr.append(s)
 #print(arr)
print(sum(arr))


Solve in Python:
Chef's love for Fibonacci numbers helps him to design following interesting problem.
He defines a function F for an array S as follows:

where
- Si denotes a non-empty subset of multiset S.
- sum(Si) denotes the sum of all element of multiset Si.
- Fibonacci(x) denotes the xth Fibonacci number.
Given an array A consisting of N elements. Chef asked you to process following two types of queries on this array accurately and efficiently.
- C X Y: Change the value of Xth element of array to Y i.e AX = Y.
- Q L R: Compute function F over the subarray defined by the elements of array A in the range L to R, both inclusive.

Please see the Note section if you need details regarding Fibonacci function.

-----Input-----
First line of input contains 2 space separated integer N and M denoting the size of array A and the number of queries to be performed. Next line of input contains N space separated integers denoting the elements of array A. Each of next M lines of input contains a query having one of the mentioned two types.

-----Output-----
For each query of type Q, output the value of function F for the given range of array A.

-----Constraints-----
- 1 ≤ N, M ≤ 105
- 1 ≤ Ai, Y ≤ 109
- 1 ≤ L, R, X ≤ N
-  type = {'C', 'Q'}

-----Subtasks-----
- Subtask 1 (20 points) : 1 ≤ N, M ≤ 1000, 1 ≤ Ai, Y ≤ 106, type = { 'Q' }
- Subtask 2 (20 points) : 1 ≤ N, M ≤ 50000, 1 ≤ Ai, Y ≤ 109, type = { 'C', Q' }
- Subtask 3 (30 points) : 1 ≤ N, M ≤ 105, 1 ≤ Ai, Y ≤ 109, type = { 'Q' }
- Subtask 4 (30 points) : 1 ≤ N, M ≤ 105, 1 ≤ Ai, Y ≤ 109, type = { 'C', Q' }

-----Example-----
Input
3 5
1 2 3
Q 1 2
Q 2 3
C 1 2
Q 1 2
Q 1 3

Output
4
8
5
30

-----Explanation:-----
- Q1 : F = Fibonacci(1) + Fibonacci(2) + Fibonacci(1+2) = 4 % 1000000007 = 4
- Q2 : F = Fibonacci(2) + Fibonacci(3) + Fibonacci(2+3) = 8 % 1000000007 = 8
- Q3 : A = {2, 2, 3}
- Q4 : F = Fibonacci(2) + Fibonacci(2) + Fibonacci(2+2) = 5 % 1000000007 = 5
- Q5 : F = Fibonacci(2) + Fibonacci(2) + Fibonacci(3) + Fibonacci(2+2) + Fibonacci(2+3) + Fibonacci(2+3) +...


Solve in Python:
Chef's loves his dog so much! Once his dog created two strings a and b each of length n consisting of digits 1 and 2, and even a problem about them!
Chef's Dog will tell by barking if a string x (also containing only digits 1 and 2 and with length N) is good or not by performing the following actions.

- It starts at first digit of the string, i.e. at i = 1.
- It can move from digit i to either i - 1 or i + 1 if xi equals 1 and the corresponding digits exist.
- It can move from digit i to either i - 2 or i + 2 if xi equals 2 and the corresponding digits exist.
- It must visit each digit exactly once.
- It must finish at the last digit (XN).

Chef's dog wants to make both the strings a and b good by choosing some subset S (possibly empty) of indices of set {1, 2, ..., n} and swapping each index i ϵ S between string a and b, i.e. swapping ai and bi. Can you find how many such subsets S exist out there? As the answer could be large, output it modulo 109 + 7.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line contains string a.
The second line contains string b.

-----Output-----
For each test case, output a single line containing answer of the problem.

-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ |a| = |b| ≤ 105
- '1' ≤ ai, bi ≤ '2'

-----Subtasks-----
- Subtask #1 (30 points) |a|, |b| ≤  10
- Subtask #2 (70 points) original constraints

-----Example-----
Input:
2
1111
2211
222
111

Output:
8
0

-----Explanation-----
Test case 1.
Possible subsets are:
{}, {1, 2}, {1, 2, 3}, {1, 2, 4}, {1, 2, 3, 4}, {3}, {4}, {3, 4}.

Test case 2. There are no possible sets S which can make both the strings good.

mod = 10 ** 9 + 7
from collections import Counter
choice = {'1' : ['11', '21', '22'], '2' : ['11', '12', '21']}
def solve(a,b):
 n = len(a)
 if n == 1:
  return 2
 dp = Counter([('11', '11')])
 for i in range(n-1):
  new = Counter()
  for x,y in (a[i], b[i]), (b[i], a[i]):
   for p in choice[x]:
    for q in choice[y]:
     m = p[-1] + x
     n = q[-1] + y
     new[m,n] += dp[p,q]
     new[m,n] %= mod
  dp = new
 ans = 0
 for i in '11', '21', :
  for j in '11', '21':
   ans += dp[i,j]
 return (ans * 2) % mod

t = int(input())
for _ in range(t):
 a = input()
 b = input()
 print(solve(a,b))


Solve in Python:
Chef's new hobby is painting, but he learned the fact that it's not easy to paint 2D pictures in a hard way, after wasting a lot of canvas paper, paint and of course time. From now on, he decided to paint 1D pictures only.
Chef's canvas is N millimeters long and is initially all white. For simplicity, colors will be represented by an integer between 0 and 105. 0 indicates white. The picture he is envisioning is also N millimeters long and the ith millimeter consists purely of the color Ci. Unfortunately, his brush isn't fine enough to paint every millimeter one by one. The brush is 3 millimeters wide and so it can only paint three millimeters at a time with the same color. Painting over the same place completely replaces the color by the new one. Also, Chef has lots of bottles of paints of each color, so he will never run out of paint of any color.
Chef also doesn't want to ruin the edges of the canvas, so he doesn't want to paint any part beyond the painting. This means, for example, Chef cannot paint just the first millimeter of the canvas, or just the last two millimeters, etc.
Help Chef by telling him whether he can finish the painting or not with these restrictions.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N. The second line contains N space-separated integers C1, C2, ..., CN denoting the colors of Chef's painting.

-----Output-----
For each test case, output a single line containing either “Yes” or “No” (without quotes), denoting whether Chef can finish the painting or not.

-----Constraints-----
- 1 ≤ T ≤ 105
- 3 ≤ N ≤ 105
- The sum of the Ns over all the test cases in a single test file is ≤ 5×105
- 1 ≤ Ci ≤ 105

-----Example-----
Input:3
4
1 5 5 5
4
1 1 1 5
3
5 5 2
Output:Yes
Yes
No

-----Explanation-----
Example case 1. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the first three...

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    ans=0
    for i in range(n-2):
        if(a[i]==a[i+1] and a[i]==a[i+2]):
            ans=1
    if ans==1:
        print('Yes')
    else:
        print('No')


Solve in Python:
Chef's pizza is the tastiest pizza to exist, and the reason for that is his special, juicy homegrown tomatoes.
Tomatoes can be grown in rectangular patches of any side lengths. However, Chef only has a limited amount of land.
Consider the entire town of Chefville to be consisting of cells in a rectangular grid of positive coordinates.
Chef own all cells (x,y)$(x, y)$ that satisfy x∗y≤N$x*y \leq N$
As an example if N=4$N = 4$, Chef owns the following cells:
(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(3,1),(4,1)$(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1) $
Chef can only grow tomatoes in rectangular patches consisting only of cells which belong to him. Also, if he uses a cell, he must use it entirely. He cannot use only a portion of it.
Help Chef find the number of unique patches of rectangular land that he can grow tomatoes in! Since this number can be very large, output it modulo 1000000007$1000000007$.

-----Input:-----
- The first line of the input contains T$T$, the number of test cases.
- The next T$T$ lines of input contains one integer N$N$.

-----Output:-----
For each testcase, output the number of ways modulo 1000000007$1000000007$.

-----Constraints-----
- 1≤T≤5$1 \leq T \leq 5$
- 1≤N≤1010$1 \leq N \leq 10^{10}$

-----Sample Input:-----
2
4
10000000000

-----Sample Output:-----
23
227374950

import math
Mod=1000000007

for _ in range(int(input())):
  v=int(input())
  i=0
  s=0
  for i in range(1,math.floor(math.sqrt(v))+1):
    s+=i*((math.floor(v/i))*(math.floor(v/i)+1)-(i*(i-1)))
    s-=(i*i)
  print(s%Mod)


Solve in Python:
Chef's younger brother is in town. He's a big football fan and has a very important match to watch tonight. But the Chef wants to watch the season finale of MasterChef which will be aired at the same time. Now they don't want to fight over it like they used to when they were little kids. They want to decide it in a fair way. So they agree to play a game to make a decision. Their favourite childhood game!
The game consists of C boards. Each board i is a grid of dimension ni x mi.
Rules of the game:

- A coin is placed at (1,1) on every board initially.

- Each one takes a turn alternatively.

- In one turn, a player can choose any one board and move a coin from a cell (i,j) to one of the following cells:

	(i+1,j) OR (i+2,j) OR (i,j+1) OR (i,j+2) OR (i+1,j+1) OR (i+2,j+2).

- A coin cannot be moved out of the board at any point during the game.

- A coin cannot be moved once it reaches the cell (n,m) where n and m are the dimensions of the board of that coin.

- A player MUST make one valid move.

- The player who makes the last move gets to watch TV.

Both of them are passionate about their interests and want to watch their respective shows. So they will obviously make optimal moves in every turn. The Chef, being the elder brother, takes the first turn.
Your task is to predict which show they will be watching tonight.

-----Input:-----
The first line of input contains a single integer T, the number of test cases. T tests follow.Each test case starts with a single line containing C, the number of boards in the game.
Then follow C lines: each containing 2 integers ni and mi, the dimensions of the ith board.

-----Output:-----
Given the number and dimensions of boards, for each test case, output in a single line: "MasterChef" if the Chef wins or "Football" if his brother wins.

-----Constraints:-----

1<=T<=10000

1<=C<=20

2<=ni,mi<=1000

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

1

1

2 2

Output:

MasterChef

Explanation:

The Chef can move the coin on the board from (1,1)->(2,2). This coin cannot be moved any further. And...

st=''
for _ in range(int(input())):
 x=0
 for c in range(int(input())):
  n,m=map(int,input().split())
  g=(m+n-2)%3
  x=x^g
 if x:
  ans=("MasterChef")
 else:
  ans=("Football")
 st+=ans+'\n'
print(st)


Solve in Python:
Cheffina challanges chef to rearrange the given array as arr[i] > arr[i+1] < arr[i+2] > arr[i+3].. and so on…, i.e. also arr[i] < arr[i+2] and arr[i+1] < arr[i+3] and arr[i] < arr[i+3] so on.. Chef accepts the challenge, chef starts coding but his code is not compiling help him to write new code.

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

-----Output:-----
For each test case, output in a single line answer given to the Chefffina.

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

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

-----Sample Output:-----
3 1 6 4
3 1 5 4 6

# cook your dish here
def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def lcm(x, y):
    return (x*y)//(gcd(x,y))

def isPrime(n) :
    if (n <= 1) :
        return False
    if (n <= 3) :
        return True
    if (n % 2 == 0 or n % 3 == 0) :
        return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

abc="abcdefghijklmnopqrstuvwxyz"

pi=3.141592653589793238

t = int(input())
for _ in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    arr.sort()
    ans=[]
    for i in range(1,n+1,2):
        try:
            ans.append(arr[i])
        except:
            pass
        try:
            ans.append(arr[i-1])
        except:
            pass
    print(*ans)


Solve in Python:
Chefina  is  always interested to play with string. But due to exam pressure she has no time to solve a string problem. She wants your help. Can you help her to solve that problem?
You are given a string. You have to find out the $Wonder$ $Sum$ of the string. $Wonder$ $Sum$ of a string is defined as the sum of the value of each character of the string.
The value of each character means:
- If the string is started with "a" , then the value of each character of the string is like "a"=100, "b"=101, "c"="102" ………"z"=125.
- If the string is started with "z" , then the value of each character of the string is like "a"=2600, "b"=2601, "c"="2602" ………"z"=2625.
Since even the $Wonder$ $Sum$ can be large, output $Wonder$ $Sum$ modulo  ($10^9 + 7$).

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, a string $S$ with lower case alphabet
only.

-----Output:-----
For each testcase, output in a single line integer i.e.  $Wonder$ $Sum$ modulo  ($10^9 + 7$).

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq |S| \leq 10^5$

-----Sample Input:-----
$2$$cab$
$sdef$

-----Sample Output:-----
$903$
$7630$

-----EXPLANATION:-----
i) For the first test case, since the string is started with "$c$", so output is ($302$+$300$+$301$)=$903$
ii)For the second test case, since the string is started with "$s$", so output is ($1918$+$1903$+$1904$+$1905$)=$7630$


Solve in Python:
Chefina has two sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_N$. She views two sequences with length $N$ as identical if, after they are sorted in non-decreasing order, the $i$-th element of one sequence is equal to the $i$-th element of the other sequence for each $i$ ($1 \le i \le N$).
To impress Chefina, Chef wants to make the sequences identical. He may perform the following operation zero or more times: choose two integers $i$ and $j$ $(1 \le i,j \le N)$ and swap $A_i$ with $B_j$. The cost of each such operation is $\mathrm{min}(A_i, B_j)$.
You have to find the minimum total cost with which Chef can make the two sequences identical.

-----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$.
- The third line contains $N$ space-separated integers $B_1, B_2, \ldots, B_N$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum cost, or $-1$ if no valid sequence of operations exists.

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

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

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

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

-----Explanation-----
Example case 1: There is no way to make the sequences identical, so the answer is $-1$.
Example case 2: The sequence are identical initially, so the answer is $0$.
Example case 3: We can swap $A_1$ with $B_2$, which makes the two sequences identical, so the answer is $1$.

# cook your dish here
from collections import Counter
for _ in range(int(input())):

 n = int(input())
 a = sorted(map(int,input().split()))
 b = sorted(map(int,input().split()))
 x=Counter(a)
 y=Counter(b)
 z=x+y
 l=[]
 q=min(a[0],b[0])
 for k in list(z.keys()):

  if z[k]%2==1:
   print(-1)
   break
  else:
   l.extend([k]*(abs(x[k]-y[k])//2))

 else:
  l.sort()
  ans=0

  if l==[]:
   print(0)
  else:
   for i in range((len(l)//2)):

    ans+=min(l[i],2*q)

   print(ans)


Solve in Python:
Chefland has all the cities on a straight line. There are $N$ cities in Chefland numbered $1$ to $N$. City $i$ is located at coordinate $x_i$ on the x-axis. Guru wants to travel from city $A$ to city $B$. He starts at time t=0. He has following choices to travel.
- He can walk $1$ metre in $P$ secs.
- There is a train that travels from city $C$ to city $D$ which travels $1$ metre in $Q$ secs which starts at time t=$Y$ secs. Guru can take the train only at city $C$ and leave the train only at city $D$.
Can you help Guru find the minimum time he will need to travel from city $A$ to $B$. Note that you cannot board the train after time t =$Y$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains eight space separated integers $N, A, B, C, D, P, Q, Y $.
- Second line of each testcase contains $N$ space-separated integers with the $i$-th integer representing $x_i$.

-----Output:-----
For each testcase, output in a single line containing the minimum travel time.

-----Constraints-----
- $1 \leq T \leq 300$
- $2 \leq N \leq 300$
- $-1000 \leq x_i \leq 1000$
- $0 \leq Y \leq 100000$
- $1 \leq A,B,C,D \leq n $
- $A \neq B$
- $C \neq D$
- $1 \leq P, Q \leq 100$
- $x_i < x_j$  if $i < j$

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

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

-----EXPLANATION:-----
Guru can walk directly in 6 secs.
If Guru takes train, then he will need  atleast 11 secs.

for _ in range(int(input())):
 n,a,b,c,d,p,q,y=map(int,input().split())
 ar=[int(x) for x in input().split()]
 temp1=abs(ar[a-1]-ar[c-1])*p
 if temp1>y:
  temp1=10**9
 else:
  if temp1==y:
   temp1+=abs(ar[c-1]-ar[d-1])*q +abs(ar[d-1]-ar[b-1])*p
  elif temp1<y:
   temp1+=abs(ar[c-1]-ar[d-1])*q +abs(ar[d-1]-ar[b-1])*p+abs(temp1-y)
 temp2=abs(ar[a-1]-ar[b-1])*p
 print(min(temp1,temp2))


Solve in Python:
Chefland is a grid with N$N$ rows and M$M$ columns. Each cell of this grid is either empty or contains a house. The distance between a pair of houses is the Manhattan distance between the cells containing them.
For each d$d$ between 1$1$ and N+M−2$N+M-2$ inclusive, Chef wants to calculate the number of unordered pairs of distinct houses with distance equal to d$d$. Please help him!

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains a binary string with length M$M$; for each j$j$ (1≤j≤M$1 \le j \le M$), the j$j$-th character of this string is '1' if the cell in the i$i$-th row and j$j$-th column contains a house or '0' if it is empty.

-----Output-----
For each test case, print a single line containing N+M−2$N+M-2$ space-separated integers. For each valid i$i$, the i$i$-th integer should denote the number of pairs with distance i$i$.

-----Constraints-----
- 1≤T≤3$1 \le T \le 3$
- 2≤N,M≤300$2 \le N, M \le 300$

-----Subtasks-----
Subtask #1 (50 points): N,M≤50$N, M \le 50$
Subtask #2 (50 points): original constraints

-----Example Input-----
1
3 4
0011
0000
0100

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

from itertools import combinations
from scipy.spatial.distance import pdist
import numpy as np

def solve():
    houses = []
    n,m = list(map(int, input().split()))

    for i in range(n):
     s = input()
     tmp = [i for i,x in enumerate(s) if x =='1']
     houses = houses + [[i,j] for j in tmp]

    counter = [0]* (n+m-1)
    dis = pdist(np.array(houses),'cityblock').astype(int)

    for i in dis:
     counter[i] += 1
    return [counter[i] for i in range(1,n+m-1)]

for _ in range(int(input())):
    print(*solve())


Solve in Python:
Chefu is Chef's little brother, he is 12 years old and he is new to competitive programming.
Chefu is practicing very hard to become a very skilled competitive programmer and win gold medal in IOI.
Now Chefu is participating in a contest and the problem that he is trying to solve states:
Given an array A of N integers, find any i, j such that i <  j
and Ai + Aj is maximum possible
unfortunately, there's no much time left before the end of the contest, so Chefu doesn't have time to think of correct solution, so instead, he wrote a solution that selects a random pair (i,  j) (i <  j) and output Ai + Aj. each pair is equiprobable to be selected.
Now Chefu wants your help to calculate the probability that his solution will pass a particular input.

-----Input-----
First line contains an integer T denoting the number of test-cases.
First line of each test-case contains a single integer N
Second line of each test-case contains N space-separated integers A1 A2 ... AN

-----Output-----
For each test-case output a single line containing a single number denoting the probability that Chefu's solution to output a correct answer. your answer will be accepted if the absolute difference between it and correct answer is less than 1e-6

-----Constraints-----
- 1 ≤ T ≤ 100
- 2 ≤ N ≤ 100
- 1 ≤ Ai ≤ 1,000

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

Output:
1.00000000
0.20000000
0.33333333

# cook your dish here
t=int(input())
while t>0:
 n=int(input())
 a=list(map(int,input().split()))
 max=0
 c=0
 for i in range(n):
  for j in range(i+1,n):
   if a[i]+a[j]>max:
    max=a[i]+a[j]
 for i in range(n):
  for j in range(i+1,n):
   if a[i]+a[j]==max:
    c+=1
 x=n*(n-1)/2
 print(c/x)
 t-=1


Solve in Python:
Chef’s girlfriend is angry with him because he forgot her birthday. Chef decided to please her by gifting her a Love Graph.
Chef has $N$ vertices: $V_1, V_2, \dots, V_N$. Love Graph is an undirected multigraph with no self-loops and can be constructed by performing the following operations:-
- Choose an integer $i$ ($1 \leq i \leq N$)
- Choose another integer $j \space \space \{ (i \neq j) \text{ and } (1 \leq j \leq N) \}$
- Make an edge between $V_i$ and $V_j$
- Set $i = j$
- Repeat steps $2, 3$ and $4$ in order $M-1$ more times.
Find the number of ways in which Chef can construct a Love Graph. Since the answer can be very large, compute it modulo $10^9+7$.

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

-----Output-----
For each test case, print a single line containing one integer — the number of ways in which Chef can construct a Love Graph modulo $10^9+7$.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $2 \leq N \leq 10^9$
- $1 \leq M \leq 10^{18}$

-----Subtasks-----
- 30 points:
- $1 \leq T \leq 100$
- $2 \leq N \leq 10$
- $1 \leq M \leq 10$
- 70 points: original constraints

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

2 1

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

-----Explanation-----
There are two ways of constructing Love Graph.

In first way, we pick Vertex 1 and then join with Vertex 2.

In second way, we pick Vertex 2 and then join with Vertex 1.

def fastpow(base, power):
 result = 1
 while power > 0:
  if power % 2 == 0:
   power = power // 2

   base = base * base
  else:
   power = power - 1
   result = result * base
   power = power // 2
   base = base * base
 return result

t=int(input())
for i in range(t):
 a=list(map(int,input().split()))
 n,r=a[0],a[1]
 w=(n*(fastpow(n-1,r)))%((10**9)+7)

 print(w)


Solve in Python:
Cherry has a binary matrix $A$ consisting of $N$ rows and $M$ columns. The rows are numbered from $1$ to $N$, columns are numbered from $1$ to $M$. Element at row $i$ ($1$ ≤ $i$ ≤ $N$) and column $j$ ($1$ ≤ $j$ ≤ $M$) is denoted as $A_{ij}$. All elements of $A$ are either $0$ or $1$.
He performs $Q$ queries on matrix. Each query is provided by four integers $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ which define the rectangle, where ($x_{1}$, $y_{1}$) stands for the coordinates of the top left cell of the rectangle, while ($x_{2}$, $y_{2}$) stands for the coordinates of the bottom right cell. You need to flip all the bits i.e. ($0$ to $1$, $1$ to $0$) that are located fully inside the query rectangle.
Finally, print the matrix after performing all the queries.
Note: $x_{1}$ represents the row number while $y_{1}$ represents the column number.

-----Input:-----
- The first line of the input contains two integers $N$ and $M$ — the number of rows and the number of columns in the matrix.
- Each of the next $N$ lines contains a string of length $M$, where the $j^{th}$ character of $i^{th}$ line denotes the value of $A_{i,j}$.
- Next line contains an integer $Q$ — the number of queries.
- Then follow $Q$ lines with queries descriptions. Each of them contains four space-seperated integers $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ — coordinates of the up left and bottom right cells of the query rectangle.

-----Output:-----
Print the matrix, in the form of $N$ strings, after performing all the queries.

-----Constraints-----
- $1 \leq N,M \leq 1000$
- $0 \leq  A_{ij}  \leq 1$
- $1 \leq Q \leq 10^6$
- $1 \leq x_{1} \leq x_{2} \leq N$
- $1 \leq y_{1} \leq y_{2} \leq M$

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

-----Sample Output:-----
01
10

-----Explanation:-----
Example case 1:
After processing the 1st query 1 1 1 1, matrix becomes:
[1000][1000]\begin{bmatrix} 10 \\ 00  \end{bmatrix}
After processing the 2nd query 2 2 2 2, the matrix becomes:
[1001][1001]\begin{bmatrix} 10 \\ 01  \end{bmatrix}
After processing...

n,m=map(int,input().split())
mat=[]
for i in range(n):
 me=[int(i) for i in list(input())]
 mat.append(me)
dummy=[[0 for i in range(m+1)] for j in range(n+1)]
q=int(input())
for i in range(q):
 x1,y1,x2,y2=map(int,input().split())
 dummy[x1-1][y1-1]+=1
 dummy[x2][y1-1]-=1
 dummy[x2][y2]+=1
 dummy[x1-1][y2]-=1
for i in range(n+1):
 for j in range(m+1):
  if j==0:
   continue
  else:
   dummy[i][j]+=dummy[i][j-1]
for j in range(m+1):
 for i in range(n+1):
  if i==0:
   continue
  else:
   dummy[i][j]+=dummy[i-1][j]
for i in range(n):
 for j in range(m):
  print((mat[i][j]+dummy[i][j]+2)%2,end="")
 print()
print()