Solve in Python:
Anas is playing an amazing game on a grid with $N$ rows and $M$ columns. The rows are numbered $1$ through $N$ from top to bottom and the columns are numbered $1$ through $M$ from left to right.
Anas wants to destroy this grid. To do that, he wants to send two heroes from the top left cell to the bottom right cell:
- The first hero visits cells in row-major order: $(1,1) \rightarrow (1,2) \rightarrow \ldots \rightarrow (1,M) \rightarrow (2,1) \rightarrow (2,2) \rightarrow \ldots \rightarrow (2,M) \rightarrow \ldots \rightarrow (N,M)$.
- The second hero visits cells in column-major order: $(1,1) \rightarrow (2,1) \rightarrow \ldots \rightarrow (N,1) \rightarrow (1,2) \rightarrow (2,2) \rightarrow \ldots \rightarrow (N,2) \rightarrow \ldots \rightarrow (N,M)$.
We know that each hero destroys the first cell he visits, rests in the next $K$ cells he visits without destroying them, then destroys the next cell he visits, rests in the next $K$ cells, destroys the next cell, and so on until he reaches (and rests in or destroys) the last cell he visits.
Anas does not know the value of $K$. Therefore, for each value of $K$ between $0$ and $N \cdot M - 1$ inclusive, he wants to calculate the number of cells that will be destroyed by at least one hero. Can you help him?

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

-----Output-----
For each test case, print a single line containing $N \cdot M$ space-separated integers as described above.

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

-----Subtasks-----
Subtask #1 (30 points):
- $2 \le N, M \le 50$
- the sum of $N \cdot M$ over all test cases does not exceed $5,000$
Subtask #2 (70 points): original constraints

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

-----Example Output-----
6 4 3 3...

for x in range(int(input())):
 n,m=map(int,input().split())
 y=n*m
 for x in range(n*m):
  a=1
  b=1
  d={(1,1):1}
  count=1
  if x==0:
   print(n*m,end=" ")
   continue
  while(True):
   b=b+x+1
   if(b>m):
    u=b-m
    if(u%m==0):
     a=a+u//m
     b=m
    else:
     a=a+(u//m)+1
     b=u%m
   if a>n:
    break
   else:
    d[(a,b)]=1
    count+=1
  a=1
  b=1
  while(True):
   a=a+x+1
   if(a>n):
    u=a-n
    if(u%n==0):
     b=b+u//n
     a=n
    else:
     b=b+(u//n)+1
     a=u%n
   if b>m:
    break
   else:
    if (a,b) not in d.keys():
     count+=1
  print(count,end=" ")
 print("")


Solve in Python:
Andre has very specific tastes. Recently he started falling in love with arrays.

Andre calls an nonempty array $b$ good, if sum of its elements is divisible by the length of this array. For example, array $[2, 3, 1]$ is good, as sum of its elements — $6$ — is divisible by $3$, but array $[1, 1, 2, 3]$ isn't good, as $7$ isn't divisible by $4$.

Andre calls an array $a$ of length $n$ perfect if the following conditions hold:   Every nonempty subarray of this array is good.  For every $i$ ($1 \le i \le n$), $1 \leq a_i \leq 100$.

Given a positive integer $n$, output any perfect array of length $n$. We can show that for the given constraints such an array always exists.

An array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.

The first and only line of every test case contains a single integer $n$ ($1 \le n \le 100$).

-----Output-----

For every test, output any perfect array of length $n$ on a separate line.

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

Output
24
19 33
7 37 79 49

-----Note-----

Array $[19, 33]$ is perfect as all $3$ its subarrays: $[19]$, $[33]$, $[19, 33]$, have sums divisible by their lengths, and therefore are good.

"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""

import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time

from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

from collections import defaultdict as dd,...


Solve in Python:
Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "d_{i} → t_{i}", that means "replace all digits d_{i} in string s with substrings equal to t_{i}". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("replace 3 by an empty string") transforms it to s = 1212. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to s by 1000000007 (10^9 + 7). When you represent s as a decimal number, please ignore the leading zeroes; also if s is an empty string, then it's assumed that the number equals to zero.

Andrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!

-----Input-----

The first line contains string s (1 ≤ |s| ≤ 10^5), consisting of digits — the string before processing all the requests.

The second line contains a single integer n (0 ≤ n ≤ 10^5) — the number of queries.

The next n lines contain the descriptions of the queries. The i-th query is described by string "d_{i}->t_{i}", where d_{i} is exactly one digit (from 0 to 9), t_{i} is a string consisting of digits (t_{i} can be an empty string). The sum of lengths of t_{i} for all queries doesn't exceed 10^5. The queries are written in the order in which they need to be performed.

-----Output-----

Print a single integer — remainder of division of the resulting number by 1000000007 (10^9 + 7).

-----Examples-----
Input
123123
1
2->00

Output
10031003

Input
123123
1
3->

Output
1212

Input
222
2
2->0
0->7

Output
777

Input
1000000008
0

Output
1

-----Note-----

Note that the leading zeroes are not removed from string s after the replacement (you can see it in the third sample).

def main():
    s = input()
    n = int(input())

    M = 1000000007
    a = {str(s):[10, s] for s in range(10)}
    d = [['_', s]] + [input().split('->') for _ in range(n)]

    for di, ti in reversed(d):
        _p = 1
        _v = 0
        for c in ti:
            _v = (_v * a[c][0] + a[c][1]) % M
            _p = (_p * a[c][0]) % M
        a[di] = [_p, _v]

    print(a['_'][1])

def __starting_point():
    main()

__starting_point()


Solve in Python:
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.

Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.

Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.

-----Input-----

The first line contains two integers, n and k (1 ≤ n ≤ 10^5; 1 ≤ k ≤ 10^9).

Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 10^5. Each string of the group consists only of lowercase English letters.

-----Output-----

If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).

-----Examples-----
Input
2 3
a
b

Output
First

Input
3 1
a
b
c

Output
First

Input
1 2
ab

Output
Second

"""
Codeforces Contest 260 Div 1 Problem B

Author  : chaotic_iak
Language: Python 3.3.4
"""

def main():
    n,k = read()
    s = set()
    for i in range(n): s.add(read(0))
    s = list(s)
    s.sort()
    s = treeify(s)
    res = solve(s)
    if res == 0: # neither: second player win
        print("Second")
    if res == 1: # odd: first player win if k is odd
        print("First" if k % 2 else "Second")
    if res == 2: # even: second player win
        print("Second")
    if res == 3: # both: first player win
        print("First")

def treeify(s):
    res = [[] for _ in range(26)]
    for i in s:
        if i: res[ord(i[0]) - 97].append(i[1:])
    fin = []
    for i in range(26):
        if res[i]: fin.append(treeify(res[i]))
    return fin

def solve(s, parity=2):
    for i in range(len(s)):
        if isinstance(s[i], list): s[i] = solve(s[i], 3-parity)
    if not s: return parity # no possible move: current parity
    if 0 in s: return 3 # any neither: both
    if 1 in s and 2 in s: return 3 # any odd and any even: both
    if 1 in s: return 1 # any odd: odd
    if 2 in s: return 2 # any even: even
    return 0 # all both: neither

################################### NON-SOLUTION STUFF BELOW

def read(mode=2):
    # 0: String
    # 1: List of strings
    # 2: List of integers
    inputs = input().strip()
    if mode == 0: return inputs
    if mode == 1: return inputs.split()
    if mode == 2: return map(int, inputs.split())

def write(s="\n"):
    if isinstance(s, list): s = " ".join(map(str, s))
    s = str(s)
    print(s, end="")

main()


Solve in Python:
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.

The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [l_{i}, r_{i}], besides, r_{i} < l_{i} + 1 for 1 ≤ i ≤ n - 1.

To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that l_{i} ≤ x ≤ r_{i}, l_{i} + 1 ≤ y ≤ r_{i} + 1 and y - x = a.

The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.

-----Input-----

The first line contains integers n (2 ≤ n ≤ 2·10^5) and m (1 ≤ m ≤ 2·10^5) — the number of islands and bridges.

Next n lines each contain two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^18) — the coordinates of the island endpoints.

The last line contains m integer numbers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^18) — the lengths of the bridges that Andrewid got.

-----Output-----

If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b_1, b_2, ..., b_{n} - 1, which mean that between islands i and i + 1 there must be used a bridge number b_{i}.

If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.

-----Examples-----
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8

Output
Yes
2 3 1

Input
2 2
11 14
17 18
2 9

Output
No

Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999

Output
Yes
1

-----Note-----

In the first sample test you can,...

#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Input

The first line contains integers n and m - the number of islands and bridges.

Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.

The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output

If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.

If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""

# Standard libraries
import unittest
import sys
import re

# Additional libraries
import heapq

###############################################################################
# Fug Class
###############################################################################

class Fug:
    """ Fug representation """

    def __init__(self, args):
        """ Default constructor """
        self.list = args[0]
        self.alist = args[1]
        self.gn = len(self.list) - 1

        # Sorted list of bridges
        self.asrt = sorted((n, i) for i, n in enumerate(self.alist))

        # List of gaps between islands
       ...


Solve in Python:
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.

The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5.

In one second, you can perform one of the two following operations:  Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;  Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b.

According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

-----Input-----

The first line contains integers n (1 ≤ n ≤ 10^5) and k (1 ≤ k ≤ 10^5) — the number of matryoshkas and matryoshka chains in the initial configuration.

The next k lines contain the descriptions of the chains: the i-th line first contains number m_{i} (1 ≤ m_{i} ≤ n), and then m_{i} numbers a_{i}1, a_{i}2, ..., a_{im}_{i} — the numbers of matryoshkas in the chain (matryoshka a_{i}1 is nested into matryoshka a_{i}2, that is nested into matryoshka a_{i}3, and so on till the matryoshka a_{im}_{i} that isn't nested into any other matryoshka).

It is guaranteed that m_1 + m_2 + ... + m_{k} = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in...

def read_data():
    n, k = map(int, input().split())
    As = []
    m = 0
    for i in range(k):
        ma = list(map(int, input().split()))
        As.append(ma[1:])
        m += ma[0] - 1
    return n, k, As, m

def solve(n, k, As, m):
    As.sort()
    steps = n + 1 + m
    mat1 = As[0]
    for i, mi in enumerate(mat1, 1):
        if i == mi:
            steps -= 2
        else:
            break
    return steps

n, k, As, m = read_data()
print(solve(n, k, As, m))


Solve in Python:
Andrii is good in Math, but not in Programming. He is asking you to solve following problem: Given an integer number N and two sets of integer A and B. Let set A contain all numbers from 1 to N and set B contain all numbers from N + 1 to 2N. Multiset C contains all sums a + b such that a belongs to A and b belongs to B. Note that multiset may contain several elements with the same values. For example, if N equals to three, then A = {1, 2, 3}, B = {4, 5, 6} and C = {5, 6, 6, 7, 7, 7, 8, 8, 9}. Andrii has M queries about multiset C. Every query is defined by a single integer q. Andrii wants to know the number of times q is contained in C. For example, number 6 is contained two times, 1 is not contained in C at all.

Please, help Andrii to answer all the queries.

-----Input-----

The first line of the input contains two integers N and M. Each of the next M line contains one integer q, the query asked by Andrii.

-----Output-----
Output the answer for each query in separate lines as in example.

-----Constraints-----
- 1 ≤ N ≤ 109
- 1 ≤ M ≤ 105
- 1 ≤ q ≤ 3N

-----Example-----
Input:
3 5
6
2
9
7
5
Output:
2
0
1
3
1

# cook your dish here
n,m=map(int,input().split())
for i in range(m):
    x=int(input())
    if x<=n or x>3*n:
        print(0)
    elif x>n and x<=2*n:
        print(x-n-1)
    else:
        print(n-(x%(2*n))+1)


Solve in Python:
Andrzej was given a task:
There are n jars with pills. In every jar there is a different type of pill and the amount of pills in each jar is infinite. One type of pill makes a person glow about 30 minutes after taking and none of the other types has any effect.
His job is to determine, in which jar are the pills that make a person glow.
But there is one catch, he only has 35 minutes to do so.(so he can't take a pill, wait for the results and then take another one, because he wouldn't be able to see the results)
Fortunetely, he can take any number of friends he needs with him.
On completing the task Andrzej receives one million dollars. You know that Andrzej is very honest, so he will split the money equally with his friends.
Your job is to determine how many friends does Andrzej need to complete the task.(He also wants to make the highest amount of money.)
For example for n = 2
The answer is 0 because he doesn't need any friends, he just needs to take a pill from the first jar and wait for the effects.
For another example for n = 4
The answer is 1 because having pills A B C D Andrzej can take pills A B and the friend can take pills B C

import math
def friends(n):
    print(n)
    if n <= 2:
        return 0
    elif math.log(n,2)==int(math.log(n,2)):
        return int(math.log(n,2)) -1
    else:
        return int(math.log(n,2))


Solve in Python:
Anmol gained a lot of weight last semester. So this semester, he decided to run everyday. There is a very long straight road starting at his hostel. There are N poles on the road - P1, P2, P3,..., PN on the road. All the poles lie on the same side of his hostel. The distance between Pi and his hostel is Di.
For 1 ≤ i, j ≤ N, i < j implies Di < Dj
Everyday, Anmol chooses a pole Pi to start running from. He keeps on running until he reaches Pi+K. Whenever he reaches a pole (other than the starting pole), he records the distance traveled since the last pole.

You are given the distances recorded by him today. Your task is to find the number of distinct values of i such that i + K ≤ N and if he starts at Pi and end at Pi+K, he would end up having exactly the same record of distances (in the same order).

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases.
- The first line of each test case contains two space separated integers N and K.
- The next line contains N space separated integers D1, D2,..., DN.
- The next line contains K space separated integers representing the distances recorded by Anmol in the same order.
.

-----Output-----
- For each test case, output a single line containing the answer for that test case.

-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ N ≤ 5 x 104
- 1 ≤ K < N
- 1 ≤ Di ≤ 106

-----Subtasks-----

-----Subtask #1 (20 points)-----
- 1 ≤ N ≤ 1000

-----Subtask #2 (80 points)-----
- Original constraints

-----Example-----
Input:
3
5 1
1 5 10 12 14
5
5 2
5 8 13 16 21
3 5
5 3
2 6 8 11 16
2 3 5

Output:
1
2
1

-----Explanation-----
Example case 1. If he runs from P2 to P3, he will record (5)
Example case 2. He can start at P1 or P3
Example case 3. He can start at P2

for t in range(int(input())):
 n, k = list(map(int, input().split()))
 poles = list(map(int, input().split()))
 dist = list(map(int, input().split()))
 dist_btw_poles = []
 for i in range(1,n):
  dist_btw_poles.append(poles[i]-poles[i-1])
 if dist_btw_poles.count(dist_btw_poles[0])==n-1:
  print(n-k)
  continue
 c = 0
 for i in range(n-k):
  if (dist_btw_poles[i] == dist[0]):
   flag = 1
   for j in range(k):
    if (dist_btw_poles[i+j] != dist[j]):
     flag = 0
     break
   if (flag == 1):
    c += 1
 print(c)


Solve in Python:
Anna Hazare is a well known social activist in India.

On 5th April, 2011 he started "Lokpal Bill movement".

Chef is very excited about this movement. He is thinking of contributing to it. He gathers his cook-herd and starts thinking about how our community can contribute to this.

All of them are excited about this too, but no one could come up with any idea. Cooks were slightly disappointed with this and went to consult their friends.

One of the geekiest friend gave them the idea of spreading knowledge through Facebook. But we do not want to spam people's wall. So our cook came up with the idea of dividing Facebook users into small friend groups and then identify the most popular friend in each group and post on his / her wall. They started dividing users into groups of friends and identifying the most popular amongst them.

The notoriety of a friend is defined as the averaged distance from all the other friends in his / her group. This measure considers the friend himself, and the trivial distance of '0' that he / she has with himself / herself.

The most popular friend in a group is the friend whose notoriety is least among all the friends in the group.

Distance between X and Y is defined as follows:

Minimum number of profiles that X needs to visit for reaching Y's profile(Including Y's profile). X can open only those profiles which are in the friend list of the current opened profile. For Example:

- Suppose A is friend of B.

- B has two friends C and D.

- E is a friend of D.

Now, the distance between A and B is 1, A and C is 2, C and E is 3.

So, one of our smart cooks took the responsibility of identifying the most popular friend in each group and others will go to persuade them for posting.  This cheeky fellow knows that he can release his burden by giving this task as a long contest problem.

Now, he is asking you to write a program to identify the most popular friend among all the friends in each group. Also, our smart cook wants to know the average distance of everyone from the most...

from collections import deque
from sys import stdin
import psyco
psyco.full()

graph = [[]]
WHITE, GRAY, BLACK = 0, 1, 2

def notoriety(x, f_count):
    queue = deque([x])
    d = [0 for i in range(f_count+1)]
    p = [0 for i in range(f_count+1)]
    color = [WHITE for i in range(f_count+1)]
    while len(queue) > 0:
        top = queue.pop()
        for node in graph[top]:
            if color[node] == WHITE:
                queue.appendleft(node)
                color[node], p[node], d[node] = GRAY, top, d[top] + 1
        color[top] = BLACK
    return sum(d)/(f_count*1.0)

def main():
    groups = int(stdin.readline())
    for g in range(groups):
        global graph
        graph = [[]]
        no_of_friends = int(stdin.readline())
        for i in range(no_of_friends):
            graph.append(list(map(int,stdin.readline().split())))
        min_notoriety, popular = 10000000, -1 # yet another magic number
        for f in range(1,no_of_friends+1):
            curr_not = notoriety(f, no_of_friends)
            if  curr_not < min_notoriety:
                min_notoriety,popular = curr_not, f
        assert popular != -1
        print(popular, "%.6f" %min_notoriety)

def __starting_point():
    main()

__starting_point()


Solve in Python:
Another Fibonacci... yes but with other kinds of result.
The function is named `aroundFib` or `around_fib`, depending of the language.
Its parameter is `n` (positive integer).

First you have to calculate `f` the value of `fibonacci(n)` with `fibonacci(0) --> 0` and
`fibonacci(1) --> 1` (see: )

- 1) Find the count of each digit `ch` in `f` (`ch`: digit from 0 to 9), call this count `cnt` and find the maximum
value of `cnt`, call this maximum `maxcnt`. If there are ties, the digit `ch` to consider is the first one - in natural digit order - giving `maxcnt`.

- 2) Cut the value `f` into chunks of length at most `25`. The last chunk may be 25 long or less.

```
Example: for `n=100` you have only one chunk `354224848179261915075`
Example: for `n=180` f is `18547707689471986212190138521399707760` and you have two chunks
`1854770768947198621219013` and `8521399707760`. First length here is 25 and second one is 13.
```

- At last return a string in the following format:
"Last chunk ...; Max is ... for digit ..."

where Max is `maxcnt` and digit the first `ch` (in 0..9) leading to `maxcnt`.

```
Example: for `n=100` -> "Last chunk 354224848179261915075; Max is 3 for digit 1"
Example: for `n=180` -> "Last chunk 8521399707760; Max is 7 for digit 7"
Example: for `n=18000` -> "Last chunk 140258776000; Max is 409 for digit 1"
```
# Beware:
`fib(18000)` has `3762` digits. Values of `n` are between `500` and `25000`.

# Note
Translators are welcome for all languages, except for Ruby since the Bash tests needing Ruby a Ruby reference solution is already there though not yet published.

def around_fib(n):
    f = str(fib(n))
    ch = ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']
    maxcnt = 0
    chunk = ''

    for digit in ch:
        cnt = f.count(digit)
        if cnt >= maxcnt:
            maxcnt = cnt
            maxdig = digit

    l = len(f) % 25
    if l == 0:
        start = len(f) - 25
    else:
        start = len(f) - l
    for i in range(start, len(f)):
        chunk += f[i]

    return 'Last chunk ' + chunk + '; Max is %d for digit ' % maxcnt + maxdig

def fib(n):
    a = 0
    b = 1
    if n == 0:
        return a
    elif n == 1:
        return b
    else:
        for i in range(2,n+1):
            c = a + b
            a = b
            b = c
        return b


Solve in Python:
Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will generate the HTML for you.

To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element.

For example,

In JavaScript:

In Python:
```python
g = HTMLGen();
paragraph = g.p('Hello, World!')
block = g.div(paragraph)

# The following are now true
paragraph == 'Hello, World!'
block == 'Hello, World!'
```

Your HTMLGen class should have methods to create the following elements:

  * a
  * b
  * p
  * body
  * div
  * span
  * title
  * comment

Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ``````.

class HTMLGen:
    def __init__(self):
        tags = ['a', 'b', 'p', 'body', 'div', 'span', 'title', 'comment']
        for tag in tags:
            setattr(self, tag, lambda content, tag=tag: '<'+tag+'>'+content+'</'+tag+'>' if not tag == 'comment' else '<!--'+content+'-->')


Solve in Python:
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]

Constraints:

10 <= low <= high <= 10^9

class Solution:
    def sequentialDigits(self, low: int, high: int) -> List[int]:
        nl, nh = len(str(low)), len(str(high))
        ans = []
        sequential = '123456789'
        for n in range(nl, min(nh+1,10)):
            start, delta = int(sequential[:n]), int('1'*n)
            k_min = 0 if n > nl else max(-(-(low-start) // delta), 0)
            k_max = 9 - n if n < nh else (min(high, int(sequential[-n:]))-start) // delta
            ans += [start + k*delta for k in range(k_min, k_max + 1)]

        return ans


Solve in Python:
Apparently "Put A Pillow On Your Fridge Day is celebrated on the 29th of May each year, in Europe and the U.S. The day is all about prosperity, good fortune, and having bit of fun along the way."

All seems very weird to me.

Nevertheless, you will be given an array of two strings (s). First find out if the first string contains a fridge... (i've deemed this as being 'n', as it looks like it could hold something).

Then check that the second string has a pillow - deemed 'B' (struggled to get the obvious pillow-esque character).

If the pillow is on top of the fridge - it must be May 29th! Or a weird house... Return true; For clarity, on top means right on top, ie in the same index position.

If the pillow is anywhere else in the 'house', return false;

There may be multiple fridges, and multiple pillows. But you need at least 1 pillow ON TOP of a fridge to return true. Multiple pillows on fridges should return true also.

100 random tests


Solve in Python:
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.

Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices.

Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains an integer n (2  ≤ n ≤ 10^5) — the number of tree vertices.

The second line contains the description of the tree: n - 1 integers p_0, p_1, ..., p_{n} - 2 (0 ≤ p_{i} ≤ i). Where p_{i} means that there is an edge connecting vertex (i + 1) of the tree and vertex p_{i}. Consider tree vertices are numbered from 0 to n - 1.

The third line contains the description of the colors of the vertices: n integers x_0, x_1, ..., x_{n} - 1 (x_{i} is either 0 or 1). If x_{i} is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.

-----Output-----

Output a single integer — the number of ways to split the tree modulo 1000000007 (10^9 + 7).

-----Examples-----
Input
3
0 0
0 1 1

Output
2

Input
6
0 1 1 0 4
1 1 0 0 1 0

Output
1

Input
10
0 1 2 1 4 4 4 0 8
0 0 0 1 0 1 1 0 0 1

Output
27

from collections import UserDict

class Tree(UserDict):
    def __init__(self, g):
        super().__init__()
        for name, value in enumerate(g, 1):
            self[value] = name

    def __setitem__(self, name, value):
        if name in self:
            if value is not None:
                self[name].add(value)
                self[value] = None
        else:
            if value is None:
                super().__setitem__(name, set())
            else:
                super().__setitem__(name, {value})
                self[value] = None

def __starting_point():
    n = int(input())

    tree = Tree(int(i) for i in input().split())
    colors = [int(i) for i in input().split()]
    t = [()] * n

    def dfs(v):
        stack = [v]
        visited = set()

        while stack:
            v = stack.pop()
            if v not in visited:
                visited.add(v)
                stack.append(v)
                stack.extend(tree[v])
            else:
                t[v] = (1, colors[v])
                for u in tree[v]:
                    t[v] = (
                        (t[v][0] * t[u][1] + t[v][0] * t[u][0] * (not colors[u])) % (10**9 + 7),
                        (t[v][1] * t[u][1] + t[v][0] * t[u][1] * (not colors[v])
                                           + t[v][1] * t[u][0] * (not colors[u])) % (10**9 + 7)
                    )

    dfs(0)

    print(t[0][1])

# Made By Mostafa_Khaled

__starting_point()


Solve in Python:
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:  Fold the sheet of paper at position p_{i}. After this query the leftmost part of the paper with dimensions 1 × p_{i} must be above the rightmost part of the paper with dimensions 1 × ([current width of sheet] - p_{i}).  Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance l_{i} from the left border of the current sheet of paper and the other at distance r_{i} from the left border of the current sheet of paper.

Please look at the explanation of the first test example for better understanding of the problem.

-----Input-----

The first line contains two integers: n and q (1  ≤ n ≤ 10^5; 1 ≤ q ≤ 10^5) — the width of the paper and the number of queries.

Each of the following q lines contains one of the described queries in the following format:  "1 p_{i}" (1 ≤ p_{i} < [current width of sheet]) — the first type query.  "2 l_{i} r_{i}" (0 ≤ l_{i} < r_{i} ≤ [current width of sheet]) — the second type query.

-----Output-----

For each query of the second type, output the answer.

-----Examples-----
Input
7 4
1 3
1 2
2 0 1
2 1 2

Output
4
3

Input
10 9
2 2 9
1 1
2 0 1
1 8
2 0 8
1 2
2 1 3
1 4
2 2 4

Output
7
2
10
4
5

-----Note-----

The pictures below show the shapes of the paper during the queries of the first example: [Image]

After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.

from itertools import starmap

def main():
    n, q = list(map(int, input().split()))

    a = list(range(n + 1))
    flipped = False
    start = 0
    end = n

    for _ in range(q):
        cmd, *args = list(map(int, input().split()))

        if cmd == 1:
            p = args[0]
            if p > end-start-p:
                flipped = not flipped
                p = end-start-p
            if flipped:
                a[end-p:end-2*p:-1] = starmap(
                    lambda a, b: a+n-b,
                    list(zip(a[end-p:end-2*p:-1], a[end-p:end]))
                )
                end -= p
            else:
                start += p
                a[start:start+p] = starmap(
                    lambda a, b: a-b,
                    list(zip(a[start:start+p], a[start:start-p:-1]))
                )
        else:
            l, r = args
            if flipped:
                l, r = end-start-r, end-start-l
            print(a[start + r] - a[start + l])

def __starting_point():
    main()

__starting_point()


Solve in Python:
Appy and Chef are participating in a contest. There are $N$ problems in this contest; each problem has a unique problem code between $1$ and $N$ inclusive. Appy and Chef decided to split the problems to solve between them ― Appy should solve the problems whose problem codes are divisible by $A$ but not divisible by $B$, and Chef should solve the problems whose problem codes are divisible by $B$ but not divisible by $A$ (they decided to not solve the problems whose codes are divisible by both $A$ and $B$).
To win, it is necessary to solve at least $K$ problems. You have to tell Appy whether they are going to win or lose.

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

-----Output-----
For each test case, print a single line containing the string "Win" if they can solve at least $K$ problems or "Lose" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 15$
- $1 \le K \le N \le 10^{18}$
- $1 \le A, B \le 10^9$

-----Subtasks-----
Subtask #1 (15 points):
- $1 \le T \le 15$
- $1 \le K \le N \le 10^6$
- $1 \le A, B \le 10^3$
Subtask #2 (85 points): original constraints

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

-----Example Output-----
Win

-----Explanation-----
Example case 1: Appy is solving the problems with codes $2$ and $4$, Chef is solving the problem with code $3$. Nobody is solving problem $6$, since $6$ is divisible by both $2$ and $3$. Therefore, they can solve $3$ problems and win.

from math import gcd as g
t=int(input())
while t!=0:
 n,a,b,k=map(int,input().split())
 lcm=(a*b)//g(a,b)
 div_a=(n//a)-(n//lcm)
 div_b=(n//b)-(n//lcm)
 net=div_a+div_b
 if net>=k:
  print('Win')
 else:
  print('Lose')
 t-=1


Solve in Python:
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.

Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.

Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.

-----Input-----

The first line contains two integers n and k (3 ≤ n ≤ 2·10^5, 2 ≤ k ≤ n - 1) — the total number of nodes and the number of exit-nodes.

Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.

-----Output-----

In the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.

If there are multiple answers, print any of them.

-----Examples-----
Input
3 2

Output
2
1 2
2 3

Input
5 3

Output
3
1 2
2 3
3 4
3 5

-----Note-----

In the first example the only network is shown on the left picture.

In the second example one of optimal networks is shown on the right picture.

Exit-nodes are highlighted. [Image]

n = list(map(int,input().split(' ')))
a,b = n[0],n[1]
if b >= a-b-1:
    if a-b == 1:
        print(2)
        for i in range(2,a+1):
            print(1,i)
    elif a-b == 2:
        print(3)
        print(1,2)
        print(2,3)
        for i in range(4,a+1):
            print(3,i)
    else:
        print(4)
        for i in range(2,a-b+1):
            print(1,i)
            print(i,i+a-b-1)
        for i in range(2*(a-b),a+1):
            print(a-b,i)
else:
    s = (a-1)//b
    if (a-1)%b == 0:
        print(2*s)
    elif (a-1)%b == 1:
        print(2*s+1)
    else:
        print(2*s+2)
    for i in range(1,b+1):
        print(a,i)
        j = i
        while j+b < a:
            print(j,j+b)
            j = j+b


Solve in Python:
Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.

Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.

-----Input-----

The first line contains three integers n, c and d (2 ≤ n ≤ 100 000, 0 ≤ c, d ≤ 100 000) — the number of fountains, the number of coins and diamonds Arkady has.

The next n lines describe fountains. Each of these lines contain two integers b_{i} and p_{i} (1 ≤ b_{i}, p_{i} ≤ 100 000) — the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively.

-----Output-----

Print the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0.

-----Examples-----
Input
3 7 6
10 8 C
4 3 C
5 6 D

Output
9

Input
2 4 5
2 5 C
2 1 D

Output
0

Input
3 10 10
5 5 C
5 5 C
10 11 D

Output
10

-----Note-----

In the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9.

In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins.

from operator import itemgetter

def get_one_max(arr, resource):
    res = 0
    for beauty, _ in [x for x in arr if x[1] <= resource]:
        res = max(res, beauty)
    return res

def get_two_max(arr, resource):
    arr.sort(key=itemgetter(1))
    best = [-1] * (resource + 1)
    ptr = 0
    for index, (beauty, price) in enumerate(arr):
        if price > resource:
            break
        while ptr < price:
            ptr += 1
            best[ptr] = best[ptr - 1]
        if best[ptr] == -1 or arr[best[ptr]][0] < beauty:
            best[ptr] = index

    while ptr < resource:
        ptr += 1
        best[ptr] = best[ptr - 1]

    res = 0
    for index, (beauty, price) in enumerate(arr):
        rest = resource - price
        if rest <= 0:
            break
        if best[rest] == -1 or best[rest] == index:
            continue
        res = max(res, beauty + arr[best[rest]][0])

    return res

n, coins, diamonds = list(map(int, input().split()))

with_coins = []
with_diamonds = []

for i in range(n):
    beauty, price, tp = input().split()
    if tp == 'C':
        with_coins.append((int(beauty), int(price)))
    else:
        with_diamonds.append((int(beauty), int(price)))

with_coins_max = get_one_max(with_coins, coins)
with_diamonds_max = get_one_max(with_diamonds, diamonds)
ans = 0 if with_coins_max == 0 or with_diamonds_max == 0 \
    else with_coins_max + with_diamonds_max
ans = max(ans, get_two_max(with_coins, coins))
ans = max(ans, get_two_max(with_diamonds, diamonds))

print(ans)


Solve in Python:
Array inversion indicates how far the array is from being sorted.

Inversions are pairs of elements in array that are out of order.

## Examples

```
[1, 2, 3, 4]  =>  0 inversions
[1, 3, 2, 4]  =>  1 inversion: 2 and 3
[4, 1, 2, 3]  =>  3 inversions: 4 and 1, 4 and 2, 4 and 3
[4, 3, 2, 1]  =>  6 inversions: 4 and 3, 4 and 2, 4 and 1, 3 and 2, 3 and 1, 2 and 1
```

## Goal

The goal is to come up with a function that can calculate inversions for any arbitrary array

from itertools import islice

def count_inversions(array):
    return sum(
        sum(x > y for y in islice(array, i+1, None))
        for i, x in enumerate(array)
    )


Solve in Python:
Arthur owns a ski resort on a mountain. There are $n$ landing spots on the mountain numbered from $1$ to $n$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.

A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.

Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable.

Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.

Arthur doesn't want to close too many spots. He will be happy to find any way to close at most $\frac{4}{7}n$ spots so that the remaining part is safe. Help him find any suitable way to do so.

-----Input-----

The first line contains a single positive integer $T$ — the number of test cases. $T$ test case description follows.

The first line of each description contains two integers $n$ and $m$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of landing spots and tracks respectively.

The following $m$ lines describe the tracks. Each of these lines contains two integers $x$ and $y$ ($1 \leq x < y \leq n$) — indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2...

import sys
inputr = lambda: sys.stdin.readline().rstrip('\n')
input = sys.stdin.readline

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

	adj = [[] for _ in range(n)]

	for _ in range(m):
		a, b = list(map(int, input().split()))
		a -= 1
		b -= 1
		adj[a].append(b)

	LP = [0] * n

	for i in range(n):
		if LP[i] < 2:
			for j in adj[i]:
				LP[j] = max(LP[j], LP[i] + 1)

	r = [i+1 for i in range(n) if LP[i] >= 2]

	print(len(r))
	print(' '.join(map(str, r)))

	assert 7 * len(r) <= 4 * n


Solve in Python:
Arya and Aryan live in a country called Nadaca. Nadaca consists of $N$ cities numbered $1$ through $N$, which are connected by some bidirectional roads. Each road has a positive (not necessarily integer) length. Arya lives in city $1$ and Aryan lives in city $N$.
Arya claims that for each city $v$, the shortest path from city $1$ to city $v$ has length $a_v$. Aryan does not disagree, but claims that for each city $v$, the shortest path from city $N$ to city $v$ has length $b_v$. You are the wisest person they know, so they asked you to tell them if it is possible for their claims to be true, i.e. if a road network which fully satisfies their claims exists. Help them!

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

-----Output-----
For each test case, print a single line containing the string "Yes" if Arya's and Aryan's claims can be true or "No" otherwise.

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

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

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

-----Example Output-----
Yes
No

t = int(input())

for m in range(t):

 n = int(input())
 l1 = list(map(int,input().split()))
 l2 = list(map(int,input().split()))
 flag = 0
 if l1[0]!=0 or l1[-1] == 0 or l2[0] == 0 or l2[-1]!=0 or l1[-1]!=l2[0]:
  flag = 1

 if flag!=1:
  for i in range(1,n-1):
   if l1[i]+l2[i]<l1[-1]:
    flag = 1
    break
   if l1[-1]+l2[i]<l1[i]:
    flag = 1
    break
   if l1[-1]+l1[i]<l2[i]:
    flag = 1
    break
 if flag == 0:
  print('Yes')
 else:
  print('No')


Solve in Python:
As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him.  [Image]

Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem.

A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally:  Empty string is a correct bracket sequence.  if s is a correct bracket sequence, then (s) is also a correct bracket sequence.  if s and t are correct bracket sequences, then st (concatenation of s and t) is also a correct bracket sequence.

A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence.

Will gave his mom a string s consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (l, r) such that 1 ≤ l ≤ r ≤ |s| and the string s_{l}s_{l} + 1... s_{r} is pretty, where s_{i} is i-th character of s.

Joyce doesn't know anything about bracket sequences, so she asked for your help.

-----Input-----

The first and only line of input contains string s, consisting only of characters '(', ')' and '?' (2 ≤ |s| ≤ 5000).

-----Output-----

Print the answer to Will's puzzle in the first and only line of output.

-----Examples-----
Input
((?))

Output
4

Input
??()??

Output
7

-----Note-----

For the first sample testcase, the pretty substrings of s are:  "(?" which can be transformed to "()".  "?)" which can be transformed to "()".  "((?)" which can be transformed to "(())".  "(?))" which can be transformed to "(())".

For the second sample testcase, the pretty substrings of s are:  "??" which...

def main():
    s = input()
    l = len(s)

    pretty_count = 0
    for i in range(l):
        left_paren_count = 0
        right_paren_count = 0
        wild_count = 0
        for j in range(i, l):
            if s[j] == '(':
                left_paren_count += 1
            elif s[j] == ')':
                right_paren_count += 1
            else:
                wild_count += 1

            if left_paren_count + wild_count < right_paren_count:
                break
            if left_paren_count < wild_count + right_paren_count:
                # Should fix one '?' as '('
                wild_count -= 1
                left_paren_count += 1
                if wild_count < 0:
                    break
            if left_paren_count == wild_count + right_paren_count:
                pretty_count += 1
    print(pretty_count)

def __starting_point():
    main()

__starting_point()


Solve in Python:
As [breadcrumb menùs](https://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29) are quite popular today, I won't digress much on explaining them, leaving the wiki link to do all the dirty work in my place.

What might not be so trivial is instead to get a decent breadcrumb from your current url. For this kata, your purpose is to create a function that takes a url, strips the first part (labelling it always `HOME`) and then builds it making each element but the last a `` element linking to the relevant path; last has to be a `` element getting the `active` `class`.

All elements need to be turned to uppercase and separated by a separator, given as the second parameter of the function; the last element can terminate in some common extension like `.html`, `.htm`, `.php` or `.asp`; if the name of the last element is `index`.something, you treat it as if it wasn't there, sending users automatically to the upper level folder.

A few examples can be more helpful than thousands of words of explanation, so here you have them:
```python
generate_bc("mysite.com/pictures/holidays.html", " : ") == 'HOME : PICTURES : HOLIDAYS'
generate_bc("www.codewars.com/users/GiacomoSorbi", " / ") == 'HOME / USERS / GIACOMOSORBI'
generate_bc("www.microsoft.com/docs/index.htm", " * ") == 'HOME * DOCS'
```
Seems easy enough?

Well, probably not so much, but we have one last extra rule: if one element (other than the root/home) is longer than 30 characters, you have to shorten it, acronymizing it (i.e.: taking just the initials of every word); url will be always given in the format `this-is-an-element-of-the-url` and you should ignore words in this array while acronymizing: `["the","of","in","from","by","with","and", "or", "for", "to", "at", "a"]`; a url composed of more words separated by `-` and equal or less than 30 characters long needs to be just uppercased with hyphens replaced by spaces.

Ignore anchors (`www.url.com#lameAnchorExample`) and parameters (`www.url.com?codewars=rocks&pippi=rocksToo`) when...

import re

def generate_bc(url, separator):
    def formater(name):
        if len(name) > 30:
            stoplist = ['the','of','in','from','by','with','and','or','for','to','at','a']
            return ''.join([ch[0].upper() for ch in name.split('-') if ch not in stoplist])
        else:
            return name.replace('-', ' ').upper()

    result = []

    url = re.sub(r'^https?:\/\/', '', url)      # remove protocol
    url = re.sub(r'\.[^\/]*$', '', url)         # remove extensions
    url = re.sub(r'(?:\#|\?).*$', '', url)      # remove anchors and queries
    url = re.sub(r'index$', '', url)            # remove indexes
    url = url.rstrip('/')                       # remove trailing slash

    crumbs = url.split('/')

    for i, crumb in enumerate(crumbs):
        if i == 0: result.append('HOME' if len(crumbs) > 1 else 'HOME')
        elif i == len(crumbs) - 1: result.append('{}'.format(formater(crumb)))
        else: result.append('{}'.format('/'.join(crumbs[1:1+i]), formater(crumb)))

    return separator.join(result)


Solve in Python:
As a member of the editorial board of the prestigous scientific Journal _Proceedings of the National Academy of Sciences_, you've decided to go back and review how well old articles you've published stand up to modern publication best practices. Specifically, you'd like to re-evaluate old findings in light of recent literature about ["researcher degrees of freedom"](http://journals.sagepub.com/doi/full/10.1177/0956797611417632).

You want to categorize all the old articles into three groups: "Fine", "Needs review" and "Pants on fire".

In order to categorize them you've enlisted an army of unpaid grad students to review and give you two data points from each study: (1) the p-value behind the paper's primary conclusions, and (2) the number of recommended author requirements to limit researcher degrees of freedom the authors satisfied:

    * Authors must decide the rule for terminating data collection before data collection begins and report this rule in the article.
    * Authors must collect at least 20 observations per cell or else provide a compelling cost-of-data-collection justification.
    * Authors must list all variables collected in a study.
    * Authors must report all experimental conditions, including failed manipulations.
    * If observations are eliminated, authors must also report what the statistical results are if those observations are included.
    * If an analysis includes a covariate, authors must report the statistical results of the analysis without the covariate.

Your army of tenure-hungry grad students will give you the p-value as a float between `1.0` and `0.0` exclusive, and the number of author requirements satisfied as an integer from `0` through `6` inclusive.

You've decided to write a function, `categorize_study()` to automatically categorize each study based on these two inputs using the completely scientifically legitimate "bs-factor". The bs-factor for a particular paper is calculated as follows:

 * bs-factor when the authors satisfy all six requirements is 1
 *...

def categorize_study(p, r):
    cat = p * 2 ** (6 - r)
    return 'Fine' if (cat < 0.05 and r) else 'Needs review' if cat < 0.15 else 'Pants on fire'


Solve in Python:
As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.

The input to the function will be an array of three distinct numbers (Haskell: a tuple).

For example:

    gimme([2, 3, 1]) => 0

*2* is the number that fits between *1* and *3* and the index of *2* in the input array is *0*.

Another example (just to make sure it is clear):

    gimme([5, 10, 14]) => 1

*10* is the number that fits between *5* and *14* and the index of *10* in the input array is *1*.

def gimme(input_array):
    maxpos = input_array.index(max(input_array))
    minpos = input_array.index(min(input_array))
    for i in input_array:
        if input_array.index(i) != maxpos and input_array.index(i) != minpos:
            return input_array.index(i)


Solve in Python:
As a strict big brother, I do limit my young brother Vasya on time he spends on computer games. I define a prime-time as a time period till which Vasya have a permission to play computer games. I specify start hour and end hour as pair of integers.

I need a function which will take three numbers - a present moment (current hour), a start hour of allowed time period and an end hour of allowed time period. The function should give answer to a question (as a boolean): "Can Vasya play in specified time?"

If I say that prime-time is from 12 till 15 that means that at 12:00 it's OK to play computer but at 15:00 there should be no more games.

I will allow Vasya to play at least one hour a day.

def can_i_play(now_hour, start_hour, end_hour):

    if start_hour<end_hour:

        return start_hour<=now_hour<end_hour

    else:

        return start_hour<=now_hour or now_hour<end_hour


Solve in Python:
As a treat, I'll let you read part of the script from a classic 'I'm Alan Partridge episode:
```
Lynn: Alan, there’s that teacher chap.
Alan: Michael, if he hits me, will you hit him first?
Michael: No, he’s a customer. I cannot hit customers. I’ve been told. I’ll go and get some stock.
Alan: Yeah, chicken stock.
Phil: Hello Alan.
Alan: Lynn, hand me an apple pie. And remove yourself from the theatre of conflict.
Lynn: What do you mean?
Alan: Go and stand by the yakults. The temperature inside this apple turnover is 1,000 degrees. If I squeeze it, a jet of molten Bramley apple is going to squirt out. Could go your way, could go mine. Either way, one of us is going down.
```

Alan is known for referring to the temperature of the apple turnover as 'Hotter than the sun!'. According to  space.com the temperature of the sun's corona is 2,000,000 degrees C, but we will ignore the science for now.

Your job is simple, if (x) squared is more than 1000, return  'It's hotter than the sun!!', else, return 'Help yourself to a honeycomb Yorkie for the glovebox.'.

X will be either a number or a string. Both are valid.

Other katas in this series:
Alan Partridge I - Partridge Watch
Alan Partridge III - London

def apple(x):
    if type(x) is str:
        x = int(x)
    return "It's hotter than the sun!!" if x * x > 1000 else "Help yourself to a honeycomb Yorkie for the glovebox."


Solve in Python:
As lockdown is going on so no is allowed to go outside , so Chef has come with an innovative idea for food home delivery using drone.  But there is an issue with it , the drone can move forward or backward a fix number of steps $x$ .
All the houses and chef restaurant are all in a straight line . Homes which need delivery are located at $H[i]$ and chef is located at $y$ coordinate .
If Drone is at a location $R$, then it can move to $R-x$ or $R+x$ .
Help chef find maximum value of $x$ to complete all the deliveries as he is busy managing the orders.

-----Input:-----
- First line will contain $n$ and $R$, number of houses that need delivery and the correct coordinate of chef (Drone).
- Second line contains $n$ integers , the coordinate of all homes that need delivery.

-----Output:-----
- The maximum value of $x$ , so that drone delivers to all houses.

-----Constraints-----
- $1 \leq n \leq 1000$
- $1 \leq R \leq 10^9$
- $1 \leq hi \leq 10^9$
- $1 \leq x  \leq 10^9$

-----Sample Input:-----
3 1
3 5 11

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

-----EXPLANATION:-----
Chef's drone is at 1 initially and he needs to visit 3,5,11 , so optimal solution will be (maximum value of x ) equal to 2.

# cook your di
import math
n,r=map(int,input().split())
l=list(map(int,input().split()))
ans=0
for i in range(len(l)):
    ans=math.gcd(ans,abs(l[i]-r))
print(ans)


Solve in Python:
As most of you might know already, a prime number is an integer `n` with the following properties:

* it must be greater than 1
* it must be divisible only by itself and 1

And that's it: -15 or 8 are not primes, 5 or 97 are; pretty easy, isn't it?

Well, turns out that primes are not just a mere mathematical curiosity and are very important, for example, to allow a lot of cryptographic algorithms.

Being able to tell if a number is a prime or not is thus not such a trivial matter and doing it with some efficient algo is thus crucial.

There are already more or less efficient (or sloppy) katas asking you to find primes, but here I try to be even more zealous than other authors.

You will be given a preset array/list with the first few `primes`. And you must write a function that checks if a given number `n` is a prime looping through it and, possibly, expanding the array/list of known primes only if/when necessary (ie: as soon as you check for a **potential prime which is greater than a given threshold for each** `n`, stop).

#  Memoization

Storing precomputed results for later re-use is a very popular programming technique that you would better master soon and that is called [memoization](https://en.wikipedia.org/wiki/Memoization); while you have your wiki open, you might also wish to get some info about the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) (one of the few good things I learnt as extra-curricular activity in middle grade) and, to be even more efficient, you might wish to consider [an interesting reading on searching from prime from a friend of mine](https://medium.com/@lcthornhill/why-does-the-6-iteration-method-work-for-testing-prime-numbers-ba6176f58082#.dppj0il3a) [she thought about an explanation all on her own after an evening event in which I discussed primality tests with my guys].

Yes, you will be checked even on that part. And you better be **very** efficient in your code if you hope to pass all the tests ;)

**Dedicated to my trainees that worked hard...

primes = [2, 3, 5, 7]

def is_prime(n):
    if n < 2:
        return False
    m = int(n ** .5) + 1
    for p in primes:
        if p >= m: break
        if not n % p:
            return False
    q, d = primes[-1], 4 if (n + 1) % 6 else 2
    while q < m:
        q, d = q + d, 4 - d
        if is_prime(q):
            primes.append(q)
            if not n % q:
                return False
    return True


Solve in Python:
As part of this Kata, you need to find the length of the sequence in an array, between the first and the second occurrence of a specified number.

For example, for a given array `arr`

    [0, -3, 7, 4, 0, 3, 7, 9]

Finding length between two `7`s like

    lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7)

would return `5`.

For sake of simplicity, there will only be numbers (positive or negative) in the supplied array.

If there are less or more than two occurrences of the number to search for, return `0`, or in Haskell, `Nothing`.

def length_of_sequence(arr, n):
    if arr.count(n) != 2:
        return 0
    a = arr.index(n)
    b = arr.index(n, a + 1)
    return b - a + 1


Solve in Python:
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.

Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.

-----Input-----

The first line contains two lowercase English letters — the password on the phone.

The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows.

The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct.

-----Output-----

Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise.

You can print each letter in arbitrary case (upper or lower).

-----Examples-----
Input
ya
4
ah
oy
to
ha

Output
YES

Input
hp
2
ht
tp

Output
NO

Input
ah
1
ha

Output
YES

-----Note-----

In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES".

In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring.

In the third example the string "hahahaha" contains "ah" as a substring.

s=input()
n=int(input())
l=[]
for u in range(n):
	l.append(input())

flag=0
for i in range(n):
	for j in range(n):
		if((l[i]+l[j]).count(s) >=1):
			flag=1
			break
	if(flag):
		break
if(flag):
	print("YES")
else:
	print("NO")


Solve in Python:
As the title suggests, this is the hard-core version of  another neat kata.

The task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly included), going in steps expressed by the third parameter:

```python
sequence_sum(2, 2, 2) # 2
sequence_sum(2, 6, 2) # 12 (= 2 + 4 + 6)
sequence_sum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5)
sequence_sum(1, 5, 3) # 5 (= 1 + 4)
```

If it is an impossible sequence (with the beginning being larger the end and a positive step or the other way around), just return `0`. See the provided test cases for further examples :)

**Note:** differing from the other base kata, much larger ranges are going to be tested, so you should hope to get your algo optimized and to avoid brute-forcing your way through the solution.

def sequence_sum(start, stop, step):
    n = (stop - start) // step
    last = start + n * step
    return (n+1) * (start + last) // 2 if n >= 0 else 0


Solve in Python:
As we all know caterpillars love to eat leaves. Usually, a caterpillar sits on leaf, eats as much of it as it can (or wants), then stretches out to its full length to reach a new leaf with its front end, and finally "hops" to it by contracting its back end to that leaf.
We have with us a very long, straight branch of a tree with leaves distributed uniformly along its length, and a set of caterpillars sitting on the first leaf. (Well, our leaves are big enough to accommodate upto $20$ caterpillars!). As time progresses our caterpillars eat and hop repeatedly, thereby damaging many leaves. Not all caterpillars are of the same length, so different caterpillars may eat different sets of leaves. We would like to find out the number of leaves that will be undamaged at the end of this eating spree. We assume that adjacent leaves are a unit distance apart and the length of the caterpillars is also given in the same unit.
For example suppose our branch had $20$ leaves (placed $1$ unit apart) and $3$ caterpillars of length $3, 2$ and $5$ units respectively. Then, first caterpillar would first eat leaf $1$, then hop to leaf $4$ and eat it and then hop to leaf $7$ and eat it and so on. So the first caterpillar would end up eating the leaves at positions $1,4,7,10,13,16$ and $19$. The second caterpillar would eat the leaves at positions $1,3,5,7,9,11,13,15,17$ and $19$. The third caterpillar would eat the leaves at positions $1,6,11$ and $16$. Thus we would have undamaged leaves at positions $2,8,12,14,18$ and $20$. So the answer to this example is $6$.

-----Input:-----
The first line of the input contains two integers $N$ and $K$, where $N$ is the number of leaves and $K$ is the number of caterpillars. Lines $2,3,...,K+1$ describe the lengths of the $K$ caterpillars. Line $i+1$ ($1 \leq i \leq K$) contains a single integer representing the length of the $i^{th}$ caterpillar.

-----Output:-----
A line containing a single integer, which is the number of leaves left on the branch after all the caterpillars have finished...

from math import gcd
n, k = list(map(int, input().split()))
a = []
for i in range(k):
    try:
        a += list(map(int, input().split()))
    except:
        pass
ans = n
for i in range(1, 2**k):
    b = bin(i)[2:].rjust(k, "0")
    c = []
    for j in range(k):
        if(b[j] == '1'):
            c.append(a[j])
    lcm = c[0]
    for j in c[1:]:
        lcm *= j // gcd(lcm, j)
    temp = ((n - 1) // lcm) + 1
    if(b.count('1')&1):
        ans -= temp
    else:
        ans += temp
print(ans)


Solve in Python:
As we all know, Chef is cooking string for long days, his new discovery on string is the longest common pattern length. The longest common pattern length between two strings is the maximum number of characters that both strings have in common. Characters are case sensitive, that is, lower case and upper case characters are considered as different. Note that characters can repeat in a string and a character might have one or more occurrence in common between two strings. For example, if Chef has two strings A = "Codechef" and B = "elfedcc", then the longest common pattern length of A and B is 5 (common characters are c, d, e, e, f).
Chef wants to test you with the problem described above. He will give you two strings of Latin alphabets and digits, return him the longest common pattern length.

-----Input-----
The first line of the input contains an integer T, denoting the number of test cases. Then the description of T test cases follows.
The first line of each test case contains a string A. The next line contains another character string B.

-----Output-----
For each test case, output a single line containing a single integer, the longest common pattern length between A and B.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ |A|, |B| ≤ 10000 (104), where |S| denotes the length of the string S
- Both of A and B can contain only alphabet characters (both lower and upper case) and digits

-----Example-----
Input:
4
abcd
xyz
abcd
bcda
aabc
acaa
Codechef
elfedcc

Output:
0
4
3
5

-----Explanation-----
Example case 1. There is no common character.
Example case 2. All the characters are same.
Example case 3. Three characters (a, a and c) are same.
Example case 4. This sample is mentioned by the statement.

def soln():
	a=input()
	b=input()
	a1=set(a)
	c=0
	for i in a1:
		if i in b:
			c+=min(a.count(i),b.count(i))

	print(c)

def main():
	t=int(input())
	while t>0:
		t=t-1
		soln()

def __starting_point():
	main()

__starting_point()


Solve in Python:
As we all know, Dhoni loves drinking milk. Once he and Sir Jadeja were invited in the inauguration of a Dairy company in Ranchi.

The company had arranged  n   jars of milk from various breeds of cows , jar number  i  containing  a[i]  litres of milk. Since Dhoni loves driking milk more than Sir Jadeja, so Kohli suggested a plan for them. His plan was that each time Dhoni will choose a jar containing the maximum amount of milk. If this jar has less than  k   litres of milk or if Dhoni has already drunk more than  m  number of times from this jar, then the milk contained in the jar will be drunk by Sir Jadeja. Sir Jadeja will drink all the milk left in that jar. Otherwise Dhoni will drink exactly k  litres of milk from the jar and put it back at its position. Dhoni will do so until he has given all jars to Sir Jadeja.

You have to calculate how much milk Sir Jadega will get after Dhoni satisfies his hunger modulo 1,000,000,007.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
-  The first line of each test case contains integer N , M, K denoting the number of milk jars, maximum number of time Dhoni will drink from any jar and maximum amount of milk Dhoni will drink at any time respectively. The second line contains N space-separated integers A1, A2, ..., AN denoting the amount of milk in each jar.

-----Output-----
- For each test case, output a single line containing the amount of milk Sir Jadega will get modulo 1,000,000,007.

-----Constraints-----
- 1 ≤ T ≤  10
- 1 ≤ N ≤  10^5
- 0 ≤ M ≤  10^6
- 1 ≤ K ≤  10^6
- 0 ≤ Ai ≤  10^9

-----Example-----
Input:
1
3 3 3
15 8 10

Output:
9

cases = int(input())

for case in range(cases):
 N, M, K = [int(i) for i in input().split()]
 A = [int(i) for i in input().split()]
 jad = 0
 P = M*K

 for milk in A:
  if(milk>P):
   jad += milk-P
  else:
   jad += milk%K

 print(jad%1000000007)


Solve in Python:
As we all know, F.C. Barcelona is the best soccer team of our era! Their entangling and mesmerizing game style usually translates into very high ball possession, consecutive counter-attack plays and goals. Lots of goals, thanks to the natural talent of their attacker and best player in history, Lionel Andres Messi.
However, at the most prestigious tournament of individual teams, the UEFA Champions League, there are no guarantees and believe it or not, Barcelona is in trouble.... They are tied versus Chelsea, which is a very defending team that usually relies on counter-strike to catch opposing teams off guard and we are in the last minute of the match. So Messi decided to settle things down for good and now he is conducting the ball on his teams' midfield and he will start a lethal counter-attack :D
After dribbling the 2 strikers from Chelsea, he now finds himself near the center of the field and he won't be able to dribble the entire team on his own, so he will need to pass the ball to one of his teammates, run forward and receive the ball once again to score the final goal.
Exactly K players are with him on his counter-attack and the coach, Tito Villanova knows that this counter-attack will end in a goal only if after exactly N passes are performed between the players, Messi ends up with the ball.
(Note that the ball only needs to end with Messi after exactly N passes are performed between all the K+1 players, i.e. Messi can receive the ball several times during the N passes. See the 2nd test case explanation for further clarification. )
However, he realized that there are many scenarios possible for this, so he asked you, his assistant coach, to tell him in how many ways can Messi score the important victory goal. So help him!!

-----Input-----
Input will contain a number T denoting the number of test cases.
Then T test cases follow, each one consisting of two space-sparated integers N and K.

-----Output-----
For each test case, output a single integer, the number of ways the winning play might happen...


Solve in Python:
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.

 [Image]

Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.

Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?

You have to determine the winner of the game for all initial positions of the marbles.

-----Input-----

The first line of input contains two integers n and m (2 ≤ n ≤ 100, $1 \leq m \leq \frac{n(n - 1)}{2}$).

The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.

-----Output-----

Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at...

# int(input())

# [int(i) for i in input().split()]

import sys

sys.setrecursionlimit(20000)

def go(v,w,last):

    if game[v][w][last] >= 0: return(game[v][w][last])

    flag = 0

    move = 0

    for p in edges_out[v]:

        if p[1] >= last:

            move = 1

            if  not go(w,p[0],p[1]):

                flag = 1

                break

    if not move or not flag:

        game[v][w][last] = 0

        return(0)

    else:

        game[v][w][last] = 1

        return(1)

n,m = [int(i) for i in input().split()]

edges_in = []

edges_out = []

for i in range(n):

    edges_in.append([])

    edges_out.append([])

for i in range(m):

    s1,s2,s3 = input().split()

    v = int(s1)-1

    w = int(s2)-1

    weight = ord(s3[0]) - ord('a') + 1

    edges_out[v].append((w,weight))

    edges_in[w].append((v,weight))

game = []

for i in range(n):

    tmp1 = []

    for j in range(n):

        tmp2 = []

        for c in range(27):

            tmp2.append(-1)

        tmp1.append(tmp2)

    game.append(tmp1)

##for v in range(n):

##    for w in range(n):

##        for last in range(27):

##            go(v,w,last)

for v in range(n):

    s = ''

    for w in range(n):

        if go(v,w,0): s = s + 'A'

        else: s = s + 'B'

    print(s)

# Made By Mostafa_Khaled


Solve in Python:
As you know America’s Presidential Elections are about to take place and the most popular leader of the Republican party Donald Trump is famous for throwing allegations against anyone he meets.

He goes to a rally and meets n people which he wants to offend. For each person i he can choose an integer between 1 to max[i].

He wants to decide in how many ways he can offend all these persons (N) given the condition that all numbers chosen by him for each person are distinct.
So he needs your help to find out the number of ways in which he can do that. If no solution is possible print 0

-----Input-----
The first line of the input contains an integer T (1<=T<=100) denoting the number of test cases. The description of T test cases follows.

The first line of each test case contains a single integer N denoting the number of people Trump wants to offend. The second line contains N space-separated integers maxnumber[0], maxnumber[1], ..., maxnumber[n-1] denoting the maxnumber that trump can choose for each person.

-----Output-----
For each test case, output a single line containing the number of ways Trump can assign numbers to the people, modulo 1,000,000,007. If it's impossible to assign distinct integers to the people, print 0

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 50
- 1 ≤ Maxnumber[i] ≤ 3000

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

Output:
4
45
0

-----Explanation-----
In case 1, He can choose any number from 1 to 4

In case 2,Out of the total 50 combination he can not take (1,1) ,(2,2) , (3,3) ,(4,4) or (5,5).

for t in range(int(input())):
 n = int(input())
 a = sorted(map(int,input().split()))
 ans = 1
 for i in range(n):
  ans *= (a[i]-i)
  ans %= (10**9+7)
  if (ans == 0):
   break
 print(ans)


Solve in Python:
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.

Elections are coming. You know the number of voters and the number of parties — $n$ and $m$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $i$-th voter $c_i$ bytecoins you can ask him to vote for any other party you choose.

The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.

-----Input-----

The first line of input contains two integers $n$ and $m$ ($1 \le n, m \le 3000$) — the number of voters and the number of parties respectively.

Each of the following $n$ lines contains two integers $p_i$ and $c_i$ ($1 \le p_i \le m$, $1 \le c_i \le 10^9$) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision.

The United Party of Berland has the index $1$.

-----Output-----

Print a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.

-----Examples-----
Input
1 2
1 100

Output
0

Input
5 5
2 100
3 200
4 300
5 400
5 900

Output
500

Input
5 5
2 100
3 200
4 300
5 800
5 900

Output
600

-----Note-----

In the first sample, The United Party wins the elections even without buying extra votes.

In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $3$, $4$ and $5$ get one vote and party number $2$ gets no votes.

In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.

def solve(max_v,votes,m):
    ans = 0
    values = []
    our_v = len(votes[0])
    for i in range(1,m):
        L = len(votes[i])
        if L > max_v:
            take = L-max_v
            our_v += take
            ans += sum(votes[i][:take])
            if take < L:
                values.extend(votes[i][take:])
        else:
            values.extend(votes[i])
    values.sort()
    if our_v <= max_v:
        needed = max_v + 1 - our_v
        if needed <= len(values):
            for i in range(needed):
                ans += values[i]
                our_v += 1
    if our_v <= max_v: return 1<<60
    return ans

n,m = [int(x) for x in input().split()]
votes = [[] for x in range(m)]

for i in range(n):
    p,c = (int(x) for x in input().split())
    p -= 1
    votes[p].append(c)

for i in range(m):
    L = len(votes[i])
    if L > 1:
        votes[i].sort()
lo = 0
hi = n // 2 + 5
while lo < hi:
    mi = lo + (hi-lo)//2
    if solve(mi,votes,m) > solve(mi+1,votes,m) : lo = mi+1
    else: hi = mi
ans = 1<<60
E = 20
for i in range(max(0,lo-E),min(lo+E,n+1)):
    ans = min(ans,solve(i,votes,m))
print(ans)


Solve in Python:
As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base!

For example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 19!

Your task is to translate the given age to the much desired 20 (or 21) years, and indicate the number base, in the format specified below.

**Note:** input will be always > 21

### Examples:

```
32  -->  "32? That's just 20, in base 16!"
39  -->  "39? That's just 21, in base 19!"
```

*Hint: if you don't know (enough) about [numeral systems](https://en.wikipedia.org/wiki/Numeral_system) and [radix](https://en.wikipedia.org/wiki/Radix), just observe the pattern!*

---

## My other katas

If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)

---

### *Translations are welcome!*

womens_age = lambda Q : f"{Q}? That's just 2{1 & Q}, in base {Q >> 1}!"


Solve in Python:
As you might remember, the collector of Siruseri had ordered
a complete revision of the Voters List. He knew that constructing
the list of voters is a difficult task, prone to errors. Some
voters may have been away on vacation, others may have moved
during the enrollment and so on.
To be as accurate as possible, he entrusted the task to three different
officials. Each of them was to independently record the list of voters and
send it to the collector. In Siruseri, every one has a ID number and
the list would only list the ID numbers of the voters and not their names.
The officials were expected to arrange the ID numbers in ascending order
in their lists.
On receiving the lists, the Collector realised that there were
discrepancies - the three lists were not identical.  He decided
to go with the majority. That is, he decided to construct the
final list including only those ID numbers that appeared in at
least 2 out of the 3 lists.  For example if the three lists
were
23  30  42  57  90
21  23  35  57  90  92
21  23  30  57  90

then the final list compiled by the collector would be:
21  23  30  57  90

The ID numbers 35, 42 and 92 which appeared in only one list
each do not figure in the final list.
Your task is to help the collector by writing a program that
produces the final list from the three given lists.
Input format
The first line of the input contains 3 integers
N1, N2 and
N3.  N1 is the number of
voters in the first list, N2 is the number of
voters in the second list and N3 is the number of
voters in the third list.  The next N1 lines
(lines 2,...,N1+1) contain one positive integer
each and describe the first list in ascending order.  The following

N2 lines (lines
N1+2,...,N1+N2+1)
describe the second list in ascending order and the final
N3 lines (lines

N1+N2+2,...,N1+N2+N3+1)
describe the third list in ascending order.
Output format
The first line of the output should contain a single integer
M indicating the number voters in the final list. The next
M lines (lines 2,...,M+1) should contain...

from sys import stdout, stdin
n,m,o = list(map(int, stdin.readline().split()))
n= n+m+o
l=[]
a=[]
for i in range(n):
    b= int(stdin.readline())
    if(b in l and b not in a):
        l.append(b)
        a.append(b)
    elif(b not in l):
        l.append(b)

a.sort()
stdout.write(str(len(a)) + '\n')
stdout.write(''.join([str(id) + '\n' for id in a]))


Solve in Python:
As you probably know, Fibonacci sequence are the numbers in the following integer sequence:
1, 1, 2, 3, 5, 8, 13...
Write a method that takes the index as an argument and returns last digit from fibonacci number. Example:
  getLastDigit(15) - 610. Your method must return 0 because the last digit of 610 is 0.
Fibonacci sequence grows very fast and value can take very big numbers (bigger than integer type can contain), so, please, be careful with overflow.

[Hardcore version of this kata](http://www.codewars.com/kata/find-last-fibonacci-digit-hardcore-version), no bruteforce will work here ;)

def get_last_digit(index):
    a, b = 0, 1
    for i in range(index):
        a, b = b, (a + b) % 10
    return a


Solve in Python:
As you see in Example test cases, the os running this service is ```posix```.

Return the output by executing the command given as the string on posix os.

See the example test cases for the expected data format.

import os
get_output=lambda Q:''.join(os.popen(Q).readlines())
import subprocess


Solve in Python:
Ash is on his way to becoming the Pokemon Master. His pokemon can perform the following moves:
- Tackle - Deal damage worth $X$ points
- Grow - Increase damage by $Y$ points i.e. $X$ = $X$ + $Y$
But, it can only perform Grow first (0 or more times) and then tackle (0 or more) times after which it cannot perform Grow again.

That is, it cannot perform the Grow operation once it has performed the tackle operation.
A pokemon can be caught only if it’s health is exactly 1. A wild pokemon has appeared and has health worth $H$ points. Find the minimum number of moves required to catch it or say that it is not possible.

-----Input:-----
-
The first line of the input consists of a single integer $T$ denoting the number of test cases.
-
Each test case consists of 3 space-separated integers $H$, $X$ and $Y$.

-----Output:-----
- For each test case, print a single line containing one integer - the minimum number of moves required to catch the pokemon if it is possible to catch it else print -1.

-----Constraints-----
-
1 <= $T$ <= 103
-
1 <=  $X$, $Y$ < $H$ <= 109

-----Subtasks-----
Subtask #1 (30 points):
- 1 <=  $X$, $Y$ < $H$ <= 1000
Subtask #2 (70 points):
- Original Constraints

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

101 10 10

11 3 3

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

-1

-----EXPLANATION:-----
-
Example Case 1:

Ash can make use of Grow once. So $X$ = 10 + 10 = 20

Then he can do Tackle 5 times to decrease $H$ to 1.

OR

Ash can make use of Grow 4 times. So $X$ = 10 + 4*10 = 50

Then he can do Tackle 2 times to decrease $H$ to 1.

Hence, a total of 6 moves are required either way which is minimum.
-
Example Case 2:

No matter how many times Ash uses Grow or Tackle, pokemon can never be caught.

# cook your dish here
import math

def printDivisors(n,X,l) :
    list = []
    for i in range(1, int(math.sqrt(n) + 1)) :
        if (n % i == 0) :
            if (n / i == i) :
                list.append(i)
                a=0
            else :
                list.append(i)
                list.append(int(n / i))

    for i in list[::-1] :
        if(i-X>=0):
            l.append(i)

T=int(input())
for _ in range(T):
    H,X,Y=list(map(int,input().split()))
    l=[]
    printDivisors(H-1,X,l)
    mv=2*H
    for i in l:
        a=(i-X)//Y
        if(a*Y==(i-X)):
            v=((H-1)//i)+a
            if(v<mv):
                mv=v

    if(mv>H):
        print(-1)

    else:
        print(mv)


Solve in Python:
Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. There can be some claimed cells in the initial state.

In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.

If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.

Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.

-----Input-----

The first line consists of a single integer $t$ $(1 \le t \le 50)$ — the number of test cases. The description of the test cases follows.

The first line of each test case consists of two space-separated integers $n$, $m$ $(1 \le n, m \le 50)$ — the number of rows and columns in the matrix.

The following $n$ lines consist of $m$ integers each, the $j$-th integer on the $i$-th line denoting $a_{i,j}$ $(a_{i,j} \in \{0, 1\})$.

-----Output-----

For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).

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

Output
Vivek
Ashish
Vivek
Ashish

-----Note-----

For the first case: One possible scenario could be: Ashish claims cell $(1, 1)$, Vivek then claims cell $(2, 2)$. Ashish can neither claim cell $(1, 2)$, nor cell $(2, 1)$ as cells $(1, 1)$ and $(2, 2)$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win.

For the second case: Ashish claims cell $(1, 1)$, the only cell that can be claimed in the first move. After that Vivek has no moves left.

For the third case: Ashish cannot make a move, so Vivek...

t=int(input())
for q in range(t):
	n,m=[int(i) for i in input().split()]
	a=[[int(j) for j in input().split()] for i in range(n)]
	row=[False for i in range(n)]
	col=[False for i in range(m)]
	nr,nc=0,0
	for i in range(n):
		for j in range(m):
			if a[i][j]==1:
				if not row[i]:
					row[i]=True
					nr+=1
				if not col[j]:
					col[j]=True
					nc+=1
	t=min(n-nr,m-nc)
	res="Vivek" if t%2==0 else "Ashish"
	print(res)


Solve in Python:
Ashley likes playing with strings.

She gives Mojo a fun problem to solve. In her imaginary string world, a string of even length is called as "Doublindrome" if both halves of the string are palindromes (both halves have length equal to half of original string).

She gives Mojo a string and asks him if he can form a "Doublindrome" by rearranging the characters of the given string or keeping the string as it is.

As Mojo is busy playing with cats, solve the problem for him.

Print "YES" (without quotes) if given string can be rearranged to form a "Doublindrome" else print "NO" (without quotes).

-----Input:-----
- First line will contain a single integer $T$, the number of testcases.
- Each testcase consists of two lines, first line consists of an integer $N$ (length of the string) and second line consists of  the string $S$.

-----Output:-----
For each testcase, print "YES"(without quotes) or "NO"(without quotes) on a new line.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 100$
- $N$ is always even.
- String $S$ consists only of lowercase English alphabets.

-----Sample Input:-----
1
8
abbacddc

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

-----EXPLANATION:-----
The given string is a Doublindrome as its 2 halves "abba" and "cddc" are palindromes.

from collections import defaultdict

for t in range(int(input())):
 n = int(input())
 s = input()
 d = defaultdict(int)
 for i in s:
  d[i] += 1
 count = 0
 for i,j in d.items():
  if j % 2 == 1:
   count += 1
 # print(count)
 if (n//2) % 2 == 0:
  if count == 0:
   print("YES")
  else:
   print("NO")
 else:
  if count == 2 or count == 0:
   print("YES")
  else:
   print("NO")


Solve in Python:
Ashley wrote a random number generator code.
Due to some reasons, the code only generates random positive integers which are not evenly divisible by 10. She gives $N$ and $S$ as input to the random number generator. The code generates a random number with number of digits equal to $N$ and sum of digits equal to $S$. The code returns -1 if no number can be generated. Print "-1" in such cases (without quotes). Else print the minimum possible product of digits of the random number generated.

-----Input:-----
- First line will contain a single integer $T$, the number of testcases.
- Each testcase consists of two space separated integers, $N$ and $S$.

-----Output:-----
For each testcase, output the answer on a new line.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 18$
- $1 \leq S \leq 5 * N$

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

2 2

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

1

-----EXPLANATION:-----
In first testcase, the only possible number of length 1 having digit sum 5 is 5. And it's product of digits is 5.
In second testcase,  only possible two digit number as a generator output is 11(as 20 is divisible by 10, it is never generated) and product of it's digits is 1.

"""
    Author : thekushalghosh
    Team   : CodeDiggers
"""
import sys,math
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(s[:len(s) - 1])
def invr():
    return(map(int,input().split()))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############
t = 1
t = inp()
for tt in range(t):
    n,s = invr()
    if n == 2 and s > 1:
        print(s - 1)
    elif n > 2 and s > 1:
        print(0)
    elif n == 1:
        print(s)
    else:
        print(-1)