I found an interesting problem on https://www.codechef.com/INOIPRAC/problems/TINOI17B:
-----INOI 2017, Problem 2, Training-----
Ash and his Pokemon Pikachu are going on a journey.  Ash has planned his route
for the journey so that it passes through N cities, numbered 1, 2, …, N, and in this order.

When they set out, Pikachu has an initial strength of Sin as well as an experience
value (XV) of 0. As they travel they may increase his strength and experience value
in a manner to be described below.

In each city,  Ash can choose either to train Pikachu or let Pikachu battle the
Gym-leader (but not both).  The Gym-leader in ith city has experience E[i]. If
Pikachu enters a city i with strength S and decides to train, then this
increases his strength by the cube of the sum of the digits in his current
strength. For example, if he entered a city with a strength of 12, then
training will increase his strength to 12 + (1+2)3 = 39.  On the other hand,
if he enters city i with strength S and battles the Gym-leader, then this
increases his experience value XV by S*E[i].

Ash wants your help to find out the maximum XV that Pikachu can attain
at the end of his journey.

-----Input-----
- The first line contains two space separated integers, N and Sin, which are the number of cities, and the initial strength, respectively.

- The second line contains N space separated integers, which correspond to E[1], E[2],..., E[N].

-----Output-----
- A single integer which is the maximum XV that Pikachu can attain.

-----Constraints-----
For all test cases you may assume that:

- 1 ≤ N ≤ 5000
- 0 ≤ Sin ≤ 109
- 0 ≤ E[i] ≤ 104

Subtask 1: For 10% of the score,

- N ≤ 20 and Sin = 1

Subtask 2: For further 40% of the score,

- E[i] = k for all i
i.e. E[i] is some constant k, for all i

Subtask 3: For further 50% of the score,

-
No further constraints.

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

Output 1:
390

-----Explanation 1-----
Suppose Pikachu trains in the first city, his strength will increase to 39, because as explained above, 12 + (1+2)3 = 39. If he battles in the first city, his XV will increase by (12*5) =...

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

#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define inf 100000000000000
typedef long long ll;
#define mp make_pair
#define f first
#define s second
ll xp[5005];
ll train[5005];
ll dp[5005][5005];
int n;
ll power(ll x,ll y){
    ll res=1;
    while (y){
        if (y & 1){
            res=res*x;
        }
        x=x*x;
        y=y>>1;
    }
    return res;
}
ll cube(ll x){
    ll res=x,sum=0;
    while(x!=0){
        sum+=(x%10);
        x=x/10;
    }
    res+=power(sum,3);
    return res;
}
ll max_xp(int i,int r){
    if(i>n){
        return 0;
    }
    if(dp[i][r]!=-1){
        return dp[i][r];
    }
    ll maxi=0;
    if(r<=n){
        maxi=max_xp(i+1,r+1);
    }
    maxi=max(maxi,max_xp(i+1,r)+xp[i]*train[r]);
    return dp[i][r]=maxi;
}
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	ll s;
	cin>>n>>s;
	for(int i=1;i<=n;i++){
	    cin>>xp[i];
	}
	memset(dp,-1,sizeof(dp));
	train[0]=s;
	for(int i=1;i<=n;i++){
	    train[i]=cube(train[i-1]);
	}
	cout<<max_xp(1,0)<<"\n";
	return 0;
}


I found an interesting problem on https://www.codechef.com/INSO2020/problems/INQU2003:
A pair of strings $(α, β)$ is called a subpair of a string $x$ if $x$ = $x_1+$$α+$$x_2+$$β+$$x_3$ (where a+b means concatenation of strings a and b) for some (possibly empty) strings $x1, x2$ and $x3$. We are given two strings and we need to find one subpair from each string such that :
Let $(a,b) , (c,d) $be subpair of $string1$ and $string2$ respectively and $X$ $=$ $a$ + $b$ + $c$ + $d$
- $X$ is a palindrome
- $|a| = |d|$
- $|b| = |c|$
- $|X|$ is maximum

-----Input Format:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two strings str1, str2.

-----Output Format:-----
- For each testcase, output in a single line representing the length of palindrome |X|.

-----Constraints-----
- $1 \leq T \leq 5$
- $2 \leq |str1| \leq 10^3$
- $2 \leq |str2| \leq 10^3$

-----Sample Input 1:-----
1
abgcd dchbag

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

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

aaa aaa

zaaax yaaaw

zax yaw

zx yw

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

6

2

0

-----EXPLANATION:-----
Sample Testcase 1: The subpairs are ("ab","cd") and ("dc","ba"). When the subpairs are concatenated string is "abcddcba" which is a pallindrome , |"ab"| = |"ba"|, |"cd"| = |"dc"| and has the maximum length equal to 8.

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

from collections import defaultdict as dd

def find(a, b):
 n = len(a)
 m = len(b)

 dp = [[0]*(m+1) for i in range(n+1)]

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

 mx = dd(int)
 ans = 0
 for i in range(n-1, -1, -1):
  for j in range(m-1, -1, -1):
   a = mx[(i+1, j)]
   b = mx[(i, j+1)]
   mx[(i, j)] = max([dp[i][j], a, b])

 for i in range(n):
  for j in range(m):
   c = dp[i][j]
   nxt = mx[(i+c, j+c)]
   cur = c + nxt
   ans = max(ans, cur)

 return 2*ans
for case in range(int(input())):
 a, b = input().split()
 b = b[-1::-1]

 ans = find(a, b)
 print(ans)


I found an interesting problem on https://www.codechef.com/IPC15P3A/problems/DMSG:
Dilku and Bhopu live in Artland. Dilku loves Bhopu and he writes a message : “iloveyou”
on paper and wishes to send it to Bhopu. As Dilku is busy making an artwork, he asks his friend Raj to send the message to Bhopu. However Raj has a condition that he may add/remove some  characters and jumble the letters of the message.
As Bhopu understands Dilku, she can read “iloveyou” from the message if all the characters of the string “iloveyou” are in the message received by her. Bhopu is happy if she can read “iloveyou” from the message. Otherwise, she is sad. Tell whether Bhopu is happy or sad.

-----Input-----
Input contains a string S, where S is the message received by Bhopu. String S consists of only lowercase letters.

-----Output-----
Output “happy” if Bhopu is happy and “sad” if Bhopu is sad.

-----Constraints-----
1 ≤ |S| ≤ 100
Where |S| denotes length of message string S

-----Example-----
Input 1:
iloveyou

Output 1:
happy

Input 2:
ulrvysioqjifo

Output 2:
sad

Input 3:
abcvleouioydef

Output 3:
happy

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

#!/usr/bin/python
a = input()
x='iloveyou'
for i in x:
 if i not in a:
  print("sad")
  return
if a.count('o') < 2:
 print("sad")
 return
print("happy")
return


I found an interesting problem on https://www.codechef.com/LOCAUG16/problems/MINMO:
Little Rohu from Pluto is the best bomb defusor on the entire planet. She has saved the planet from getting destruced multiple times now. Of course, she's proud of her achievments. But, to prepare herself for more complicated situations, she keeps challenging herself to handle tricky tasks.
Her current challenge involves the following things:
- A square matrix of the form N*N.
- B bombs planted at various cells of the square matrix.
- There can be multiple bombs at a given cell.
- Only the four corners of the square matrix have a bomb defusor, so if a bomb is moved to any one of the four corners, it will be defused.

From a given cell, any bomb can be moved in all the four directions, North, South, East, West respectively.

Rohu is given the number of bombs and the dimensions of the square matrix she's going to be dealing with, you've to help her figure out the minimum number of moves required to defuse all the bombs.

Note-1: She's not going to enter the matrix, she's just going to move the bombs from outside.
Note-2: The matrix is 1-indexed.

-----Input-----
- The first line of each test case contains two integers N, denoting the dimension of the square matrix, and B denoting the number of bombs. This will be followed by two lines, where the first line will denote the x-coordinate of all the bombs, and the second line will denote the y-coordinate of all the bombs. x[0], y[0] will be the position of the first bomb, ... , x[B-1], y[B-1] will be the position of the Bth bomb.

-----Output-----
- Output a single line containing the minimum number of moves required.

-----Subtasks-----
- 1 ≤ N, B ≤ 100000: 50 points

- 1 ≤ N, B ≤ 1000: 30 points

- 1 ≤ N, B ≤ 10: 20 points

-----Constraints-----
- 1 ≤ N, B ≤ 100000

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

Output:
2

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

Output:
0

-----Explanation-----
Example case 1:Only the bomb at {2,2} needs to be moved in two steps.
Example case 2:No bomb needs to be moved anywhere.

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

a,b=list(map(int,input().split()))
c=list(map(int,input().split()))
d=list(map(int,input().split()))
ans=0
for i in range(0,b):
	c[i]=c[i]-1
	d[i]=d[i]-1
	f=[]
	f.append(c[i]+d[i])
	f.append(2*a-2-c[i]-d[i])
	f.append(a-1-c[i]+d[i])
	f.append(c[i]+a-1-d[i])
	ans=ans+min(f)
print(ans)


I found an interesting problem on https://www.codechef.com/LTIME33/problems/CHEFTIC:
Tic-Tac-Toe used to be Chef's favourite game during his childhood. Reminiscing in his childhood memories, he decided to create his own "Tic-Tac-Toe", with rules being similar to the original Tic-Tac-Toe, other than the fact that it is played on an NxN board.

The game is played between two players taking turns. First player puts an 'X' in an empty cell of the board, then the second player puts an 'O' in some other free cell. If the first player has K continuous X's or the second player has K continuous O's in row, column or diagonal, then he wins.

Chef started playing this new "Tic-Tac-Toe" with his assistant, beginning as the first player himself (that is, Chef plays 'X's). Currently, the game is ongoign, and it's Chef's turn. However, he needs to leave soon to begin tonight's dinner preparations, and has time to play only one more move. If he can win in one move, output "YES", otherwise output "NO" (without quotes). It is guaranteed that no player has already completed the winning criterion before this turn, and that it's a valid "Tic-Tac-Toe" game.

-----Input-----
The first line of input contains one integer T denoting the number of testcases. First line of each testcase contains two integers N and K, next N lines contains N characters each. Each character is either an 'X' denoting that the first player used this cell, an 'O' meaning that the second player used this cell, or a '.' (a period) representing a free cell.

-----Output-----
For each testcase, output, in a single line, "YES" if Chef can win in one move, or "NO" otherwise.

-----Constraints-----
- 1 ≤ T ≤ 100
- 3 ≤ N ≤ 20
- 1 ≤ K ≤ N

-----Example-----
Input:
3
3 3
XOX
O.O
XOX
3 1
...
...
...
3 2
...
...
...

Output:
YES
YES
NO

Input:
1
4 4
XOXO
OX..
XO..
OXOX

Output:
YES

-----Subtasks-----
- Subtask 1:  K  = 1. Points - 10
- Subtask 2:  N  =  K  = 3. Points - 30
- Subtask 3: Original constraints. Points - 60

-----Explanation-----
Test #1:

In first testcase, put 'X' in (2, 2), in second we can put 'X' in any cell and win.
Test #2:

If you...

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

# cook your code here

def checkRow(A,row,N,K):
    count = 0
    move  = 0
    for i in range(N):
        if(A[row][i]=='.'):
            move = move+1
        if(not(A[row][i]=='O') and move<2):
            count = count+1
        elif(A[row][i]=='.'):
            move  = 1
            count = 1
        else:
            count = 0
            move  = 0
        if(count==K):
            return 1
    return 0

def checkCol(A,col,N,K):
    count = 0
    move  = 0
    for i in range(N):
        if(A[i][col]=='.'):
            move = move+1
        if(not(A[i][col]=='O') and move<2):
            count = count+1
        elif(A[i][col]=='.'):
            count = 1
            move  = 1
        else:
            count = 0
            move  = 0
        if(count==K):
            return 1
    return 0

def checkDiag(A,row,col,N,K):
    count = 0
    move  = 0

    for i in range(K):
        if(A[row+i][col+i]=='.'):
            move = move+1
        if(not(A[row+i][col+i]=='O') and move<2):
            count = count+1
        elif(A[row+i][col+i]=='.'):
            move = 1
            count = 1
        else:
            move = 0
            count = 0
        if(count==K):
            return 1
    return 0

def chck(A,N,K):
    flag = 0

    if(flag==0):
        #row
        for i in range(N):
            flag = checkRow(A,i,N,K)
            if(flag==1):
                break

    if(flag==0):
        #col
        for j in range(N):
            flag = checkCol(A,j,N,K)
            if(flag==1):
                break

    if(flag==0):
        #diag
        for i in range(N-K+1):
            for j in range(N-K+1):
                flag = checkDiag(A,i,j,N,K)
                if(flag==1):
                    break
            if(flag==1):
                    break

    return flag

for tests in range(eval(input())):
    [N,K] = list(map(int,input().split()))
    A = [""]*N

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

    if(chck(A,N,K)==1):
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://www.codechef.com/LTIME35/problems/KSUM:
Chef likes arrays a lot. Today, he found an array A consisting of N positive integers.
Let L denote the sorted (in non-increasing order) list of size N*(N+1)/2 containing the sums of all possible contiguous subarrays of A. Chef is interested in finding the first K elements from the list L. Can you help him in accomplishing this task?

-----Input-----
There is only a single test case per input file.
The first line of input contains two space separated integer numbers N and K denoting the size of the array and the number of the maximal sums you need to find.
The following line contains N space separated integer numbers denoting the array A.

-----Output-----
Output K space separated integers where the ith integer denotes the ith element of L.

-----Constraints-----
- 1 ≤ N ≤ 105
- 1 ≤ K ≤ min(N*(N+1)/2, 105)
- 1 ≤ Ai ≤ 109

-----Subtasks-----
- Subtask 1 (47 pts) : 1 ≤ N ≤ 1000, 1 ≤ K ≤ min{N*(N+1)/2, 105}
- Subtask 2 (53 pts) : 1 ≤ N ≤ 105, 1 ≤ K ≤ min{N*(N+1)/2, 105}

-----Example-----
Input 13 4
1 3 4

Output 18 7 4 4

Input 23 3
10 2 7

Output 219 12 10

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

The first 4 elements of it are [8, 7, 4, 4].

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

__author__ = 'Deepak'
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
m=1
d=[]
while(m<=len(a)):
 for j in range(len(a)-m+1):
  d.append(sum(list(a[j:j+m])))
 m+=1
#print d
d.sort(reverse=True)
for i in range(k):
 print(d[i], end=' ')


I found an interesting problem on https://www.codechef.com/LTIME40/problems/LTM40AB:
Chef likes inequalities. Please help him to solve next one.
Given four integers a, b, c, d. Find number of solutions x < y, where a ≤ x ≤ b and c ≤ y ≤ d and x, y integers.

-----Input-----
The first line contains an integer T denoting number of tests.
First line of each test case contains four positive integer numbers a, b, c and d.

-----Output-----
For each test case, output a single number each in separate line denoting number of integer solutions as asked in the problem.

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

-----Subtasks-----
- Subtask #1: (30 points)  1 ≤ a, b, c, d ≤ 103.
- Subtask #2: (70 points)  Original constraints.

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

Output:3

Input:1
2 999999 1 1000000

Output:499998500001

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

import sys
ting = int(sys.stdin.readline())
for i in range(ting):
 m = list(map(int,sys.stdin.readline().split()))
 a,b,c,d = m[0],m[1],m[2],m[3]
 count1 = 0
 i = a
 while i<=b:
  if i > d:
   break
  if i<c:
   count1 = count1 + d-c+1
  if i>=c:
   count1 = count1 + d-i
  i = i + 1
 print(count1)


I found an interesting problem on https://www.codechef.com/MAY16/problems/CHBLLS:
Chef has bought ten balls of five colours. There are two balls of each colour. Balls of same colour have same weight. Let us enumerate colours by numbers from 1 to 5. Chef knows that all balls, except two (of same colour), weigh exactly one kilogram. He also knows that each of these two balls is exactly 1 kg heavier than other balls.

You need to find the colour which balls are heavier than others.
To do that, you can use mechanical scales with two weighing pans. As your scales are very accurate, you can know the exact difference of weights of objects from first and second pans. Formally, the scales will give you the difference (signed difference) of weights of the objects put into the first pan and the second pan. See the following examples for details.

- If you put two balls of the same colour on your scales, each ball to one pan, the scales will tell you that difference is "0".
- But if you put into the first pan some balls of total weight 3 kg, and into the second pan of 5 kg, then scales will tell you "-2" because the second pan is 2 kg heavier than first.
- Similarly, if you put 5 kg weight in first pan and 3 kg in the second pan, then scale will tell you "2" as first pan is 2 kg heavier than second.

-----Input & Output-----
- The interaction process have two phases. At first phase you perform sequence of weighings on the mechanical scales. At the second phase you should output the colour of the heavier balls.
- To use the mechanical scales, you should print "1"(without quotes) and then print two lines, the first line will describe the enumeration of colours of balls on the first pan and second line should that of second pan.
- To describe some pan, you need to print one integer n - the number of balls you put in this pan, followed by n space-separated integers - colours of the balls you put in this pan.
- Once you have printed required data, you can read from the standard input one integer - the difference of weights of the first and the second pans.
- To output the colour of the heavier balls,...

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

import sys

print("1")
print("3 1 1 2")
print("3 3 3 4")
sys.stdout.flush()
wt=eval(input())

if(wt==0):
	print("2")
	sys.stdout.flush()
	print("5")
	sys.stdout.flush()

elif(wt<0):
	if wt==-1:
		print("2")
		sys.stdout.flush()
		print("4")
		sys.stdout.flush()
	elif wt==-2:
		print("2")
		sys.stdout.flush()
		print("3")
		sys.stdout.flush()

elif(wt>0):
	if wt==1:
		print("2")
		sys.stdout.flush()
		print("2")
		sys.stdout.flush()
	elif wt==2:
		print("2")
		sys.stdout.flush()
		print("1")
		sys.stdout.flush()


I found an interesting problem on https://www.codechef.com/MCOD2020/problems/MCUBES:
Every year the professor selects the top two students from his class and takes them on a fun filled field trip, this year Ali and Zafar were selected.
The professor took them to a place where there was a never-ending queue of solid metal cubes. The professor could see $n$ cubes at a time. On the day before, he had painted the first $n$ cubes from the left with various colours.
Ali was allowed to choose any painted cube to initially stand on (say $X$). Zafar was asked to stand on the last painted cube (the $n^{th}$ cube) with the professor.
The two students were given an activity each:
- Ali had to shout out the colour of the cube he is standing on.
- Zafar had to paint the adjacent cube on the right of him with that colour.
Both Ali and Zafar had to take one step to the right each time they performed their activity.
The Professor jumped along with Zafar, and never left his side. Throughout the activity he was looking leftwards keeping an eye on Ali. They were given a gold star and were allowed to go home when all the cubes that the professor could see at the time were painted with the same color.
Ali wanted to choose a position furthest from the professor and also wanted the gold star.
Can you help Ali to choose this position $X$?
The cubes are numbered from 1 starting from the first painted cube.
The colours are represented as integers.

-----Input:-----
- The first line contains one integer n, the number of cubes initially painted.
- The second line contains n space-separated integers: $a_1$, $a_2$, $\dots$, $a_n$, the colours the professor chose for the first $n$ cubes.

-----Output:-----
Print a single line containing one integer $X$, the position Ali should initially stand on.

-----Constraints-----
- $1 \leq n \leq 10^{6}$
- $0 \leq a_i \leq 999$

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

3 3 8 8

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

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

2 8 7 3

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

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

n = int(input())
li = list(map(int, input().split()))
prev = None
for ind, z in enumerate(reversed(li)):
    if prev is not None:
        if z != prev[1]:
            break

        prev[0] = ind
    else:
        prev = [ind, z]
print(n - prev[0])


I found an interesting problem on https://www.codechef.com/MCOD2020/problems/MGOLD:
Uppal-balu is busy in extraction of gold from ores. He got an assignment from his favorite professor MH sir, but he got stuck in a problem. Can you help Uppal-balu to solve the problem.
You are given an array $a_1$, $a_2$, $\dots$, $a_n$ of length $n$. You can perform the following operations on it:
- Choose an index $i$ ($1 \leq i \leq n$), and replace $a_i$ by $a_{i} + 1$ or $a_{i} - 1$, which means add or subtract one to the element at index $i$.
Beauty of the array is defined as maximum length of a subarray containing numbers which give same remainder upon dividing it by $k$ (that is, ($a_l$ mod $k$) = ($a_{l+1}$ mod $k$) = $\dots$ = ($a_r$ mod $k$) for some $1 \leq l \leq r \leq n$).
You need to calculate the beauty of the array $a_1$, $a_2$, $\dots$, $a_n$ after applying at most $m$ operations.
NOTE:
- The subarray of a is a contiguous part of the array $a$, i. e. the array $a_l$, $a_{l+1}$, $\dots$, $a_r$ for some $1 \leq l \leq r \leq n$.
- $x$ mod $y$ means the remainder of $x$ after dividing it by $y$.

-----Input:-----
- First line of input contains 3 integers $n$, $m$ and $k$.
- The second line contains $n$ integers $a_1$, $a_2$, $\dots$, $a_n$.

-----Output:-----
Output in a single line the beauty of the array after applying at most m operations.

-----Constraints-----
- $1 \leq n,m \leq 2\cdot10^{5}$
- $1 \leq k \leq 7$
- $1 \leq a_i \leq 10^9$

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

8 2 3 7 8 1 1

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

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

7 2 1 3 6 5 6 2

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

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

t=1
for _ in range(t):
    n,m,k=(list(map(int,input().split())))
    a=list(map(int,input().split()))
    for i in range(n):
        a[i]=a[i]%k

    s=1
    for j in range(k):
        ss=0
        v=0
        for i in range(n):
            v+=min(abs(a[i]-j),k-abs(a[i]-j))
            while ss<i and v>m:
                v-=min(abs(a[ss]-j),k-abs(a[ss]-j))
                ss+=1
            s=max(s,i-ss+1)

    print(s)


I found an interesting problem on https://www.codechef.com/POPU2021/problems/EASYABC:
Alisha has a string of length n. Each character is either 'a', 'b' or 'c'. She has to select two characters s[i] and s[j] such that s[i] != s[j] and i,j are valid indexes. She has to find the maximum value of the absolute difference between i and j i.e abs(i-j) .
Since Alisha is busy with her Semester exams help her find the maximum distance where distance is the maximum value of absolute difference between i and j  i.e abs(i-j) .

-----Input:-----
- The first and the only line contains the string s with each character either 'a', 'b', or 'c'.

-----Output:-----
Print a single integer the maximum absolute difference between i and j.

-----Constraints-----
- $1 \leq n \leq 10^5$
- s[i] can either be 'a', 'b' or 'c'.

-----Subtasks-----
- 40 points : $1 \leq n \leq 100$
- 60 points : $1 \leq n \leq 10^5$

-----Sample Input1:-----
aabcaaa

-----Sample Output1:-----
4

-----Sample Input2:-----
aba

-----Sample Output2:-----
1

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

s = str(input().strip())
d = {}
d['a']=[]
d['b']=[]
d['c']=[]

for i in range(len(s)):
    d[s[i]].append(i)
ans = [0]
try:
    ans.append(abs(d["a"][0]-d["b"][-1]))
    ans.append(abs(d["b"][0]-d["a"][-1]))
except:
    pass
# if(len(d['a'])>0 and len(d['c'])>0):
try:
    ans.append(abs(d["a"][0]-d["c"][-1]))
    ans.append(abs(d["c"][0]-d["a"][-1]))
except:
    pass
# if(len(d['c'])>0 and len(d['b'])>0):
try:
    ans.append(abs(d["c"][0]-d["b"][-1]))
    ans.append(abs(d["b"][0]-d["c"][-1]))
except:
    pass
print(max(ans))


I found an interesting problem on https://www.codechef.com/POPU2021/problems/TSOH:
It is the last day of covid and you are coming back to your home with two empty sacks. On
the way to your home, you found Ambani brothers donating all their wealth in form of coins
after getting fed up with all the money they have. The coins have both positive and negative
values and they are laid down in a line. Now as you don’t want to go with an empty sack so
you also decided to take some of the money being given by Ambani’s. But anyone who
wants the money has to follow a rule that he/she can choose an only contiguous segment of
coins which are lying in a line (you can also imagine it like an array of coins) whether its value
is positive or negative.
Formally according to the rule if you are given an array [-1,2,3,4,2,0] you can only choose
subarrays like [2,3], [4,2,0], [-1] , [-1,2,3,4,2,0] etc.
Now as you have two siblings you decided to fill both the sacks with some coins. Your task is
to choose the coins in such a way that the sum of values of all the coins(including sacks 1
and 2) is maximum and both sacks are non-empty.
For e.g.:
If the array of coins is:
-1 2 3 4 -3 -5 6 7 1
Following are some ways you can choose the coins:
2 3 4 and -5 6 7
-1 2 3 and 6 7 1
2 3 4 and 6 7 1
and so on….
You can see that among the given ways the 3rd way will yield maximum values (2+3+4) +
(6+7+1)=23
Note:
Both the sack should be non-empty.
A subarray is a contiguous part of an array. An array that is inside another array.
A coin can be inserted in one and only one sacks i.e you cannot choose a coin more than one time.

-----Input:-----
- The first line contains $n$, the number of coins in the array $c$.
- The next line will contain $n$ space integers denoting the value $coin$ $c[i]$.

-----Output:-----
One and the only line containing the maximum possible sum of values of all the coins in
both sacks.

-----Constraints-----
- $2 \leq n \leq 10^5$
- $-10^5 \leq c[i] \leq 10^5$

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

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

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

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

-10 -1 -30 -40 -3...

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

# cook your dish here
# Python program to print largest contiguous array sum

from sys import maxsize

# Function to find the maximum contiguous subarray
# and print its starting and end index
def maxSubArraySum(a,size):

	max_so_far = -maxsize - 1
	max_ending_here = 0
	start = 0
	end = 0
	s = 0

	for i in range(0,size):

		max_ending_here += a[i]

		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
			start = s
			end = i

		if max_ending_here < 0:
			max_ending_here = 0
			s = i+1
	return max_so_far,start,end

# 	print("Maximum contiguous sum is %d"%(max_so_far))
# 	print("Starting Index %d"%(start))
# 	print("Ending Index %d"%(end))
    # return max_so_far,start,end

n = int(input())
lst = list(map(int,input().split()))
t_lst = lst[:]
aaa = abs(-n//2)
maxi,start,end = maxSubArraySum(lst[0:aaa],aaa)
# lst = lst[0:start]+lst[end+1:]
l = lst[aaa:]
M,st,en = maxSubArraySum(l,len(l))
x = maxi+M

maxi,start,end = maxSubArraySum(t_lst,n)
t_lst = t_lst[0:start]+t_lst[end+1:]
M,st,en = maxSubArraySum(t_lst,len(t_lst))
y = maxi+M

print(max(x,y))


I found an interesting problem on https://www.codechef.com/SPRT2020/problems/MXSCST:
Tim buy a string of  length N from his friend which consist of  ‘d’ and ‘u’ letters only
,but now Tim wants to sell the string at maximum cost.
The maximum cost of string is defined as the maximum length of a Substring (consecutive subsequence) consisting of equal letters.
Tim can change at most P characters of string (‘d’ to ‘u’   and   ‘u’ to ‘d’) you have to find out the maximum cost of string?

-----Input:-----
- First line will contain $N$ and $P$ .
- Second line will contain the String $S$.

-----Output:-----
Maximum cost of string S.

-----Constraints-----
- $1 \leq N\leq 10^5$
- $0 \leq P \leq N$

-----Sample Input 1:-----
4  2
$duud$

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

-----Sample Input 2 :-----
10 1
$dduddudddu$

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

-----EXPLANATION:-----
In the first sample input , We can obtain both strings $dddd$ and $uuuu$ .
In the second sample, the optimal answer is obtained with the string $dddddudd$ or with the string $dduddddd$

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

N, P = map(int, input().split())
S = [i == 'd' for i in input().strip()]

def calcMax(ar):
	j = c = ans = 0
	for i in range(len(ar)):
		while j < len(ar) and c + ar[j] <= P:
			c += ar[j]
			j += 1
		ans = max(ans, j - i)
		c -= ar[i]
	return ans

print(max(calcMax(S), calcMax([not _ for _ in S])))


I found an interesting problem on https://www.codechef.com/TEWE2020/problems/BINOD:
Binod and his family live in Codingland. They have a festival called N-Halloween.
The festival is celebrated for N  consecutive days. On each day Binod gets some candies from his mother. He may or may not take them. On a given day ,  Binod will be sad if he collected candies on that day and he does not have at least X   candies remaining  from the candies he collected that day at the end of that day . His friend Pelu who is very fond of candies asks for X  candies from Binod on a day if Binod collects any candy on that day. He does so immediately after Binod collects them. Binod being a good friend never denies him.

Given a list a   where ai   denotes the number of candies Binod may take on the ith   day and  Q  queries having a number X , find the maximum number of candies Binod can collect so that he won't be sad after the festival ends.
Input format:

First-line contains two integers N and Q denoting the number of festival days and number of queries respectively.

The second line is the array whose ith   element is the maximum number of candies Binod may
collect on that day.

Each of the next Q lines contains the number X i.e the minimum number of candies Binod wants to have at the end of every day on which he collects any candy.
Output format:

For every query output, a single integer denoting the max number of candies Binod may
collect (for the given X ) to be happy after the festival ends.
Constraints:

1<=N,Q<=105

1<=Q<=105

0<=ai<=109

0<=X<=109

Sample Input :

5 2

4 6 5 8 7

1

2

Sample Output :

30

30

Sample Input:

6 3

20 10 12 3 30 5

2

6

13

Sample Output

77

62

30

Explanation:

In the first query of sample input 1, Binod can collect the maximum number of given chocolates for a given day each day as after the end of every day Binod will have a number of collected
chocolates on that day greater than equal to 1 even after giving 1 chocolate to Pelu. So the
the answer is 4+6+5+8+7=30.

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

from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
 #------------------Sublime--------------------------------------#
 sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
 def I():return (int(input()))
 def In():return(map(int,input().split()))
else:
 #------------------PYPY FAst I/o--------------------------------#
 def I():return (int(stdin.readline()))
 def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
 d={}
 for x in a:
  if d.get(x,-1)!=-1:
   d[x]+=1
  else:
   d[x]=1
 return d
def find_gt(a, x):
 'Find leftmost value greater than x'
 i = bi.bisect_right(a, x)
 if i != len(a):
  return i
 else:
  return -1

def find_ge(a, x):
 'Find leftmost item greater than or equal to x'
 i = bi.bisect_left(a, x)
 if i != len(a):
  return i
 else:
  return -1
def main():
 try:
  n,Q=In()
  l=list(In())
  l.sort()
  pre=[0]
  su=0
  for x in range(n):
   su+=l[x]
   pre.append(su)
  #print(pre)
  for x in range(Q):
   q=I()
   q*=2
   pos=find_ge(l,q)
   #print(pos)
   if pos==-1:
    print(0)
   else:
    #print(pos)
    ans=pre[-1]-pre[pos]
    print(ans)
 except:
  pass

M = 998244353
P = 1000000007

def __starting_point():
 #for _ in range(I()):main()
 for _ in range(1):main()
__starting_point()


I found an interesting problem on https://www.codechef.com/TEWE2020/problems/FIXTHE:
You are given a string S  of numbers. Dr. Dragoon has eaten up some numbers of the string. You decide to fix the string by putting the numbers 0 and 1 in the empty spaces.
The base cost for putting the ‘0’  is x  and putting ‘1’  is y . The cost of putting a number is the base cost multiplied by the number of times you use the letter till  that position (including   the position ).  The local mayor is happy with your work and commissions you for every number you put.

More specifically ,  if you put , say 0  in 5th position, the mayor will count the number of occurrences of 0  till 5th   position and pay you the same amount. You wonder what the minimum cost for fixing the string is. Note  – The answer can also be negative, they denote that you got an overall profit.

Input Format:

The input consists of 2 lines. First-line consists of the string of numbers S. ‘?’  denotes an empty position.

The second line consists of 2 integers x,y, the base cost of 0 and 1.

Output Format:

Output 1 integer, the minimum cost of fixing the string.

Constraints :

1<=|S|<=100

1<=x,y<=100

Sample Input:

501?1?

6 5

Sample Output:

6

Sample Input:

1001?11?

5  23

Sample Output:

8

Explanation  :

Fill 0 in the first place, the net cost will be 6-2=4. In the second place fill, 1 the net cost will be 5-3=2 Hence total cost is 4+2=6.

In second test case we will fill both spaces with zero , filling first zero costs  1*5-3=2 and filling the other zero costs  2*5  - 4 =6  , so total being 8.

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

# cook your dish here
def ans(n,a,b):
    if n == act:
        return 0
    if dp[n][a][b] != -1:
        return dp[n][a][b]
    if l[n] == "0":
        dp[n][a][b]
        return ans(n+1,a+1,b)
    elif l[n] == "1":
        dp[n][a][b] = ans(n+1,a,b+1)
        return ans(n+1,a,b+1)
    elif l[n] == "?":
        dp[n][a][b] = min((a-l1[n]+1)*x -(a+1) + ans(n+1,a+1,b),(b-l2[n]+1)*y -(b+1) + ans(n+1,a,b+1))
        return(min((a-l1[n]+1)*x -(a+1) + ans(n+1,a+1,b),(b-l2[n]+1)*y -(b+1) + ans(n+1,a,b+1)))
    else:
        dp[n][a][b] = ans(n+1,a,b)
        return ans(n+1,a,b)

l = str(input())
x,y = map(int,input().split())
dp = [[[-1 for i in range(101)]for j in range(101)]for k in range(101)]
l1 = []
l2 = []
c = 0
k = 0
for i in l:
    if i == "1":
        c+=1
    if i == "0":
        k+=1
    l1.append(k)
    l2.append(c)
act = len(l)
dd = ans(0,0,0)
print(dd)


I found an interesting problem on https://www.codechef.com/TSTIND16/problems/AMR15A:
Kattapa, as you all know was one of the greatest warriors of his time. The kingdom of Maahishmati had never lost a battle under him (as army-chief), and the reason for that was their really powerful army, also called as Mahasena.
Kattapa was known to be a very superstitious person. He believed that a soldier is "lucky" if the soldier is holding an even number of weapons, and "unlucky" otherwise. He considered the army as "READY FOR BATTLE" if the count of "lucky" soldiers is strictly greater than the count of "unlucky" soldiers, and "NOT READY" otherwise.
Given the number of weapons each soldier is holding, your task is to determine whether the army formed by all these soldiers is "READY FOR BATTLE" or "NOT READY".
Note: You can find the definition of an even number here.

-----Input-----

The first line of input consists of a single integer N denoting the number of soldiers. The second line of input consists of N space separated integers A1, A2, ..., AN, where Ai denotes the number of weapons that the ith soldier is holding.

-----Output-----
Generate one line output saying "READY FOR BATTLE", if the army satisfies the conditions that Kattapa requires or "NOT READY" otherwise (quotes for clarity).

-----Constraints-----
- 1 ≤ N ≤ 100
- 1 ≤ Ai ≤ 100

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

Output:
NOT READY

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

Output:
READY FOR BATTLE

-----Example 3-----
Input:
4
11 12 13 14

Output:
NOT READY

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

Output:
READY FOR BATTLE

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

Output:
NOT READY

-----Explanation-----

- Example 1: For the first example, N = 1 and the array A = [1]. There is only 1 soldier and he is holding 1 weapon, which is odd. The number of soldiers holding an even number of weapons = 0, and number of soldiers holding an odd number of weapons = 1. Hence, the answer is "NOT READY" since the number of soldiers holding an even number of weapons is not greater than the number of soldiers holding an odd number of weapons.

- Example 2: For the second...

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

T=eval(input())
t=list(map(int,input().strip().split()))
c=0
for i in t:
    if i%2==0:
        c=c+1

if c>len(t)-c:
    print("READY FOR BATTLE")
else:
    print("NOT READY")


I found an interesting problem on https://www.codechef.com/WNTR2020/problems/WC01:
The lockdown hasn’t been great for our chef as his restaurant business got sabotaged because of lockdown, nevertheless no worries our chef is a multi-talented guy. Chef has decided to be a freelancer and work remotely. According to chef’s maths, he should be able to work on maximum tasks assuming that he can only work on a single task at a time.
Assume that chef does N tasks. The start and finish time units of those tasks are given. Select the maximum number of tasks that can be performed by a chef, assuming that a he can only work on a single task at a time.

-----Input:-----
- The first input contains of size of array N representing the total number of tasks.
- The second and third lines contains N space-seperated integers representing the starting and finish time of the the tasks.

-----Output:-----
A single line containing indices of tasks that chef will be able to do.

-----Constraints-----
- $1 \leq N \leq 10^5$
- Note: The lists have been sorted based on the ending times of the tasks.

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

10 12 20

20 25 30

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

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

1 2 0 6 3 7

2 4 5 7 9 10

-----Sample Output 2:-----
0  1  3  5

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

# cook your dish here
size = int(input())
starting_times = list(map(int, input().split()))
ending_times = list(map(int, input().split()))

tasks_indices_set = set()

last_timing = 0

for i in range(size):
    # print("Index:", i, "& last_timing:", last_timing)
    # if i==0: tasks_indices_set.add(i)
    if starting_times[i]>=last_timing:
        tasks_indices_set.add(i)
        last_timing = ending_times[i]
        for j in range(i+1, size):
            if ending_times[i]<=starting_times[j]:
                tasks_indices_set.add(j)
                last_timing = ending_times[j]
                break

print(*sorted(tasks_indices_set))


I found an interesting problem on https://www.codechef.com/ZCOPRAC/problems/ZCO13004:
Zonal Computing Olympiad 2013, 10 Nov 2012

Spaceman Spiff has crash landed on Planet Quorg. He has to reach his ship quickly. But the evil Yukbarfs have stolen many Death Ray Blasters and have placed them along the way. You'll have to help him out!

Spaceman Spiff is initially at the top left corner (1,1) of a rectangular N × M grid . He needs to reach the bottom right corner (N,M). He can only move down or right. He moves at the speed of 1 cell per second. He has to move every second—that is, he cannot stop and wait at any cell.

There are K special cells that contain the Death Ray Blasters planted by the Yukbarfs. Each Blaster has a starting time t and a frequency f.  It first fires at time t seconds, followed by another round at time t+f seconds, then at time t+2f seconds ….  When a Blaster fires, it simultaneously emits four pulses, one in each of the four directions: up, down, left and right.  The pulses travel at 1 cell per second.

Suppose a blaster is located at (x,y) with starting time t and frequency f.  At time t seconds, it shoots its first set of pulses. The pulse travelling upwards will be at the cell (x,y-s) at time t+s seconds.  At this time, the pulse travelling left will be at cell (x-s,y), the pulse travelling right will be at cell (x+s,y) and the pulse travelling down will be at cell (x,y+s).  It will fire next at time t+f seconds.  If a pulse crosses an edge of the grid, it disappears. Pulses do not affect each other if they meet. They continue along their original path. At any time, if Spaceman Spiff and a pulse are in the same cell, he dies. That is the only way pulses interact with Spaceman Spiff. Spaceman Spiff can also never be on a cell which has a blaster. Given these, you should find the least time (in seconds) in which Spaceman Spiff can reach his ship safely.

As an example consider a 4×4 grid that has only one Blaster, at (3,2), with starting time 1 and frequency 3.  In the grids below, S denotes Spaceman Spiff, B denotes the blaster and P denotes a pulse.  The sequence of...

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

from sys import stdin
ip = lambda :[int(w) for w in stdin.readline().split()]

n,m,k = [int(w) for w in stdin.readline().split()]
sp = 2 if k == 1 else 0
dp = [[1]*(m+1) for j in range(n+1)]
for j in range(k):
    x,y,t,f = [int(w) for w in stdin.readline().split()]
    dp[x][y] = 0
    for i in range(1,n+1):
        reach = i + y -2 - t - abs(x-i) +sp
        if reach > 0 and reach % f == 0:
            dp[i][y] = 0
    for i in range(1,m+1):
        reach = i + x -2 - t - abs(y-i) +sp
        if reach > 0 and reach % f == 0:
            dp[x][i] = 0
for i in range(1,n+1):
    for j in range(1,m+1):
        cur,left,up = dp[i][j],dp[i][j-1],dp[i-1][j]
        dp[i][j] = cur*left or cur*up

if dp[-1][-1]:
    print("YES")
    print(n+m-2)
else:
    print("NO")


I found an interesting problem on https://www.codechef.com/ZCOPRAC/problems/ZCO15003:
Zonal Computing Olympiad 2015, 29 Nov 2014

An interval is a pair of positive integers [a, b] with a ≤ b. It is meant to denote the set of integers that lie between the values a and b. For example [3,5] denotes the set {3,4,5} while the interval [3, 3] denotes the set {3}.

We say that an interval [a, b] is covered by an integer i, if i belongs to the set defined by [a, b]. For example interval [3, 5] is covered by 3 and so is the interval [3, 3].

Given a set of intervals I, and a set of integers S we say that I is covered by S if for each interval [a, b] in I there is an integer i in S such that [a, b] is covered by i. For example, the set {[3, 5], [3, 3]} is covered by the set {3}. The set of intervals {[6, 9], [3, 5], [4, 8]} is covered by the set {4, 5, 8}. It is also covered by the set {4, 7}.

We would like to compute, for any set of intervals I, the size of the smallest set S that covers it. You can check that for the set of intervals {[6, 9], [3, 5], [4, 8]} the answer is 2 while for the set of intervals {[3, 5], [3, 3]} the answer is 1.

Your program should take the set of intervals as input and output the size of the smallest set that covers it as the answer.

-----Input format-----
The first line contains a single integer N, giving the number of intervals in the input.

This is followed by N lines, each containing two integers separated by a space describing an interval, with the first integer guaranteed to be less than or equal to the second integer.

-----Output format-----
Output a single integer giving the size of the smallest set of integers that covers the given set of intervals.

-----Test data-----
You may assume that all integers in the input are in the range 1 to 10^8 inclusive.

Subtask 1 (100 marks) : 1 ≤ N ≤ 5000.

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

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

-----Sample Input 2-----
3
6 9
3 5
4 8

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

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

n = int(input())

chu = []
bs = []

mi = -1
count = 0

for _ in range(n):
	x,k = map(int, input().split())
	chu.append([x,k])

chu.sort()

for i in range(n):
	x = chu[i][0]
	k = chu[i][1]

	if x <= mi:
		mi = min(mi, k)
	else:
		count += 1
		mi = k

	#print(bs,chu)
print(count)


I found an interesting problem on https://www.codechef.com/problems/AMBOXES:
Andy got a box of candies for Christmas. In fact, he discovered that the box contained several identical smaller boxes, and they could contain even smaller boxes, and so on. Formally, we say that candies are boxes of level 0, and for 1 ≤ i ≤ n, a level i box contains ai boxes of level i - 1. The largest box has level n. Andy realized that it can take quite a long time to open all the boxes before he actually gets to eat some candies, so he put the box aside in frustration.

But today being his birthday, some friends came to visit Andy, and Andy decided to share some candies with them. In order to do that, he must open some of the boxes. Naturally, Andy can not open a box that is still inside an unopened box. If Andy wants to retrieve X candies, what is the least number of boxes he must open? You must help him answer many such queries. Each query is independent.

-----Input-----
- The first line contains two integers n and m, which refer to the level of the largest box, and the number of queries respectively.
- The second line contains n integers a1, ..., an.
- The third line contains m integers X1, ..., Xm.

-----Output-----
- Print m integers each in a new line, ith of them equal to the smallest number of boxes Andy must open in order to retrieve at least Xi candies.

-----Constraints-----
- 1 ≤ n,m ≤ 300000
- 1 ≤ ai ≤ 109
- 1 ≤ Xi ≤ 1012
- It is guaranteed that the total number of candies is at least Xi for all i

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

Output 1:
5

Input 2:
3 3
3 3 3
2 8 13

Output 2:
3
5
8

-----Explanation-----
Testcase 1: The only candy is contained in five levels of boxes.
Testcase 2: In the third query, for 13 candies, Andy should open the largest box, two level-2 boxes, and finally five of six available level-1 boxes. Each of those boxes will contain 3 level-0 boxes (which are candies). So he'll have 15 candies in total, but he needs only 13 of them.

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

n,m = map(int,input().split())
box = list(map(int,input().split()))
mularr = []
queries = list(map(int,input().split()))
qm = max(queries)
cnt = 0
mularr.append([box[0],1])
candy = box[0]
for b in box[1:]:
    if b == 1:
     mularr[-1][1] +=1
    else:
     candy *= b
     mularr.append([candy,1])
    if qm <= candy:
     break
#print(mularr)
for query in queries:
    cnt = n
    test = query
    test-=1
    for k,v in mularr:
     #print(mularr[m],test)
     add = (test//k)*v
     cnt+=add
    print(cnt)


I found an interesting problem on https://www.codechef.com/problems/ATM:
Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges).  For each successful withdrawal the bank charges 0.50 $US.

Calculate Pooja's account balance after an attempted transaction.

-----Input-----
Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw.

Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance.

-----Output-----
Output the account balance after the attempted transaction, given as a number with two digits of precision.  If there is not enough money in the account to complete the transaction, output the current bank balance.

-----Example - Successful Transaction-----
Input:
30 120.00

Output:
89.50

-----Example - Incorrect Withdrawal Amount (not multiple of 5)-----
Input:
42 120.00

Output:
120.00

-----Example - Insufficient Funds-----
Input:
300 120.00

Output:
120.00

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

# cook your dish here

x, y = input().split()
x=int(x)
y=float(y)

if x%5==0 and y-x>=0.5 :
    y = y - x - 0.5
print(y)


I found an interesting problem on https://www.codechef.com/problems/BALLCOL:
There are $n$ red balls kept on the positive $X$ axis, and $m$ blue balls kept on the positive $Y$ axis. You are given the positions of the balls. For each $i$ from $1$ to $n$, the $i$-th red ball has the coordinates $(x_i, 0)$, where $x_i$ is a positive integer. For each $i$ from $1$ to $m$, the $i$-th blue ball has the coordinates $(0, y_i)$, where $ y_i$ is a positive integer.
It is given that all $x_i$ are distinct. Also, all $y_i$ are distinct.
At the time $t= 0$, for each $i$ from $1$ to $n$, the $i^{\text{th}}$ red ball is thrown towards positive $Y$ axis with a speed of $u_i$( that is, with velocity vector $(0, u_i)$). Simultaneously (at time $t = 0$), for each $i$ from $1$ to $m$, the $i^{\text{th}}$ blue ball is thrown towards positive $X$ axis with a speed of $v_i$ (that is, with velocity vector $(v_i, 0)$).
Two balls are said to collide if they are at the same position at the same time. When two balls collide, they disappear, and hence no longer collide with other balls. (See sample examples for clarification).
Find the total number of collisions the balls will have.

-----Input-----
- First line contains $n$ and $m$, the number of red balls, and the number of blue balls, respectively.
- $i^{\text{th}}$  of the next $n$ lines contains two space separated integers $x_i$ and $u_i$, the position and speed of the $i^{\text{th}}$  red ball respectively
- $i^{\text{th}}$  of the next $m$ lines contains two space separated integers $y_i$ and $v_i$, the position and speed of the $i^{\text{th}}$  blue ball respectively

-----Output-----
Print the number of collisions.

-----Constraints-----
- $1 \le n, m \le 10^5$
- $1 \le x_i, u_i, y_i, v_i \le 10^9$
- for all $1 \le i < j \le n, x_i \neq x_j$
- for all $1 \le i < j \le m, y_i \neq y_j$

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

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

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

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

-----Explanation-----
Example case 1: The balls collide at t = 1, at the coordinates (1, 2).
Example case 2: The red ball and...

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

# cook your dish here
n,m=list(map(int,input().split()))
arr=[]
for i in range(n):
    l=list(map(int,input().split()))
    arr.append([l[0]*l[1],0,l[0]])
for i in range(m):
    l=list(map(int,input().split()))
    arr.append([l[0]*l[1],1,l[0]])
arr.sort()
i=0
ans=0
while(i<m+n):
    if(arr[i][1]==1):
        i+=1
    else:
        w=i
        for j in range(i,m+n+1):
            if(j!=m+n and arr[j][0]==arr[i][0]):
                if(arr[j][1]==1 and w==i):
                    w=j
            else:
                break
        ans+=min(w-i,j-w)
        i=j
print(ans)


I found an interesting problem on https://www.codechef.com/problems/BINTOUR:
Knights' tournaments were quite popular in the Middle Ages. A lot of boys were dreaming of becoming a knight, while a lot of girls were dreaming of marrying a knight on a white horse.

In this problem we consider one of these tournaments.

Let's us call a tournament binary, if it runs according to the scheme described below:

- Exactly N knights take part in the tournament, N=2K for some integer K > 0.

- Each knight has a unique skill called strength, described as an integer from the interval [1, N].

- Initially, all the knights are standing in a line, waiting for a battle. Since all their strengths are unique, each initial configuration can be described as a permutation of numbers from 1 to N.

- There are exactly K rounds in the tournament, 2K - i + 1 knights take part in the i'th round. The K'th round is called the final.

- The i'th round runs in the following way: for each positive integer j ≤ 2K - i happens a battle between a knight on the 2∙j'th position and a knight on the 2∙j+1'th position. The strongest of two continues his tournament, taking the j'th position on the next round, while the weakest of two is forced to leave.

- The only knight, who has won K rounds, is the winner. The only knight, who has won K - 1 rounds, but lost the final, is the runner-up.

As you can see from the scheme, the winner is always the same, an initial configuration doesn't change anything. So, your task is to determine chances of each knight to appear in the final.

Formally, for each knight you need to count the number of initial configurations, which will lead him to the final. Since the number can be extremly huge, you are asked to do all the calculations under modulo 109 + 9.

-----Input-----

The first line contains the only integer K, denoting the number of rounds of the tournament.

-----Output-----
Output should consist of 2K lines. The i'th line should contain the number of initial configurations, which lead the participant with strength equals to i to the final.

-----Constraints-----
1 ≤ K...

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

# cook your dish here
mod = 1000000009
import math
K = int(input())
N = 2 ** K
temp1 = N//2
fact = math.factorial((N/2-1))%mod
div = ((fact **2) * temp1)*N%mod
temp2 = 1
for i in range(1,N+1):
    if i < N/2:
        print("0")
    else:
        print(div)
        div = (((div * pow(temp2,mod-2,mod))%mod)*temp1)%mod
        temp1 += 1
        temp2+= 1


I found an interesting problem on https://www.codechef.com/problems/CHEFSOCK:
Today, Chef woke up to find that he had no clean socks. Doing laundry is such a turn-off for Chef, that in such a situation, he always buys new socks instead of cleaning the old dirty ones. He arrived at the fashion store with money rupees in his pocket and started looking for socks. Everything looked good, but then Chef saw a new jacket which cost jacketCost rupees. The jacket was so nice that he could not stop himself from buying it.

Interestingly, the shop only stocks one kind of socks, enabling them to take the unsual route of selling single socks, instead of the more common way of selling in pairs. Each of the socks costs sockCost rupees.

Chef bought as many socks as he could with his remaining money. It's guaranteed that the shop has more socks than Chef can buy. But now, he is interested in the question: will there be a day when he will have only 1 clean sock, if he uses a pair of socks each day starting tommorow? If such an unlucky day exists, output "Unlucky Chef", otherwise output "Lucky Chef". Remember that Chef never cleans or reuses any socks used once.

-----Input-----
The first line of input contains three integers — jacketCost, sockCost, money — denoting the cost of a jacket, cost of a single sock, and the initial amount of money Chef has, respectively.

-----Output-----
In a single line, output "Unlucky Chef" if such a day exists. Otherwise, output "Lucky Chef".

-----Constraints-----
- 1 ≤ jacketCost ≤ money ≤ 109
- 1 ≤ sockCost ≤ 109

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

Output:
Unlucky Chef

Input:
1 2 6

Output:
Lucky Chef

-----Subtasks-----
- Subtask 1:  jacketCost, money, sockCost ≤ 103. Points - 20
- Subtask 2: Original constraints. Points - 80

-----Explanation-----
Test #1:
When Chef arrived at the shop, he had 3 rupees. After buying the jacket, he has 2 rupees left, enough to buy only 1 sock.
Test #2:
Chef had 6 rupees in the beginning. After buying the jacket, he has 5 rupees left, enough to buy a pair of socks for 4 rupees.

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

# cook your dish here
jacketCost, sockCost, money=map(int, input().split())
money=money-jacketCost
if (money//sockCost)%2==0:
    print("Lucky Chef")
else:
    print("Unlucky Chef")


I found an interesting problem on https://www.codechef.com/problems/CHEFSQUA:
Chef loves squares! You are given N points with integers coordinates, Chef asks you to find out how many points he should add to these set of N points, so that one could create at least one square having its vertices from the points of the resulting set. Note that the square created need not to be parallel to the axis.

-----Input-----
The first line contains singe integer N.
Each of next N lines contains two integers Xi and Yi denotine the coordinates of i-th point.

-----Output-----
In a single line print single integer - the minimal number of points Chef need to paint to receive at least one square.

-----Constraints-----
- 0 ≤ N ≤ 2000
- -10^6 ≤ Xi, Yi ≤ 10^6
- There are NO coincided points

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

Output:
2

Input:
5
0 0
100 100
200 200
100 0
0 100

Output:
0

-----Explanation-----
For the first example Chef can add points (2, 0), (0, 2) or (2, 3), (3, 2)
For the second example Chef already has square (0, 0), (100, 0), (0, 100), (100, 100).

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

import sys
import math

def main(arr):
 ans=2
 if len(arr)<2:
  return 4-len(arr)
 set_arr=set(arr)
 for i in range(len(arr)):
  for j in range(i+1,len(arr)):
   need=2
   x1,y1=arr[i]
   x2,y2=arr[j]
   xc = (x1 + x2)/2  ;  yc = (y1 + y2)/2  ;
   xd = (x1 - x2)/2  ;  yd = (y1 - y2)/2  ;

   x3 = xc - yd  ;  y3 = yc + xd;
   x4 = xc + yd  ;  y4 = yc - xd;
   if (x3,y3) in set_arr:
    need-=1
   if (x4,y4) in set_arr:
    need-=1
   ans=min(ans,need)
 return ans

arr=[]
for i in range(int(input())):
 arr.append(tuple(map(int,input().split())))
print(main(arr))


I found an interesting problem on https://www.codechef.com/problems/CHEFZOT:
Chef loves research! Now he is looking for subarray of maximal length with non-zero product.
Chef has an array A with N elements: A1, A2, ..., AN.

Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj.
Product of subarray Aij is product of all its elements (from ith to jth).

-----Input-----
- First line contains sinlge integer N denoting the number of elements.
- Second line contains N space-separated integers A1, A2, ..., AN denoting the elements of array.

-----Output-----
- In a single line print single integer - the maximal length of subarray with non-zero product.

-----Constraints-----
- 1 ≤ N ≤ 100000
- 0 ≤ Ai ≤ 10000

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

Output:
2

Input:
1
0

Output:
0

Input:
3
1 0 1

Output:
1

-----Explanation-----
For the first sample subarray is: {2, 3}.
For the second sample there are no subbarays with non-zero product.
For the third sample subbarays is {1}, (the first element, or the third one).

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

n=int(input())
a=list(map(int,input().split()))
c=m=0
for i in range(n):
 if a[i]!=0:
  c+=1
 else:
  m=max(m,c)
  c=0
 #print(m,c,a[i])
m=max(m,c)
print(m)


I found an interesting problem on https://www.codechef.com/problems/CVOTE:
Chefs from all over the globe gather each year for an international convention. Each chef represents some country. Please, note that more than one chef can represent a country.
Each of them presents their best dish to the audience. The audience then sends emails to a secret and secure mail server, with the subject being the name of the chef whom they wish to elect as the "Chef of the Year".
You will be given the list of the subjects of all the emails. Find the country whose chefs got the most number of votes, and also the chef who got elected as the "Chef of the Year" (the chef who got the most number of votes).
Note 1
If several countries got the maximal number of votes, consider the country with the lexicographically smaller name among them to be a winner. Similarly if several chefs got the maximal number of votes, consider the chef with the lexicographically smaller name among them to be a winner.
Note 2
The string A = a1a2...an is called lexicographically smaller then the string B = b1b2...bm in the following two cases:
- there exists index i ≤ min{n, m} such that aj = bj for 1 ≤ j < i and ai < bi;
- A is a proper prefix of B, that is, n < m and aj = bj for 1 ≤ j ≤ n.
The characters in strings are compared by their ASCII codes.
Refer to function strcmp in C or to standard comparator < for string data structure in C++ for details.

-----Input-----
The first line of the input contains two space-separated integers N and M denoting the number of chefs and the number of emails respectively. Each of the following N lines contains two space-separated strings, denoting the name of the chef and his country respectively. Each of the following M lines contains one string denoting the subject of the email.

-----Output-----
Output should consist of two lines. The first line should contain the name of the country whose chefs got the most number of votes. The second line should contain the name of the chef who is elected as the "Chef of the Year".

-----Constraints-----
- 1 ≤ N ≤ 10000 (104)
- 1 ≤ M ≤ 100000 (105)
-...

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

N,M = [int(i) for i in input().split()]

get_country = {}
for i in range(N):
    name,country = input().split()
    get_country[name] = country

country_votes = {}
name_votes = {}
for i in range(M):
    name = input()
    country_votes[get_country[name]] = country_votes.get(get_country[name],0) + 1
    name_votes[name] = name_votes.get(name,0) + 1

win_country = None
votes = -float('inf')
for i,j in country_votes.items():
    if(j>votes):
        win_country = i
        votes = j
    elif(j==votes and i<win_country):
        win_country = i

win_name = None
votes = -float('inf')
for i,j in name_votes.items():
    if(j>votes):
        win_name = i
        votes = j
    elif(j==votes and i<win_name):
        win_name = i

print(win_country)
print(win_name)


I found an interesting problem on https://www.codechef.com/problems/DEVARRAY:
Devu has an array A consisting of N positive integers. He would like to perform following operation on array.

- Pick some two elements a, b in the array (a could be same as b, but their corresponding indices in the array should not be same).
Remove both the elements a and b and instead add a number x such that x lies between min(a, b) and max(a, b), both inclusive, (i.e. min(a, b) ≤ x ≤ max(a, b)).

Now, as you know after applying the above operation N - 1 times, Devu will end up with a single number in the array. He is wondering whether it is possible to do the operations in such a way that he ends up a number t.

He asks your help in answering Q such queries, each of them will contain an integer t and you have to tell whether it is possible to end up t.

-----Input-----
There is only one test case per test file.
First line of the input contains two space separated integers N, Q denoting number of elements in A and number of queries for which Devu asks your help, respectively
Second line contains N space separated integers denoting the content of array A.

Each of the next Q lines, will contain a single integer t corresponding to the query.

-----Output-----
Output Q lines, each containing "Yes" or "No" (both without quotes) corresponding to the answer of corresponding query.

-----Constraints-----
- 1 ≤ N, Q ≤ 105
- 0 ≤ t ≤ 109

-----Subtasks-----
Subtask #1 : 30 points
- 1 ≤ Ai ≤ 2

Subtask #2 : 70 points
- 1 ≤ Ai ≤ 109

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

Output:
Yes
No

Input 2:
2 4
1 3
1
2
3
4

Output:
Yes
Yes
Yes
No

-----Explanation-----
In the first example, Devu can't apply any operation. So the final element in the array will be 1 itself.

In the second example,
Devu can replace 1 and 3 with any of the numbers among 1, 2, 3. Hence final element of the array could be 1, 2 or 3.

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

def chk(a,q):
 l = a[0]
 m = a[len(a) - 1]
 if q >= l and q <= m :
  return("Yes")
 return "No"
def main():
 n,q=list(map(int,input().split()))
 A = list(map(int,input().split()))
 A.sort()
 while(q > 0):
  q-=1
  ques = int(input())
  print(chk(A,ques))

def __starting_point():
 main()

__starting_point()


I found an interesting problem on https://www.codechef.com/problems/DIGJUMP:
Chef loves games! But he likes to invent his own. Now he plays game "Digit Jump". Chef has a sequence of digits $S_{1}, S_{2}, \ldots , S_{N}$. He is staying in the first digit $S_{1}$ and wants to reach the last digit $S_{N}$ in the minimal number of jumps.
While staying in some index $i$ Chef can jump into $i - 1$ and $i + 1$, but he can't jump out from sequence. Or he can jump into any digit with the same value $S_i$.
Help Chef to find the minimal number of jumps he need to reach digit $S_{N}$ from digit $S_1$.

-----Input-----
Input contains a single line consist of string $S$ of length $N$ - the sequence of digits.

-----Output-----
In a single line print single integer - the minimal number of jumps he needs.

-----Constraints-----
- $1\leq N \leq 10^5$
- Each symbol of $S$ is a digit from $0$ to $9$.

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

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

-----Example Input 2-----
012134444444443

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

-----Explanation-----
Test Case 1: Chef can directly jump from the first digit (it is $0$) to the last (as it is also $0$).
Test Case 2: Chef should follow the following path: $1 - 2 - 4 - 5 - 15$.

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

from collections import defaultdict
a=input().strip()
n=len(a)
g=defaultdict(list)
for i in range(n):
 g[a[i]].append(i)
vis={}
vis[0]=0
q=[0]
while len(q)!=0:
 tmp=q.pop(0)
 if tmp==n-1:
  break
 val=a[tmp]
 s=len(g[val])
 for i in range(s):
  if g[val][i] not in vis:
   vis[g[val][i]]=vis[tmp]+1
   q.append(g[val][i])
 g[val]=[]
 if tmp+1<=n-1 and tmp+1 not in vis:
  q.append(tmp+1)
  vis[tmp+1]=vis[tmp]+1
 if tmp-1>=0 and tmp-1 not in vis:
  q.append(tmp-1)
  vis[tmp-1]=vis[tmp]+1
print(vis[n-1])


I found an interesting problem on https://www.codechef.com/problems/DIVIDING:
Are you fond of collecting some kind of stuff? Mike is crazy about collecting stamps. He is an active member of Stamp Collecting Сommunity(SCC).

SCC consists of N members which are fond of philately. A few days ago Mike argued with the others from SCC. Mike told them that all stamps of the members could be divided in such a way that i'th member would get i postage stamps. Now Mike wants to know if he was right. The next SCC meeting is tomorrow. Mike still has no answer.

So, help Mike! There are N members in the SCC, i'th member has Ci stamps in his collection. Your task is to determine if it is possible to redistribute C1 + C2 + ... + Cn stamps among the members of SCC thus that i'th member would get i stamps.

-----Input-----
The first line contains one integer N, denoting the number of members of SCC.
The second line contains N integers Ci, denoting the numbers of the stamps in the collection of i'th member.

-----Output-----
The first line should contain YES, if we can obtain the required division, otherwise NO.

-----Constraints-----
1 ≤ N ≤ 100 000;
1 ≤  Ci ≤ 109.

-----Examples-----
Input:
5
7 4 1 1 2

Output:
YES

Input:
5
1 1 1 1 1

Output:
NO

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

# cook your dish here
l=list()
n=int(input())
x=[int(item) for item in input().split()]
sum1=sum(x)
j=1
while n:
    l.append(j)
    j=j+1
    n=n-1
if sum1==sum(l)    :
    print("YES")
else:
    print("NO")


I found an interesting problem on https://www.codechef.com/problems/GARGOYLE:
There has been yet another murder in the Shady city of Riverdale. This murder is being investigated by none other than the Riverdale's Finest- Jughead Jones & Betty Cooper. This murder has been done exactly in the same manner as all the murders happening since the return of the deadly game Gargoyle &Griffins. Betty has decided to put an end to these murders, so they decide to interrogate each and every person in the neighbourhood.
As they don't know these people personally they want to first get to know about their character i.e whether a particular person is a Truth−speaking−person$Truth-speaking-person$ or a False−speaking−person$False-speaking-person$. Jughead devises a strategy of interrogating the civilians.
Jughead decides that they will collect statements from all the people in the neighbourhood about every other person living in the neighbourhood. Each person speaks a statement in form of an array consisting of T$T$ and F$ F$, which tells us what he thinks about the ith$ith$ person. Let there be N$N$ people living in the neighbourhood. So if a person i$i$ is giving his/her statement, he/her will always call himself/herself a True person i.e Statement[i]=T$Statement[i]=T$.
So Jughead says that they will select the maximum$maximum$ number$number$ of people that maybe speaking the truth such that their statements don't contradict and then interrogate them further about the murder.
Help them pick the max no. of Truth speaking people.
Note$Note$- A person speaking falsely$falsely$ doesn't mean that the complement of his statement would be the truth$truth$. If a person is declared false$false$(i.e not included in the set) after Betty and Jughead pick their set of truth speaking people with non-contradicting statements, the person declared false might not be speaking falsely$falsely$ about anyone(except saying he himself is a true$true$ speaking person which contradicts with the selected statements) but since the selected Set of statements feels him to be a false$false$ speaking person he won't be included...

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

# cook your dish here
testCases=int(input())
answers=[]
for i in range (testCases):
    a=input().split()
    answers.append(a)
count = 0
for i in range(testCases):
    flag = 0
    ans=answers[i].count('T')
    #print(answers[i])
    for j in range (testCases):
     if answers[i][j] =='T' and i!=j :
      if answers[i] == answers [j]:
       continue
      else:
  #           print("HII")
       flag=1
       break
    if flag==0 and count<ans:
     count=ans
print(count)


I found an interesting problem on https://www.codechef.com/problems/MATDYS:
Mathison has bought a new deck of cards that contains 2N cards, numbered and ordered from 0 to 2N-1.
Mathison is getting bored and decides to learn the Dynamo shuffle (or Sybil cut) - a flashy manner to shuffle cards. Unfortunately, the Dynamo shuffle is a little too complicated so Mathison decides to create his own shuffle.

This newly invented shuffle is done in N steps. At step k (0 ≤ k < N) the deck is divided into 2k equal-sized decks
where each one contains cards that lie on consecutive positions.
Each one of those decks is then reordered: all the cards that lie on even positions are placed first followed by all cards that lie on odd positions
(the order is preserved in each one of the two subsequences and all positions are 0-based). Then all the decks are put back together (preserving the order of decks).

Mathison has spent hours practising the shuffle and he now believes that he has perfected his technique. However, Chef doesn't believe him yet so he asks Mathison to answer Q questions that given a deck of size 2N where i-th card is labelled i, find the position of the card labelled K in the final, shuffled deck.

-----Input-----
The first line of the input file will contain one integer, Q, representing the number of Chef's questions.
Each of the next Q lines will contain a pair of integers, N and K.

-----Output-----
The output file will contain Q lines, each one representing the answer to one of Chef's questions.

-----Constraints-----
- 1 ≤ Q ≤ 1000
- 1 ≤ N ≤ 64
- 0 ≤ K < 2N

-----Subtaks-----
Subtask #1 (30 points):

- 1 ≤ N ≤ 10

Subtask #2 (30 points):

- 1 ≤ N ≤ 32

Subtask #3 (40 points):

- Original constraints

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

Output:
1
6
2

Input:
1
64 11047805202224836936

Output:
1337369305470044825

-----Explanation-----
In all questions, we have N = 3. Therefore, we have a deck with 8 cards.
The shuffling is done in three steps:

Step 0: We divide {0, 1, 2, 3, 4, 5, 6, 7} in 20 decks. We get only one deck.
The deck is reordered into {0, 2, 4, 6, 1, 3, 5,...

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

# cook your dish here
t = int(input())
while t>0:
 x = input().split()
 n = int(x[0])
 k = int(x[1])
 ans = 0
 for i in range(n):
  if (k&(1<<i))!=0:
   ans += 2**(n-i-1)
 print(ans, end="\n")
 t -= 1


I found an interesting problem on https://www.codechef.com/problems/MEXDIV:
Given an array A of n non-negative integers. Find the number of ways to partition/divide the array into subarrays, such that  mex in each subarray is not more than k. For example, mex of the arrays [1, 2] will be 0, and that of [0, 2] will be 1, and that of [0, 1, 2] will be 3. Due to the fact that the answer can turn out to be quite large, calculate it modulo 109 + 7.

-----Input-----
- The first line of the input contains two integers n, k denoting the number of elements and limit of mex.
- The second line contains n space-separated integers A1, A2, ... , An .

-----Output-----
- Output a single integer corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ n ≤ 5 * 105
- 0 ≤ k, A[i] ≤ 109

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

Output:
2

Input:
10 3
0 1 2 3 4 0 1 2 5 3

Output:
379

-----Explanation-----
Example 1. The valid ways of partitioning will be [[0], [1, 2]] (mex of first subarray is 1, while that of the second is zero), and [[0], [1], [2]] (mex of first subarray is 1, and that of others is 0). There is no other way to partition the array such that mex is less than or equal to 1. For example, [[0, 1], [2]] is not a valid partitioning as mex of first subarray is 2 which is more than 1.

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

n,k=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
cons=int(5e5+1)
mod=10**9+7
tpa=[1 for i in range(cons)]
tpa[0]=1
for i in range(1,cons):
    tpa[i]=(tpa[i-1]*2)%mod
if k>n:
    print(tpa[n-1])
else:
    il=[[]for i in range(k+1)]
    for i in range(n):
        if l[i]<=k:
            il[l[i]].append(i)
    for i in range(k+1):
        if len(il[i])==0:
            print(tpa[n-1])
            break
    else:
        pi=-1
        dp=[-1 for i in range(n)]
        dp[0]=1
        si=max(il,key=lambda x:x[0])[0]
        s=1
        for i in range(1,si):
            dp[i]=tpa[i]
            s=(s+dp[i])%mod
        ci=[0 for i in range(k+1)]
        j=si
        i=0
        while j<n:
            if l[i]>k :
                s=(s-dp[i])%mod
                i+=1
            elif ci[l[i]]+1<len(il[l[i]]) and il[l[i]][ci[l[i]]+1]<=j:
                s=(s-dp[i])%mod
                ci[l[i]]+=1
                i+=1
            else:
                dp[j]=s
                pi=i
                s=(s+dp[j])%mod
                j+=1
        print(dp[n-1])


I found an interesting problem on https://www.codechef.com/problems/MIKE1:
Mike is given a matrix A, N and M are numbers of rows and columns respectively. A1, 1 is the number in the top left corner. All the numbers in A are non-negative integers. He also has L pairs of integers (ik, jk). His task is to calculate Ai1, j1 + Ai2, j2 + ... + AiL, jL.

Unfortunately, Mike forgot if Ai, j was a number in the i'th row and j'th column or vice versa, if Ai, j was a number in the j'th row and i'th column.

So, Mike decided to calculate both E1 = Ai1, j1 + Ai2, j2 + ... + AiL, jL and E2 = Aj1, i1 + Aj2, i2 + ... + AjL, iL. If it is impossible to calculate E1(i.e. one of the summands doesn't exist), then let's assume, that it is equal to -1. If it is impossible to calculate E2, then let's also assume, that it is equal to -1.

Your task is to calculate max(E1, E2).

-----Input-----

The first line contains two integers N and M, denoting the number of rows and the number of columns respectively.

Each of next N lines contains M integers. The j'th integer in the (i + 1)'th line of the input denotes Ai, j.

The (N + 2)'th line contains an integer L, denoting the number of pairs of integers, that Mike has.

Each of next L lines contains a pair of integers. The (N + 2 + k)-th line in the input contains a pair (ik, jk).

-----Output-----
The first line should contain an integer, denoting max(E1, E2).

-----Examples-----
Input:
3 2
1 2
4 5
7 0
2
1 2
2 2
Output:
9

Input:
1 3
1 2 3
2
1 3
3 1
Output:
-1

Input:
1 3
1 2 3
2
1 1
3 1
Output:
4

-----Explanation-----

In the first test case N equals to 3, M equals to 2, L equals to 2. E1 = 2 + 5 = 7, E2 = 4 + 5 = 9. The answer is max(E1, E2) = max(7, 9) = 9;

In the second test case N equals to 1, M equals to 3, L equals to 2. It is impossible to calculate E1 and E2, because A3, 1 doesn't exist. So the answer is max(E1, E2) = max(-1, -1) = -1;

In the third test case N equals to 1, M equals to 3, L equals to 2. It is impossible to calculate E1, because A3, 1 doesn't exist. So E1 is equal to -1. E2 = 1 + 3 = 4. The answer is max(E1, E2) = max(-1,4) =...

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

# cook your dish here
n , m = map(int,input().split(" "))
arr = []
for i in range(n):
    arr.append([int(j) for j in input().split()])
l = int(input())
check = []
for i in range(l):
    a, b = map(int,input().split())
    check.append([a-1,b-1])

e1 , e2 = 0 , 0
for i in range(l):
    if e1 != -1:
        if check[i][0] < n and check[i][1] < m:
            e1 += arr[check[i][0]][check[i][1]]
        else:
            e1 = -1
    if e2 != -1:
        if check[i][0] < m and check[i][1] < n:
            e2 += arr[check[i][1]][check[i][0]]
        else:
            e2 = -1
print(max(e1,e2))


I found an interesting problem on https://www.codechef.com/problems/OJUMPS:
This morning Chef wants to jump a little. In a few minutes he will arrive at the point 0. Then he will perform a lot of jumps in such a sequence: 1-jump, 2-jump, 3-jump, 1-jump, 2-jump, 3-jump, 1-jump, and so on.
1-jump means that if Chef is at the point x, he will jump to the point x+1.
2-jump means that if Chef is at the point x, he will jump to the point x+2.
3-jump means that if Chef is at the point x, he will jump to the point x+3.
Before the start Chef asks you: will he arrive at the point a after some number of jumps?

-----Input-----

The first line contains a single integer a denoting the point Chef asks about.

-----Output-----
Output "yes" without a quotes if Chef can arrive at point a or "no" without a quotes otherwise.

-----Constraints-----

- 0 ≤ a ≤ 1018

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

Output:
yes

Input:
1

Output:
yes

Input:
2

Output:
no

Input:
3

Output:
yes

Input:
6

Output:
yes

Input:
7

Output:
yes

Input:
10

Output:
no

-----Explanation-----
The first reached points are: 0 (+1) 1 (+2) 3 (+3) 6 (+1) 7, and so on.

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

n = int(input())
if n == 0 or n == 1:
 print('yes')
elif n % 3 == 0:
 print('yes')
elif n % 6 == 1:
 print('yes')
else:
 print('no')


I found an interesting problem on https://www.codechef.com/problems/PCJ18D:
Chef is baking delicious cookies today! Since Chef is super hungry, he wants to eat at least $N$ cookies.
Since Chef is a messy eater, he drops a lot of crumbs. Crumbs of $B$ cookies can be put together to make a new cookie!
Given $N$ and $B$, help Chef find out the minimum number of cookies he must initially bake, $A$, to satisfy his hunger.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of  two space separated integers $N, B$.

-----Output:-----
For each test case, print a single integer $A$, the minimum number of cookies Chef must bake initially.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 1000000000$
- $2 \leq B \leq 1000000000$

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

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

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

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

-----Explanation 2:-----
Chef initially make 6 cookies. From the crumbs, Chef makes 3 new cookies with no crumbs left over. From the crumbs of the new cookies, Chef makes 1 new cookie and have crumbs left from one cookie. From the new cookie, Chef gets more crumbs. He adds the crumbs and gets one last cookie. After eating that, there are not enough crumbs left to make a new cookie. So a total of 11 cookies are consumed!

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

t=int(input())
for i in range(t):
 n,b=map(int,input().split())
 a=n-n//b
 if(n%b==0):
  a=a+1
 print(a)


I found an interesting problem on https://www.codechef.com/problems/RAINBOWB:
Chef loves arrays. But he really loves a specific kind of them - Rainbow Arrays.
The array is a Rainbow Array if it has such a structure:
- The first a1 elements equal to 1.
- The next a2 elements equal to  2.
- The next a3 elements equal to  3.
- The next a4 elements equal to  4.
- The next a5 elements equal to  5.
- The next a6 elements equal to  6.
- The next a7 elements equal to  7.
- The next a6 elements equal to  6.
- The next a5 elements equal to  5.
- The next a4 elements equal to  4.
- The next a3 elements equal to  3.
- The next a2 elements equal to  2.
- The next a1 elements equal to  1.
- ai is a positive integer, the variables with the same index (a1 in the first statement and a1 in the last one, for example) are equal.
- There are no any other elements in array.

For example, {1,1,2,2,2,3,4,5,5,6,7,7,7,6,5,5,4,3,2,2,2,1,1} is a Rainbow Array.

The array {1,2,3,4,5,6,7,6,6,5,4,3,2,1} is not a Rainbow Array, because the sizes of the blocks with the element 6 are different.
Please help Chef to count the number of different Rainbow Arrays that contain exactly N elements.

-----Input-----
The first line contains a single integer N.

-----Output-----
Output the number of different Rainbow Arrays with N elements, modulo 10^9+7.

-----Constraints-----
- 1 ≤ N ≤ 106

-----Example-----
Input #1:
10

Output #1:
0

Input #2:
13

Output #2:
1

Input #3:
14

Output #3:
1

Input #4:
15

Output #4:
7

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

mod = 10**9 + 7
n = int(input())
fiveFac = 120

def solve(a) :
	ab2 = a/2
	return nC5(ab2 - 1)

def nC5(k) :
	res = (k-4)*(k)*(k-1)*(k-2)*(k-3)
	res = res/120
	return res

if n < 13 :
	print(0)
elif n == 13 :
	print(1)

else :
	a7Max = n-12 + 1
	if n%2 == 1 :
		ans = 0
		for a7 in range(1,a7Max,2) :
			rest = n - a7
			ans += solve(rest)
			ans = ans%mod
		print(ans%mod)

	else :
		ans = 0
		for a7 in range(2,a7Max,2) :
			rest = n - a7
			ans += solve(rest)
			ans = ans%mod
		print(ans%mod)


I found an interesting problem on https://www.codechef.com/problems/SAD:
Our Chef is very happy that his son was selected for training in one of the finest culinary schools of the world.
So he and his wife decide to buy a gift for the kid as a token of appreciation.
Unfortunately, the Chef hasn't been doing good business lately, and is in no mood on splurging money.
On the other hand, the boy's mother wants to buy something big and expensive.
To settle the matter like reasonable parents, they play a game.

They spend the whole day thinking of various gifts and write them down in a huge matrix.
Each cell of the matrix contains the gift's cost.
Then they decide that the mother will choose a row number r while the father will choose a column number c,
the item from the corresponding cell will be gifted to the kid in a couple of days.

The boy observes all of this secretly.
He is smart enough to understand that his parents will ultimately choose a gift whose cost is smallest in its row,
but largest in its column.
If no such gift exists, then our little chef has no option but to keep guessing.
As the matrix is huge, he turns to you for help.

He knows that sometimes the gift is not determined uniquely even if a gift exists whose cost is smallest in its row,
but largest in its column.
However, since the boy is so smart, he realizes that the gift's cost is determined uniquely.
Your task is to tell him the gift's cost which is smallest in its row,
but largest in its column, or to tell him no such gift exists.

-----Input-----
First line contains two integers R and C, the number of rows and columns in the matrix respectively. Then follow R lines, each containing C space separated integers - the costs of different gifts.

-----Output-----
Print a single integer - a value in the matrix that is smallest in its row but highest in its column. If no such value exists, then print "GUESS" (without quotes of course)

-----Constraints-----
1 <= R, C <= 100
All gift costs are positive and less than 100000000 (10^8)

-----Example 1-----
Input:
2 3
9 8 8
2 6 11

Output:
8

-----Example...

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

# cook your dish here
r,c=list(map(int,input().split(" ")))

mat=[]
small_mat=[]
result="GUESS"

for i in range(r):
    data=list(map(int,input().split(" ")))
    small_mat.append(min(data))
    mat.append(data)

for i in range(r):
    for j in range(c):
        if mat[i][j]==small_mat[i]:
            temp_data=[]
            for k in range(r):
                temp_data.append(mat[k][j])

            if max(temp_data)==small_mat[i]:
                result=small_mat[i]
                break
print(result)


I found an interesting problem on https://www.codechef.com/problems/TOURISTS:
The grand kingdom of Mancunia is famous for its tourist attractions and visitors flock to it throughout the year. King Mancunian is the benevolent ruler of the prosperous country whose main source of revenue is, of course, tourism.

The country can be represented by a network of unidirectional roads between the cities. But Mancunian, our benign monarch, has a headache. The road network of the country is not tourist-friendly and this is affecting revenue. To increase the GDP of the nation, he wants to redirect some of the roads to make the road network tourist-friendly and hence, ensure happiness and prosperity for his loyal subjects.

Now is the time for some formal definitions. :(

A road network is said to be tourist-friendly if for every city in the country, if a tourist starts his journey there, there is a path she can take to visit each and every city of the nation and traverse each road exactly once before ending up at the city where she started.

Given a description of the road network of Mancunia, can you come up with a scheme to redirect some (possibly none) of the roads to make it tourist-friendly?

-----Input-----
The first line contains two integers N and E denoting the number of cities and roads in the beautiful country of Mancunia respectively.
Each of the next E lines contains two integers a and b implying that there is a unidirectional road from city a to city b.

It is guaranteed that there aren't multiple roads in the exact same direction and that there is no road from a city to itself.

-----Output-----
If there is no solution, print "NO" (without quotes). Else, print "YES" (without quotes), followed by exactly E lines.
The ith line of output should represent the ith road in the input. It should have two integers a and b denoting that the final orientation of that road is from a to b.

-----Constraints-----

- 1 ≤ N ≤ 100000
- 1 ≤ E ≤ 200000
- 1 ≤ a, b ≤ N

Subtask 1: (20 points)
- 1 ≤ N ≤ 20
- 1 ≤ E ≤ 21

Subtask 2: (80 points)
- Same as original constraints

-----Example 1-----
Input:
3...

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

class Graph(object):
	"""docstring for Graph"""
	def __init__(self, vertices):
		self.vertices = vertices
		graph = dict()
		for i in range(1, vertices+1):
			graph[i] = []
		self.graph = graph

	def add_edge(self,a,b):
		self.graph[a].append(b)
		self.graph[b].append(a)

	def eulerPath(self):
		g = self.graph
		odd = [k for k, v  in g.items() if len(v)%2 == 1]
		if len(odd) == 0 :
			odd = [list(g.keys())[0]]
		elif len(odd) == 1 or len(odd) > 2 :
			return None
		path = []
		stack = [odd[-1]]
		while stack:
			u = stack[-1]
			if g[u]:
				v = g[u][0]
				del g[u][0]
				del g[v][g[v].index(u)]
				stack.append(v)
			else:
				path.append(stack.pop())
		return path

n, e = map(int, input().strip().split())
g = Graph(n)

u = []
v = []

for i in range(e):
	a, b = map(int, input().strip().split())
	g.add_edge(a,b)
	u.append(a)
	v.append(b)

ans = g.eulerPath()

if ans is None:
	print('NO')
else:
	if len(ans) == (e+1) and ans[0] == ans[-1]:
# 		print(ans)
		print("YES")
		temp_dict = {}
		for i in range(len(ans)-1,0,-1):
			if ans[i] in temp_dict:
				temp_dict[ans[i]][ans[i-1]] = True
			else:
				temp_dict[ans[i]] = {ans[i-1]:True}
		for i in range(e):
			if u[i] in temp_dict and v[i] in temp_dict[u[i]]:
				print(u[i] , v[i])
			else:
				print(v[i], u[i])
	else:
		print("NO")


I found an interesting problem on https://www.codechef.com/problems/TWODOGS:
In Chef's house there are N apples lying in a row on the floor. These apples are numbered from 1 (left most one) to N (right most one). The types of apples are also numbered by positive integers, and the type of apple i is Ti.
Chef has recently brought two trained dogs. Both of the dogs are too intelligent to know the smell of each type of apple. If Chef gives a dog an integer x, and releases it at one end of the row of apples, then the dog smells each apple one by one. Once the dog find an apple of type x, the dog picks the apple and back to Chef's room immidiately. If there is no apple of type x, then the dog will back without any apples.
Now Chef wants to eat two apples as soon as possible. Here the apples must have distinct types, and the sum of the types must be equal to K. Chef can release the dogs from either of the ends, namely, he can leave (both at left end) or (both at right end) or (one at left end and one at right end) and he can release them at the same time. The dogs take one second to smell each apple. However the dogs can run rapidly, so the time for moving can be ignored. What is the minimum time (in seconds) to get the desired apples from his dogs?

-----Input-----
The first line of input contains two space-separated integers N and K, denoting the number of apples and the required sum respectively. Then the next line contains N space-separated integers T1, T2, ..., TN, denoting the types of the apples.

-----Output-----
Print one integer describing the minimum number of seconds that Chef needs to wait till he gets the desired apples. If Chef cannot get the desired apples, then output "-1" without quotes.

-----Constraints-----
- 2 ≤ N ≤ 500000 (5 × 105)
- 1 ≤ K ≤ 1000000 (106)
- 1 ≤ Ti ≤ 1000000 (106)

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

Sample Output 1:
2

Sample Input 2:
5 5
2 4 9 2 5

Sample Output 2:
-1

-----Explanation-----
In the first example, if Chef leaves the first dog from left and gives it integer 4, and the second dog from right and gives it integer 1, then the...

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

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

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

# l = []
#
# for i in range(len(la)):
#        l.append([la[i],i])
# l.sort()
mini = 10**18
# i = 0
# j = len(l)-1
# # print(l)
# while i<j:
#     if l[i][0]+l[j][0]<k:
#         i+=1
#     elif l[i][0]+l[j][0]>k:
#         j-=1
#     else:
#         if l[i][0]+l[j][0]==k:
#
#             z1,z2 = max(l[i][1],l[j][1]),min(l[i][1],l[j][1])
#             ans1 = max(z1,z2)+1
#             ans2 = max(n-z1,n-z2)
#             ans3 = max(n-z1,z2+1)
#             ans4 = max(z1+1,n-z2)
#             # print(l[i][0],l[j][0])
#             if l[i][0]!=l[j][0]:
#              mini = min(mini,ans1,ans2,ans3,ans4)
#             j-=1
#             i+=1
#
# if mini == 10**18:
#     print(-1)
# else:
#     print(mini)

#
# from collections import defaultdict
# INF = float("inf")
#
# n,k = map(int,input().split())
# t = list(map(int,input().split()))
# d = defaultdict(int)
# for i in range(n):
#     x = i+1 if i<n/2 else n-i
#     if d[t[i]]:
#         d[t[i]] = min(d[t[i]],x)
#     else:
#         d[t[i]] = x
# ans = INF
# for i in range(n):
#     if d[k-t[i]] and t[i] != k-t[i]:
#         ans = min(ans,max(d[k-t[i]],d[t[i]]))
# print(-1 if ans == INF else ans)
#
#
#
from collections import defaultdict

hash = defaultdict(int)

for i in range(len(la)):
 z1 = i+1
 z2 = n-i
 z = min(z1,z2)
 if la[i] in hash:
  hash[la[i]] = min(z,hash[la[i]])
 else:
  hash[la[i]] = z

for i in range(len(la)):
 z = k-la[i]
 if z in hash and z!=la[i]:
  ans = max(hash[z],hash[la[i]])
  mini = min(mini,ans)

if mini == 10**18:
 print(-1)
else:
 print(mini)


I found an interesting problem on https://www.codechef.com/problems/URCALC:
Write a program to obtain 2 numbers $($ $A$ $and$ $B$ $)$ and an arithmetic operator $(C)$ and then design a $calculator$ depending upon the operator entered by the user.
So for example if C="+", you have to sum the two numbers.
If C="-", you have to subtract the two numbers.
If C=" * ", you have to print the product.
If C=" / ", you have to divide the two numbers.

-----Input:-----
- First line will contain the first number $A$.
- Second line will contain the second number $B$.
- Third line will contain the operator $C$, that is to be performed on A and B.

-----Output:-----
Output a single line containing the answer, obtained by, performing the operator on the numbers. Your output will be considered to be correct if the difference between your output and the actual answer is not more than $10^{-6}$.

-----Constraints-----
- $-1000 \leq A \leq 1000$
- $-1000 \leq B \leq 1000$ $and$ $B \neq 0$
- $C$ $can$ $only$ $be$ $one$ $of$ $these$ $4$ $operators$ {" + ", " - ", " * ", " / "}

-----Sample Input:-----
8
2
/

-----Sample Output:-----
4.0

-----Sample Input:-----
5
3
+

-----Sample Output:-----
8

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

a=int(input())
b=int(input())
c=input()
if c=="+":
 print(a+b)
elif c=="-":
 print(a-b)
elif c=="*":
 print(a*b)
elif c=="/":
 print(a/b)


I found an interesting problem on https://www.hackerrank.com/challenges/class-1-dealing-with-complex-numbers/problem:
=====Problem Statement=====
For this challenge, you are given two complex numbers, and you have to print the result of their addition, subtraction, multiplication, division and modulus operations. The real and imaginary precision part should be correct up to two decimal places.

=====Input Format=====
One line of input: The real and imaginary part of a number separated by a space.

=====Output Format=====
For two complex numbers C and D, the output should be in the following sequence on separate lines:
C+D
C-D
C*D
C/D
mod(C)
mod(D)

For complex numbers with non-zero real (A) and complex part (B), the output should be in the following format:
Replace the plus symbol (+) with a minus symbol (-) when B<0.
For complex numbers with a zero complex part i.e. real numbers, the output should be:
A+0.00i
For complex numbers where the real part is zero and the complex part is non-zero, the output should be:
0.00+Bi

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

import numbers

r1, i1 = map(float, input().split())
r2, i2 = map(float, input().split())
c1 = complex(r1, i1)
c2 = complex(r2, i2)

def printer(c):
    real = c.real
    imag = c.imag

    sign = '+' if imag >= 0 else '-'
    print('{:.2f}{}{:.2f}i'.format(real, sign, abs(imag)))

def mod(c):
    return (c.real * c.real + c.imag * c.imag) ** 0.5

printer(c1 + c2)
printer(c1 - c2)
printer(c1 * c2)
printer(c1 / c2)
print('{:.2f}+0.00i'.format(mod(c1)))
print('{:.2f}+0.00i'.format(mod(c2)))


I found an interesting problem on https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle/problem:
=====Problem Statement=====
You are given four points A, B, C and D in a 3-dimensional Cartesian coordinate system. You are required to print the angle between the plane made by the points A, B, C and B, C, D in degrees(not radians). Let the angle be PHI.
Cos(PHI) = (X.Y)/|X|Y| where X = AB x BC and Y = BC x CD.
Here, X.Y means the dot product of X and Y, and AB x BC means the cross product of vectors AB and BC. Also, AB = B-A.

=====Input Format=====
One line of input containing the space separated floating number values of the and coordinates of a point.

=====Output Format=====
Output the angle correct up to two decimal places.

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

# Enter your code here. Read input from STDIN. Print output to STDOUT

import math
def custom_diff(a,b):
    res0 = a[0] - b[0]
    res1 = a[1] - b[1]
    res2 = a[2] - b[2]
    return [res0,res1,res2]

def dot_product(a,b):
    return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]

def abs_val(a):
    tmp_val=a[0]*a[0]+a[1]*a[1]+a[2]*a[2]
    return math.sqrt(tmp_val)

def cross(a, b):
    c = [a[1]*b[2] - a[2]*b[1],
         a[2]*b[0] - a[0]*b[2],
         a[0]*b[1] - a[1]*b[0]]

    return c

a_str_ar=input().strip().split()
b_str_ar=input().strip().split()
c_str_ar=input().strip().split()
d_str_ar=input().strip().split()

a=list(map(float,a_str_ar))
b=list(map(float,b_str_ar))
c=list(map(float,c_str_ar))
d=list(map(float,d_str_ar))

ab=custom_diff(b,a)
bc=custom_diff(c,b)
cd=custom_diff(d,c)

x=cross(ab,bc)
y=cross(bc,cd)

cosphi_top=dot_product(x,y)
cosphi_bottom=abs_val(x)*abs_val(y)
cosphi=cosphi_top/cosphi_bottom

res=math.degrees(math.acos(cosphi))

print(("%.2f" %res))


I found an interesting problem on https://www.hackerrank.com/challenges/decorators-2-name-directory/problem:
=====Problem Statement=====
Let's use decorators to build a name directory! You are given some information about N people. Each person has a first name, last name, age and sex ('M' or 'F'). Print their names in a specific format sorted by their age in ascending order i.e. the youngest person's name should be printed first. For two people of the same age, print them in the order of their input.

For Henry Davids, the output should be:
Mr. Henry Davids

For Mary George, the output should be:
Ms. Mary George

=====Input Format=====
The first line contains the integer N, the number of people. N lines follow each containing the space separated values of the first name, last name, age and sex, respectively.

=====Constraints=====
1≤N≤10

=====Output Format=====
Output N names on separate lines in the format described above in ascending order of age.

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

# Enter your code here. Read input from STDIN. Print output to STDOUT
ar=[]
n=int(input())
for i in range(0,n):
    str_ar=input().strip().split()
    user_name=str_ar[0]+" "+str_ar[1]
    user_age=int(str_ar[2])
    user_sex=str_ar[3]
    user_new_name=""
    if(user_sex=="M"):
        user_new_name="Mr. "+user_name
    else:
        user_new_name="Ms. "+user_name
    ar.append([user_new_name,user_age])

l = sorted(ar, key=lambda tup: tup[1])
for i in range(0,n):
    print((l[i][0]))