Solve in Python:
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.

To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.

For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :

Initially, the company name is ???.

Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.

Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.

Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.

In the end, the company name is oio.

Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?

A string s = s_1s_2...s_{m} is called lexicographically smaller than a string t = t_1t_2...t_{m} (where s ≠ t) if s_{i} < t_{i} where i is the smallest index such that s_{i} ≠ t_{i}. (so s_{j} = t_{j} for all j < i)

-----Input-----

The first line of input contains a string s of length n (1 ≤ n ≤ 3·10^5). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially.

The...

oleg = input()
igor = input()
oleg = sorted(list(oleg))
igor = sorted(list(igor))
n = len(oleg)
oleg_turns = (n + 1) // 2
igor_turns = n // 2
min_oleg_id = 0
min_igor_id = n - igor_turns
ans = ['?'] * n
max_oleg_id = oleg_turns - 1
max_igor_id = n - 1
curr_turn = 'o'
next_turn = {'o' : 'i', 'i' : 'o'}
l_ans = 0
r_ans = n - 1
while r_ans >= l_ans:
    if curr_turn == 'o':
        if oleg[min_oleg_id] < igor[max_igor_id]:
            ans[l_ans] = oleg[min_oleg_id]
            l_ans += 1
            min_oleg_id += 1
        else:
            ans[r_ans] = oleg[max_oleg_id]
            r_ans += -1
            max_oleg_id += -1
        curr_turn = 'i'
    else:
        if igor[max_igor_id] > oleg[min_oleg_id]:
            ans[l_ans] = igor[max_igor_id]
            l_ans += 1
            max_igor_id += -1
        else:
            ans[r_ans] = igor[min_igor_id]
            r_ans += -1
            min_igor_id += 1
        curr_turn = 'o'
strans = ''.join(ans)
print(strans)


Solve in Python:
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.

To improve his division skills, Oleg came up with $t$ pairs of integers $p_i$ and $q_i$ and for each pair decided to find the greatest integer $x_i$, such that:   $p_i$ is divisible by $x_i$;  $x_i$ is not divisible by $q_i$.  Oleg is really good at division and managed to find all the answers quickly, how about you?

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 50$) — the number of pairs.

Each of the following $t$ lines contains two integers $p_i$ and $q_i$ ($1 \le p_i \le 10^{18}$; $2 \le q_i \le 10^{9}$) — the $i$-th pair of integers.

-----Output-----

Print $t$ integers: the $i$-th integer is the largest $x_i$ such that $p_i$ is divisible by $x_i$, but $x_i$ is not divisible by $q_i$.

One can show that there is always at least one value of $x_i$ satisfying the divisibility conditions for the given constraints.

-----Example-----
Input
3
10 4
12 6
179 822

Output
10
4
179

-----Note-----

For the first pair, where $p_1 = 10$ and $q_1 = 4$, the answer is $x_1 = 10$, since it is the greatest divisor of $10$ and $10$ is not divisible by $4$.

For the second pair, where $p_2 = 12$ and $q_2 = 6$, note that   $12$ is not a valid $x_2$, since $12$ is divisible by $q_2 = 6$;  $6$ is not valid $x_2$ as well: $6$ is also divisible by $q_2 = 6$.  The next available divisor of $p_2 = 12$ is $4$, which is the answer, since $4$ is not divisible by $6$.

mod = 1000000007
eps = 10**-9

def main():
    import sys
    input = sys.stdin.readline

    def PrimeDecomposition(N):
        ret = {}
        n = int(N ** 0.5)
        for d in range(2, n + 1):
            while N % d == 0:
                if d not in ret:
                    ret[d] = 1
                else:
                    ret[d] += 1
                N //= d
            if N == 1:
                break
        if N != 1:
            ret[N] = 1
        return ret

    for _ in range(int(input())):
        p, q = list(map(int, input().split()))
        if p % q != 0:
            print(p)
            continue
        prime = PrimeDecomposition(q)
        C = {}
        mi = p
        for pr in prime:
            C = 0
            tmp = p
            while tmp % pr == 0:
                C += 1
                tmp //= pr
            mi = min(mi, pr ** (C - prime[pr] + 1))
        print(p // mi)

def __starting_point():
    main()

__starting_point()


Solve in Python:
Oliver and Nova are true lovers. Inspite of knowing that Nova will die Oliver married her at the lake where they met. But they had a conflict about even and odd numbers. Nova likes the odd numbers and Oliver prefers even. One day they went to a fair where Oliver bought some square shaped marshmallows and Nova bought some round shaped. Then they decided to play a game. They will pick a natural number N . Nova will sum up the odd numbers from 1 to N and and she will notedown LCM of R(R is defined in the picture) and the sum she calculated before. And Oliver will sum up the even numbers from 1 to N and and he will notedown LCM of S(S is defined in the picture) and the sum he calculated before. You must use the ceil value of R and S.

Now  whose LCM is strictly greater than the other will win.If both of their LCM is equal Nova will win because Oliver is afraid of Nova.
$N.B.$ define the value of pi with $acos(-1)$.
$N.B.$ Sum of all odd number and sum of all even number will not exceed 10^18.

-----Input:-----
The first line contains an integer $T$  — the number of test cases in the input. Next, T test cases are given, one per line.
Each test case is a positive integer $N$  .

-----Output:-----
Print T answers to the test cases.
In each test cases,
If Oliver wins the game, print "Nova's gonna kill me" (without quotes) .
If Nova wins the game, print "YESS(sunglass emo)" (without quotes) .

-----Constraints-----
- $1 \leq T \leq 2000$
- $1 \leq N \leq 1845271$

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

-----Sample Output:-----
YESS(sunglass emo)

import math

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

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

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

    na = math.ceil((2*n)/math.acos(-1))
    nb = ((n+1)//2)**2

    nlcm = lcm(na, nb)

    oa = math.ceil(n/2)
    ob = (n//2)*(n//2+1)

    olcm = lcm(oa, ob)

    if olcm > nlcm:
        print("Nova's gonna kill me")
    else:
        print("YESS(sunglass emo)")

# cook your dish here


Solve in Python:
Omy and Ish were learning the pattern printing. In order to learn they give themselves a task. In this task they are given a string and they have to form a pyramid with the pattern as follows:
RowNumber are one based indexed.
-
If (RowNumber % 3 == 0) then string is written in left to right while in other cases it is written in right to left order.
-
if the string end it will be started again and end of the pyramid need not to be the end of string.
For eg: string is “$CODING$” and height of pyramid is “$5$”
C
D O
I N G
I D O C
D O C G N

Omi will be asked $Q$ queries and he has to tell the frequency of a character  C in that particular row $R$ of pyramid.

-----Input:-----
- First line will contain $N$, height of pyramid.
- Next line contain a string consists only of Uppercase English Alphabets, length not exceed $10^6$
- Third line contain a single integer $Q$, the number of queries to be asked.
- Each query contain two space separated integers, $R$ and $C$, where $R$ is the row number and $C$ is the character.

-----Output:-----
- For each query, output in a single line the frequency of the alphabet in the given row.

-----Constraints:-----
- $1$ $\leq$ $N$ $\leq$ $10$^$18$
- $1$ $\leq$ $Q$ $\leq$ $50000$
- $1 \leq R \leq N$
- $A \leq C \leq Z$

-----Sample Input:-----
5
CODING
2
1 C
2 D

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

import sys

n = int(sys.stdin.readline().strip())
s = sys.stdin.readline().strip()

alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

arr = [0]*26
pref = []

for i in range(len(s)):
	for j in range(26):
		if alph[j] == s[i]:
			arr[j] += 1
			break
	pref += [arr[:]]

# for x in pref:
# 	print(x)

q = int(sys.stdin.readline().strip())

for _ in range(q):
	r, c = sys.stdin.readline().strip().split()

	for i in range(26):
		if alph[i] == c:
			ind = i
			break

	r = int(r)

	prev = ((r-1)**2 + r-1)//2

	done = prev%len(s)

	ans = 0
	rem = (len(s) - done)%len(s)

	if r <= rem:
		print(pref[done+r-1][ind] - pref[done-1][ind])
		continue

	if rem != 0:
		ans += pref[-1][ind] - pref[done-1][ind]
		r -= rem

	ans += pref[-1][ind] * (r//len(s))
	r %= len(s)

	# print("AA", ans, r)

	if r != 0:
		ans += pref[r-1][ind]

	print(ans)

	# print(rem, done, prev)


Solve in Python:
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $k$ ($k \ge 3$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.

Mountains are described by a sequence of heights $a_1, a_2, \dots, a_n$ in order from left to right ($k \le n$). It is guaranteed that neighboring heights are not equal to each other (that is, $a_i \ne a_{i+1}$ for all $i$ from $1$ to $n-1$).

Peaks of mountains on the segment $[l,r]$ (from $l$ to $r$) are called indexes $i$ such that $l < i < r$, $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$. It is worth noting that the boundary indexes $l$ and $r$ for the segment are not peaks. For example, if $n=8$ and $a=[3,1,4,1,5,9,2,6]$, then the segment $[1,8]$ has only two peaks (with indexes $3$ and $6$), and there are no peaks on the segment $[3, 6]$.

To break the door, Nastya throws it to a segment $[l,l+k-1]$ of consecutive mountains of length $k$ ($1 \le l \le n-k+1$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $p+1$, where $p$ is the number of peaks on the segment $[l,l+k-1]$.

Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $[l, l+k-1]$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $l$ is minimal.

Formally, you need to choose a segment of mountains $[l, l+k-1]$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $l$.

-----Input-----

The first line contains an integer $t$ ($1 \leq t \leq 10^4$)  — the number of test cases. Then the descriptions of the test cases follow.

The first...

import sys

input = sys.stdin.readline

for _ in range(int(input())):
    n, k = list(map(int, input().split()))
    a = list(map(int, input().split()))
    peak = [0] + [1 if a[i - 1] < a[i] and a[i] > a[i + 1] else 0 for i in range(1, n - 1)] + [0]
    b = [None] * (n - k + 1)
    b[0] = sum(peak[1 : k - 1])
    for i in range(1, n - k + 1):
        b[i] = b[i - 1] - peak[i] + peak[i + k - 2]
    p = max(b)
    print(p + 1, b.index(p) + 1)


Solve in Python:
On Miu's smart phone, there is a search feature which lets her search for a contact name by typing digits on the keypad where each digit may correspond to any of the characters given below it. For example, to search for TOM, she can type 866 and for MAX she can type 629.
+------+-----+------+
|   1  |  2  |   3  |
|      | ABC |  DEF |
+------+-----+------+
|   4  |  5  |   6  |
|  GHI | JKL |  MNO |
+------+-----+------+
|   7  |  8  |   9  |
| PQRS | TUV | WXYZ |
+------+-----+------+
|      |  0  |      |
+------+-----+------+

Miu typed a random string of digits $S$ on the keypad while playing around, where each digit is between 2 and 9 inclusive. Now she wants to know the number of possible strings which would map to $S$.
Since this number can be very large, output it modulo 10^9 + 7 (1000000007)

-----Input:-----
-
The first line of the input consists of a single integer $T$ denoting the number of test cases.
-
Each test case consists of a string $S$.

-----Output:-----
- For each test case, print a single line containing one integer - the count of all possible strings mod 1,000,000,007

-----Constraints-----
-
1 <= $T$ <= 10
-
1 <= $|S|$ <= 105

-----Subtasks-----
Subtask #1 (10 points):
- 1 <= $|S|$ <= 10
Subtask #2 (90 points):
- Original Constraints

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

5

72

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

12

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

On the key 5, we have the character set JKL.

Hence the possible strings are J,K,L.

Hence the answer is 3 % (1000000007) = 3.
-
Example Case 2:
On key 7, we have the character set PQRS.

On key 2, we have the character set ABC.

Hence the possible strings are PA,PB,PC,QA,QB,QC,RA,RB,RC,SA,SB,SC.

Hence the answer is 12 % (1000000007) = 12.

# cook your dish here
t=int(input())
while(t>0):
 n=int(input())
 c=1
 while(n>0):
  m=n%10
  if(m==7 or m==9):
   c*=4
  else:
   c*=3
  n=n//10
 print(c%1000000007)
 t-=1


Solve in Python:
On Unix system type files can be identified with the ls -l command which displays the type of the file in the first alphabetic letter of the file system permissions field. You can find more information about file type on Unix system on the [wikipedia page](https://en.wikipedia.org/wiki/Unix_file_types).

- '-' A regular file ==> `file`.
- 'd' A directory ==> `directory`.
- 'l' A symbolic link ==> `symlink`.
- 'c' A character special file. It refers to a device that handles data as a stream of bytes (e.g: a terminal/modem) ==> `character_file`.
- 'b' A block special file. It refers to a device that handles data in blocks (e.g: such as a hard drive or CD-ROM drive) ==> `block_file`.
- 'p' a named pipe ==> `pipe`.
- 's' a socket ==> `socket`.
- 'D' a door ==> `door`.

In this kata you should complete a function that return the `filetype` as a string regarding the `file_attribute` given by the `ls -l` command.

For example if the function receive `-rwxr-xr-x` it should return `file`.

import re
def linux_type(file_attribute):
    types={"-": "file",
          "d": "directory",
          "l": "symlink",
          "c": 'character_file',
           "b": 'block_file',
           "p": "pipe",
           "s": "socket",
           "D": "door"
          }
    return types[file_attribute[0]]


Solve in Python:
On a 2-dimensional grid, there are 4 types of squares:

1 represents the starting square.  There is exactly one starting square.
2 represents the ending square.  There is exactly one ending square.
0 represents empty squares we can walk over.
-1 represents obstacles that we cannot walk over.

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

Example 1:
Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
Explanation: We have the following two paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)

Example 2:
Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output: 4
Explanation: We have the following four paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)

Example 3:
Input: [[0,1],[2,0]]
Output: 0
Explanation:
There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.

Note:

1 <= grid.length * grid[0].length <= 20

class Solution:
    def uniquePathsIII(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        # step 1). initialize the conditions for backtracking
        #   i.e. initial state and final state
        non_obstacles = 0
        start_row, start_col = 0, 0
        for row in range(0, rows):
            for col in range(0, cols):
                cell = grid[row][col]
                if  cell >= 0:
                    non_obstacles += 1
                if cell == 1:
                    start_row, start_col = row, col

        # count of paths as the final result
        path_count = 0

        # step 2). backtrack on the grid
        def backtrack(row, col, remain):
            # we need to modify this external variable
            nonlocal path_count
            print(grid)

            # base case for the termination of backtracking
            if grid[row][col] == 2 and remain == 1:
                # reach the destination
                path_count += 1
                return

            # mark the square as visited. case: 0, 1, 2
            temp = grid[row][col]
            grid[row][col] = -4
            remain -= 1   # we now have one less square to visit

            # explore the 4 potential directions around
            for ro, co in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                next_row, next_col = row + ro, col + co

                if not (0 <= next_row < rows and 0 <= next_col < cols):
                    # invalid coordinate
                    continue
                if grid[next_row][next_col] < 0:
                    # either obstacle or visited square
                    continue

                backtrack(next_row, next_col, remain)

            # unmark the square after the visit
            grid[row][col] = temp

        backtrack(start_row, start_col, non_obstacles)

        return path_count


Solve in Python:
On a broken calculator that has a number showing on its display, we can perform two operations:

Double: Multiply the number on the display by 2, or;
Decrement: Subtract 1 from the number on the display.

Initially, the calculator is displaying the number X.
Return the minimum number of operations needed to display the number Y.

Example 1:
Input: X = 2, Y = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.

Example 2:
Input: X = 5, Y = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.

Example 3:
Input: X = 3, Y = 10
Output: 3
Explanation:  Use double, decrement and double {3 -> 6 -> 5 -> 10}.

Example 4:
Input: X = 1024, Y = 1
Output: 1023
Explanation: Use decrement operations 1023 times.

Note:

1 <= X <= 10^9
1 <= Y <= 10^9

class Solution:
    def brokenCalc(self, X: int, Y: int) -> int:
        cnt=0
        while Y>X:
            cnt+=1
            if Y%2==0:
                Y//=2
            else:
                Y+=1
        return cnt+X-Y


Solve in Python:
On a planet called RUIZ LAND, which is ruled by the queen, Erika Ruiz. Each person on that planet has a strength value (strength value >0).
That planet has a special rule made by the queen that a boy and a girl will form a couple if their Hate value is a prime number where $Hate$ is given by the formula:-
Hate = (boy's strength value)  XOR (girl's strength value )
You are given $N$ numbers denoting the strength value of $N$ girls, and each of the $N$ girls has to form a couple with a boy such that sum of $Hate$ value of all the $N$ couples will be minimum.
You need to print the strength value of each boy, Where the boy at index $i$ will form a couple with the girl at index $i$, where $1 \leq i \leq N$.
Assume that you can always find at least one boy having that strength for each girl.

-----Input:-----
- First line will contain $N$, the number of Girls.
- Next line contains $N$ numbers separated by space denoting strength value for each girl.

-----Output:-----
Print the required $N$ numbers denoting strength of boys.

-----Constraints-----
- $1 \leq N \leq 100000$
- $1 \leq A_i \leq 10^9$ , (where $1 \leq i \leq N$) and $A_i$ denotes strength of i'th girl.

-----Sample Input:-----
2
10 16

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

lens = int(input())
arrs = [int(x) for x in input().split()]
vals = []
for a in arrs:
    if a != 2:
        vals.append(2 ^ a)
    else:
        vals.append(3 ^ a)
print(*vals)


Solve in Python:
On a table are N cards, with a positive integer printed on the front and back of each card (possibly different).
We flip any number of cards, and after we choose one card.
If the number X on the back of the chosen card is not on the front of any card, then this number X is good.
What is the smallest number that is good?  If no number is good, output 0.
Here, fronts[i] and backs[i] represent the number on the front and back of card i.
A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.
Example:
Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output: 2
Explanation: If we flip the second card, the fronts are [1,3,4,4,7] and the backs are [1,2,4,1,3].
We choose the second card, which has number 2 on the back, and it isn't on the front of any card, so 2 is good.

Note:

1 <= fronts.length == backs.length <= 1000.
1 <= fronts[i] <= 2000.
1 <= backs[i] <= 2000.

class Solution:
    def flipgame(self, fronts: List[int], backs: List[int]) -> int:
        same = {x for x, y in zip(fronts, backs) if x == y}
        return min([i for i in fronts + backs if i not in same] or [0])


Solve in Python:
On an 8 x 8 chessboard, there is one white rook.  There also may be empty squares, white bishops, and black pawns.  These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.
The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies.  Also, rooks cannot move into the same square as other friendly bishops.
Return the number of pawns the rook can capture in one move.

Example 1:

Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
In this example the rook is able to capture all the pawns.

Example 2:

Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation:
Bishops are blocking the rook to capture any pawn.

Example 3:

Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
The rook can capture the pawns at positions b5, d6 and f5.

Note:

board.length == board[i].length == 8
board[i][j] is either 'R', '.', 'B', or 'p'
There is exactly one cell with board[i][j] == 'R'

class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        count=0;
        for i in range(len(board)):
            for j in range(len(board[i])):
                if board[i][j]=='R':
                    d=1;
                    #위
                    while 0<=i-d:
                        if board[i-d][j]=='B':
                            break;
                        elif board[i-d][j]=='p':
                            count+=1;
                            break;
                        else:
                            d+=1;
                    d=1;
                    #아래
                    while i+d<=len(board)-1:
                        if board[i+d][j]=='B':
                            break;
                        elif board[i+d][j]=='p':
                            count+=1;
                            break;
                        else:
                            d+=1;
                    d=1;
                    #왼쪽
                    while 0<=j-d:
                        if board[i][j-d]=='B':
                            break;
                        elif board[i][j-d]=='p':
                            count+=1;
                            break;
                        else:
                            d+=1;
                    d=1;
                    #오른쪽
                    while j+d<=len(board[i])-1:
                        if board[i][j+d]=='B':
                            break;
                        elif board[i][j+d]=='p':
                            count+=1;
                            break;
                        else:
                            d+=1;
        return count;


Solve in Python:
On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).

Now rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.

You start at the top left square (0, 0). What is the least time until you can reach the bottom right square (N-1, N-1)?

Example 1:

Input: [[0,2],[1,3]]
Output: 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.

You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.

Example 2:

Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output: 16
Explanation:
 0  1  2  3  4
24 23 22 21  5
12 13 14 15 16
11 17 18 19 20
10  9  8  7  6

The final route is marked in bold.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.

Note:

       2 <= N <= 50.
       grid[i][j] is a permutation of [0, ..., N*N - 1].

class Solution:
     def reorganizeString(self, S):
         """
         :type S: str
         :rtype: str
         """
         '''
         size = len(S)
         limit = size//2 + size%2
         cnt = collections.Counter(S)
         res = [0]*size
         i = 0
         for k, v in cnt.most_common():
             if v > limit:
                 return ''
             for _ in range(v):
                 if i >= size:
                     i = res.index(0)
                 res[i] = k
                 i += 2
         return ''.join(res)
         '''
         cnt = collections.Counter(S)
         res = '#'
         while cnt:
             stop = True
             for k, v in cnt.most_common():
                 if k != res[-1]:
                     stop = False
                     res += k
                     cnt[k] -= 1
                     if not cnt[k]:
                         del cnt[k]
                     break
             if stop == True:
                 break
         return res[1:] if len(res) == len(S)+1 else ''


Solve in Python:
On an infinite number line (x-axis), we drop given squares in the order they are given.
The i-th square dropped (positions[i] = (left, side_length)) is a square with the left-most point being positions[i][0] and sidelength positions[i][1].
The square is dropped with the bottom edge parallel to the number line, and from a higher height than all currently landed squares.  We wait for each square to stick before dropping the next.
The squares are infinitely sticky on their bottom edge, and will remain fixed to any positive length surface they touch (either the number line or another square).  Squares dropped adjacent to each other will not stick together prematurely.

Return a list ans of heights.  Each height ans[i] represents the current highest height of any square we have dropped, after dropping squares represented by positions[0], positions[1], ..., positions[i].

Example 1:

Input: [[1, 2], [2, 3], [6, 1]]
Output: [2, 5, 5]
Explanation:

After the first drop of positions[0] = [1, 2]:
_aa
_aa
-------
The maximum height of any square is 2.

After the second drop of positions[1] = [2, 3]:
__aaa
__aaa
__aaa
_aa__
_aa__
--------------
The maximum height of any square is 5.
The larger square stays on top of the smaller square despite where its center
of gravity is, because squares are infinitely sticky on their bottom edge.

After the third drop of positions[1] = [6, 1]:
__aaa
__aaa
__aaa
_aa
_aa___a
--------------
The maximum height of any square is still 5.

Thus, we return an answer of [2, 5, 5].

Example 2:

Input: [[100, 100], [200, 100]]
Output: [100, 100]
Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces.

Note:
1 .
1 .
1 .

class Solution:
     def fallingSquares(self, positions):
         """
         :type positions: List[List[int]]
         :rtype: List[int]
         """
         to_cor = {}
         for x, l in positions:
             to_cor[x] = 1
             to_cor[x+l] = 1
         for i, v in enumerate(sorted(to_cor.keys())):
             to_cor[v] = i
         over = Overlapper(len(to_cor))
         ans = []
         mx = 0
         for x, l in positions:
             tmx = over.getMax(to_cor[x], to_cor[x+l])+l
             mx = max(mx, tmx)
             ans.append(mx)
             over.Update(to_cor[x], to_cor[x+l], tmx)
         return ans

 class Overlapper:
     def __init__(self, n):
         self.line = [0]*n

     def getMax(self, a, b):
         return max(self.line[a:b])

     def Update(self, a, b, mx):
         self.line[a:b] = [mx]*(b-a)


Solve in Python:
On an infinite plane, a robot initially stands at (0, 0) and faces north.  The robot can receive one of three instructions:

"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.

The robot performs the instructions given in order, and repeats them forever.
Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

Example 1:
Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.

Example 2:
Input: "GG"
Output: false
Explanation:
The robot moves north indefinitely.

Example 3:
Input: "GL"
Output: true
Explanation:
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...

Note:

1 <= instructions.length <= 100
instructions[i] is in {'G', 'L', 'R'}

class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
      # loop through all the commands in the arr
      # scenario the direction is not facing the same

        def is_infinite_loop(command):
            # iterate over all the commands
            # direction 0: NameError
            # x and y coordinates, if x and 0 is (0, 0) return True
            direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]
            d_index = 0
            x, y = 0, 0
            for move in command:
                if move == 'G':
                    x += direction[d_index][0]
                    y += direction[d_index][1]
                elif move == 'R':
                    d_index = (d_index + 1) % 4
                elif move == 'L':
                    d_index = (d_index + 3) % 4
            # if back at origin
            # print(d_index)
            if x == y == 0:
                return True
            if (x != 0 or y != 0) and d_index != 0:
                return True
            return False

        return is_infinite_loop(instructions)

# class Solution:
#     def isRobotBounded(self, instructions: str) -> bool:
#         L_occurances = instructions.count('L')
#         R_occurances = instructions.count('R')
#         difference = L_occurances - R_occurances

#         if difference % 4 == 0:
#             # check if loop otherwise return False too
#             directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # N, E, S, W
#             d = 0                                           # start at North index
#             point = [0, 0]
#             for instruction in instructions:
#                 if instruction == 'G':
#                     point[0] += directions[d][0]
#                     point[1] += directions[d][1]
#                 elif instruction == 'L':
#                     d = (d + 3) % 4
#                 elif instruction == 'R':
#                     d = (d + 1) % 4
#             return True if point == [0, 0] else False
#         else:
#             return True

    ...


Solve in Python:
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Now we view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.
Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.

Example 1:
Input: [[2]]
Output: 5

Example 2:
Input: [[1,2],[3,4]]
Output: 17
Explanation:
Here are the three projections ("shadows") of the shape made with each axis-aligned plane.

Example 3:
Input: [[1,0],[0,2]]
Output: 8

Example 4:
Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 14

Example 5:
Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 21

Note:

1 <= grid.length = grid[0].length <= 50
0 <= grid[i][j] <= 50

class Solution:
    def projectionArea(self, grid: List[List[int]]) -> int:

        max_rows = [0 for _ in grid]
        max_cols = [0 for _ in grid]

        total_nonzero = 0

        for r in range(len(grid)):

            for c in range(len(grid[r])):

                if grid[r][c] > max_cols[c]:
                    max_cols[c] = grid[r][c]

                if grid[r][c] > max_rows[r]:
                    max_rows[r] = grid[r][c]

                if grid[r][c] > 0:
                    total_nonzero += 1

        print(max_rows)
        print(max_cols)
        print(total_nonzero)

        return sum(max_rows) + sum(max_cols) + total_nonzero


Solve in Python:
On each of the following $N$ days (numbered $1$ through $N$), Chef is planning to cook either pizza or broccoli. He wrote down a string $A$ with length $N$, where for each valid $i$, if the character $A_i$ is '1', then he will cook pizza on the $i$-th day, while if $A_i$ is '0', he will cook broccoli on this day.
Chefu, his son, loves pizza but hates broccoli ― just like most kids. He wants to select a substring of $A$ with length $K$ and change each character '0' in this substring to '1'. Afterwards, let's define pizza time as the maximum number of consecutive days where Chef will cook pizza. Find the maximum pizza time Chefu can achieve.

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

-----Output-----
For each test case, print a single line containing one integer ― the maximum pizza time.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le K \le N \le 10^5$
- $A$ contains only characters '0' and '1'
- the sum of $N$ over all test cases does not exceed $10^6$

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

-----Example Input-----
2
13 2
0101110000101
6 3
100001

-----Example Output-----
5
4

-----Explanation-----
Example case 1: Chefu can choose the substring $A[2, 3]$ = "10", and change the third character of $A$ to '1'. Then, the pizza time is $5$ days: from day $2$ to day $6$.
Example case 2: Chefu can choose the substring $A[2, 4]$ = "000". Then, the pizza time is $4$ days: from day $1$ to day $4$.

t = int(input())
for T in range(t):
 n, k = [int(x) for x in input().split()]
 s = input()
 l, r = [0] * n, [0] * n

 for i in range(1, n):
  if s[i - 1] == '1':
   l[i] = l[i - 1] + 1
 for i in range(n - 2, -1, -1):
  if s[i + 1] == '1':
   r[i] = r[i + 1] + 1

 ans = 0
 for i in range(n - k + 1):
  ans = max(ans, l[i] + k + r[i + k - 1])
 print(ans)


Solve in Python:
On fictional islands of Matunga archipelage several different tribes use fictional currency - tung. One tung is a very small amount, so all payments are made with coins of different values. For example, one tribe use coins of 7 and 9 tungs, another - 6, 10 and 11 tungs. Every tribe has at least 2 different coins.
Also every tribe has a shop with remarkable feature: if you find an item N tungs worth, you always can find an item priced N+1 tungs in the same shop.
Your goal is to write the function min_price(coins) which finds out the minimum price of item which can be in sale in Matunga tribe shop, knowing the values of coins used there.

Function should return -1 if result is not accessible (i.e. coins of these values can't cover natural row from N to infinity without gaps).

For example, some tribe has coins of 3 and 5 tungs. They can't sell items of 4 or 7 tungs, because 4 and 7 can't be represented as a sum of 3's and 5's. But starting from 8 tungs you can do it with every sum: 8 is 5+3, 9 is 3+3+3, 10 is 5+5, 11 is 5+3+3 and so on. So the answer for this set of coins is 8.

from fractions import gcd

def min_price(nums):
    nums.sort()
    ns = [0] + [float('inf')] * (nums[0] - 1)
    for c in nums[1:]:
        d = gcd(nums[0], c)
        for r in range(d):
            n = min(ns[r::d], default=float('inf'))
            if n < float('inf'):
                for j in range(nums[0] // d):
                    n += c
                    p = n % nums[0]
                    ns[p] = n = min(n, ns[p])
    max_ = max(ns) or 1
    return max_ - nums[0] + 1 if max_ < float('inf') else -1


Solve in Python:
On her way to ChefLand, Marichka noticed $10^K$ road signs (numbered $0$ through $10^K - 1$). For each valid $i$, the sign with number $i$ had the integer $i$ written on one side and $10^K-i-1$ written on the other side.
Now, Marichka is wondering — how many road signs have exactly two distinct decimal digits written on them (on both sides in total)? Since this number may be large, compute it modulo $10^9+7$.
For example, if $K = 3$, the two integers written on the road sign $363$ are $363$ and $636$, and they contain two distinct digits $3$ and $6$, but on the road sign $362$, there are integers $362$ and $637$, which contain four distinct digits — $2$, $3$, $6$ and $7$. On the road sign $11$, there are integers $11$ and $988$, which contain three distinct digits — $1$, $9$ and $8$.

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

-----Output-----
For each test case, print a single line containing one integer — the number of road signs with exactly two digits, modulo $10^9+7$.

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

-----Subtasks-----
Subtask #1 (20 points): $1 \le T, K \le 5$
Subtask #2 (80 points): original constraints

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

-----Example Output-----
10

import math
t=int(input())
for i in range(t):
    k=int(input())
    res=((pow(2,k,1000000007))*5)
    print(res)


Solve in Python:
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).

Examples:
Input: N = 1, K = 1
Output: 0

Input: N = 2, K = 1
Output: 0

Input: N = 2, K = 2
Output: 1

Input: N = 4, K = 5
Output: 1

Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001

Note:

       N will be an integer in the range [1, 30].
       K will be an integer in the range [1, 2^(N-1)].

import math
 class Solution:
     def maxChunksToSorted(self, arr):
         count = 0

         minVal = [0] * len(arr)
         minSofar = math.inf
         for idx in reversed(range(len(arr))):
             minVal[idx] = min(minSofar, arr[idx])
             minSofar = minVal[idx]

         maxSofar = -math.inf
         for idx in range(len(arr)):
             maxSofar = max(maxSofar, arr[idx])
             if idx == len(arr) - 1:
                 count += 1
             elif maxSofar <= minVal[idx+1]:
                 count+=1

         return count


Solve in Python:
On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t).
He can move in arbitrary directions with speed 1.
Here, we will consider him as a point without size.
There are N circular barriers deployed on the plane.
The center and the radius of the i-th barrier are (x_i, y_i) and r_i, respectively.
The barriers may overlap or contain each other.
A point on the plane is exposed to cosmic rays if the point is not within any of the barriers.
Snuke wants to avoid exposure to cosmic rays as much as possible during the travel.
Find the minimum possible duration of time he is exposed to cosmic rays during the travel.

-----Constraints-----
 - All input values are integers.
 - -10^9 ≤ x_s, y_s, x_t, y_t ≤ 10^9
 - (x_s, y_s) ≠ (x_t, y_t)
 - 1≤N≤1,000
 - -10^9 ≤ x_i, y_i ≤ 10^9
 - 1 ≤ r_i ≤ 10^9

-----Input-----
The input is given from Standard Input in the following format:
x_s y_s x_t y_t
N
x_1 y_1 r_1
x_2 y_2 r_2
:
x_N y_N r_N

-----Output-----
Print the minimum possible duration of time Snuke is exposed to cosmic rays during the travel.
The output is considered correct if the absolute or relative error is at most 10^{-9}.

-----Sample Input-----
-2 -2 2 2
1
0 0 1

-----Sample Output-----
3.6568542495

An optimal route is as follows:

import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

from heapq import heapify,heappop,heappush
def dijkstra(G,s = 0): #sを始点とした最短経を求める
    n = len(G)
    dist = [INF] * n
    dist[s] = 0
    q = [(0,s)]
    while q:
        d,v = heappop(q)
        if dist[v] < d:
            continue
        for e,cost in G[v]:
            if dist[e] > dist[v] + cost:
                dist[e] = dist[v] + cost
                heappush(q,(dist[e],e))
    return dist

from math import hypot
def main():
    sy,sx,gy,gx = map(int,input().split())
    N = int(input())
    circles = [(sy,sx,0)] + [tuple(map(int,input().split())) for _ in range(N)] + [(gy,gx,0)]
    N += 2

    G = [[] for _ in range(N)]
    for i in range(N):
        x,y,z = circles[i]
        for j in range(i + 1,N):
            p,q,r = circles[j]
            d = max(0,hypot(x - p,y - q) - z - r)
            G[i].append((j,d))
            G[j].append((i,d))

    dist = dijkstra(G)
    ans = dist[-1]
    print(ans)
def __starting_point():
    main()
__starting_point()


Solve in Python:
Once N boys and M girls attended a party. You are given a matrix A of N rows and M columns where Aij is 1 if the i-th boy likes the j-th girl, otherwise it will be 0. Note that it is not necessary that if a boy x likes girl y, then girl y should like boy x.
You know that if there are two different boys x and y, who both like girl z, then there will be a collision.
Can you calculate the number of different collisions at this party? Note that order of boys in the collision doesn't matter.

-----Input-----
The first line contains a single integer T denoting the number of test cases. Then T test cases follow.
The first line of each test case contains two space separated integers N, M denoting the number of boys and girls, respectively.
Each of the following N lines contain M characters, each of them is either '0' or '1'.

-----Output-----
For each test case output a single line containing an integer corresponding to the number of collisions at the party.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N, M ≤ 10

-----Example-----
Input:
2
4 3
111
100
110
000
2 2
10
01

Output:
4
0

-----Explanation-----
Example Case 1. All three boys like the first girl, so there are (1, 2, 1), (1, 3, 1), (2, 3, 1) collisions with her. Boys 1 and 3 both like the second girl so this is one more collision. Only one boy likes the third girl, so there are no collisions with her and thus we have 4 collisions total.
Example Case 2. For each girl there is only one boy who likes her, so there are no collisions at all.

# cook your dish here
t = int(input())
for _ in range(t):
 n, m = map(int, input().split())
 matrix = []
 for i in range(n):
  matrix.append(list(input()))
 collision = 0
 for i in range(m):
  count = 0
  for j in range(n):
   if matrix[j][i] == '1':
    count += 1
  # print('Count:', count)
  if count > 1:
   collision += ((count * (count-1)) // 2)
 print(collision)


Solve in Python:
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.

The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).

Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.

Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 10^9 + 9.

-----Input-----

The first line contains number m (2 ≤ m ≤ 10^5).

The following m lines contain the coordinates of the cubes x_{i}, y_{i} ( - 10^9 ≤ x_{i} ≤ 10^9, 0 ≤ y_{i} ≤ 10^9) in ascending order of numbers written on them. It is guaranteed that the original figure is stable.

No two cubes occupy the same place.

-----Output-----

In the only line print the answer to the...

import heapq

def coor_neighbor(coor, dxs, dys):
    x, y = coor
    for dx in dxs:
        for dy in dys:
            yield x + dx, y + dy

def coor_bottoms(coor):
    return coor_neighbor(coor, (-1, 0, 1), (-1, ))

def coor_tops(coor):
    return coor_neighbor(coor, (-1, 0, 1), (1, ))

def coor_sibs(coor):
    return coor_neighbor(coor, (-2, -1, 1, 2), (0, ))

class Figure:

    def __init__(self, coors):
        self._coors = dict()
        self._stables_min = []
        self._stables_max = []
        self._pushed = set()
        self._dropped = set()

        cubes = dict()
        self._bots = dict()
        self._tops = dict()
        for idx, coor in enumerate(coors):
            cubes[coor] = idx
            self._coors[idx] = coor
            self._bots[idx] = set()
            self._tops[idx] = set()

        coor_set = set(coors)
        for idx, coor in enumerate(coors):
            for bottom in coor_bottoms(coor):
                if bottom in coor_set:
                    self._bots[idx].add(cubes[bottom])
            for top in coor_tops(coor):
                if top in coor_set:
                    self._tops[idx].add(cubes[top])

        for idx in self._coors:
            if self.isdroppable(idx):
                self.push(idx)

    def sibs(self, idx):
        for top_idx in self._tops[idx]:
            for sib_idx in self._bots[top_idx]:
                if sib_idx not in self._dropped:
                    yield sib_idx

    def bottom_count(self, idx):
        return len(self._bots[idx])

    def isdroppable(self, idx):
        return all(len(self._bots[top_idx]) > 1 for top_idx in self._tops[idx])

    def push(self, idx):
        if idx not in self._pushed:
            heapq.heappush(self._stables_min, idx)
            heapq.heappush(self._stables_max, -idx)
            self._pushed.add(idx)

    def unpush(self, idx):
        if idx in self._pushed:
            self._pushed.remove(idx)

    def drop(self, idx):
        if idx not in self._pushed:
            return False
       ...


Solve in Python:
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:

There are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\{-1, 0, 1\}$.

Anton can perform the following sequence of operations any number of times:  Choose any pair of indexes $(i, j)$ such that $1 \le i < j \le n$. It is possible to choose the same pair $(i, j)$ more than once.   Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.

For example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.

Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?

-----Input-----

Each test contains multiple test cases.

The first line contains the number of test cases $t$ ($1 \le t \le 10000$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$)  — the length of arrays.

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-1 \le a_i \le 1$)  — elements of array $a$. There can be duplicates among elements.

The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$)  — elements of array $b$. There can be duplicates among elements.

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.

-----Output-----

For each test case, output one line containing "YES" if it's possible to make arrays $a$ and $b$ equal by performing the described operations, or "NO" if it's impossible.

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

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

Output
YES
NO
YES
YES
NO

-----Note-----

In the first test-case we can choose $(i, j)=(2, 3)$...

import math

def main():
    was = set()
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    for i in range(n):
        if a[i] - b[i] > 0:
            if not -1 in was:
                print("NO")
                return
        elif a[i] - b[i] < 0:
            if not 1 in was:
                print("NO")
                return
        was.add(a[i])
    print("YES")

def __starting_point():
    t = int(input())
    for i in range(t):
        main()

__starting_point()


Solve in Python:
Once again, we have a lot of requests from coders for a challenging problem on geometry. Geometry expert Nitin is thinking about a problem with parabolas, icosahedrons, crescents and trapezoids, but for now, to encourage beginners, he chooses to work with circles and rectangles.
You are given two sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_N$. You should choose a permutation $P_1, P_2, \ldots, P_N$ of the integers $1$ through $N$ and construct $N$ rectangles with dimensions $A_1 \times B_{P_1}, A_2 \times B_{P_2}, \ldots, A_N \times B_{P_N}$. Then, for each of these rectangles, you should construct an inscribed circle, i.e. a circle with the maximum possible area that is completely contained in that rectangle.
Let $S$ be the sum of diameters of these $N$ circles. Your task is to find the maximum value of $S$.

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

-----Output-----
For each test case, print a single line containing one integer ― the maximum value of $S$. It is guaranteed that this value is always an integer.

-----Constraints-----
- $1 \le T \le 50$
- $1 \le N \le 10^4$
- $1 \le A_i, B_i \le 10^9$ for each valid $i$

-----Subtasks-----
Subtask #1 (20 points):
- $A_1 = A_2 = \ldots = A_N$
- $B_1 = B_2 = \ldots = B_N$
Subtask #2 (80 points): original constraints

-----Example Input-----
2
4
8 8 10 12
15 20 3 5
3
20 20 20
10 10 10

-----Example Output-----
30
30

-----Explanation-----
Example case 1: Four rectangles with dimensions $8 \times 3$, $8 \times 5$, $10 \times 20$ and $12 \times 15$ lead to an optimal answer.

for _ in range(int(input())):
 n=int(input())
 a=list(map(int,input().split()))
 b=list(map(int,input().split()))
 a.sort()
 b.sort()
 s=0
 for i,j in zip(a,b):
  s+=min(i,j)
 print(s)


Solve in Python:
Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_number
) and discovered that **more than 1** "kind of plural" may exist.

For example [Sursurunga Language](http://en.wikipedia.org/wiki/Sursurunga_language) distinguishes 5 types of numbers: **singular** (1 thing), **dual** (2 things), '**trial**' or '**lesser paucal**' (3 or 4), '**greater paucal**' (more than 4) and **plural** (many).

In this kata, you'll have to handle only four types of numbers:

- **singular**: 0 or 1 thing
- **dual**: 2 things
- **paucal**: 3 to 9 things
- **plural**: more than 9 things

To add some flavor the **number-marker** will not be added in same places:

- **singular**, no marker : `1 cat`
- **dual**, prefixed "`bu`" : `2 cats -> 2 bucat`
- **paucal**, suffixed "`zo`" : `4 cats -> 4 catzo`
- **plural**, "circumfixed `ga`" : `100 cats -> 100 gacatga`

As you all ("hawk eyes") have seen, the final `s` of english plural **disappears**.

( btw these markers, of course, have absolutely nothing to do with true sursurunga language, we're just talking about "**pig**-sursurunga" with **pig** as **pig** in "**pig latin**" )

## Your Job . . .
. . . if you accept it, will be to write a `sursurungal` function which get a `string` as argument and returns this string with words in it eventually converted to their "pig-sursurunga number type".

If a `number` ( *ie* 1 or more digit ) + a `space` + a `word` ( letters ) are found then the word should be converted.

**Each** group of `number+space+word` found in the string should be evaluated.

### Examples :

You may assume at least 1 `number+space+word` group will be provided.

**Beware** `s` of english plural should be removed, not ending `s` of some singular words ( *eg* "kiss" )

Good luck!

import re
def sursurungal(txt):
    def change(t1):
        a, b = t1.split()
        if int(a) <= 1: return t1
        if int(a) == 2:
            return "{} bu{}".format(a, b[:-1]) if b[-1] == 's' else "{} bu{}".format(a, b)
        if int(a) <= 9:
            return "{} {}zo".format(a, b[:-1]) if b[-1] == 's' else "{} {}zo".format(a, b)
        else:
            return "{} ga{}ga".format(a, b[:-1]) if b[-1] == 's' else "{} ga{}ga".format(a, b)

    lst = re.findall("[0-9]+\s[a-zA-Z]+[\n]?", txt)
    lst = [i[:-1] if i[-1:] == '\n' else i for i in lst]
    t = txt[:]
    for i in lst:
        t = re.sub(i, '~', t)
    lst2 = [change(i) for i in lst]
    for i in lst2:
        t = t.replace('~', i, 1)
    return t


Solve in Python:
Once upon a time, a king and a few of his soldiers were  caught by an enemy king in a war.

He puts them in a circle. The first man in the circle has to kill the second man, the third man has to kill the fourth, fifth man to kill the sixth and so on. When the circle is completed, the remaining people have to form a circle and the process has to repeat. The last man standing will be set free.

If the king has to be set free, which position must he take? For any given N number of people, write a program to find the position that the king has to take.

-----Input-----
Any positive integer in the range 1 to 10000.

-----Output-----
A positive integer indicating safest position

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

Output:
3

n=int(input())
arr=[]
for i in range(1,n+1):
 arr.append(i)
c=0
i=0
f=0;
while(c<n-1):
 if(arr[i%n]!=-1 and f):
  arr[i%n]=-1
  c=c+1
  f=0
 if(arr[i%n]!=-1):
  f=1
 i=i+1

for i in range(0,n):
 if(arr[i]!=-1):
  ans=arr[i]
  break;
print(ans)


Solve in Python:
Once you complete this kata, there is a [15x15 Version](http://www.codewars.com/kata/15x15-nonogram-solver) that you can try.
And once you complete that, you can do the [Multisize Version](https://www.codewars.com/kata/5a5519858803853691000069) which goes up to 50x50.

# Description

For this kata, you will be making a Nonogram solver. :)

If you don't know what Nonograms are, you can [look at some instructions](https://www.puzzle-nonograms.com/faq.php) and also [try out some Nonograms here.](https://www.puzzle-nonograms.com/)

For this kata, you will only have to solve 5x5 Nonograms. :)

# Instructions

You need to complete the Nonogram class and the solve method:
```python
class Nonogram:

    def __init__(self, clues):
        pass

    def solve(self):
        pass
```

You will be given the clues and you should return the solved puzzle. All the puzzles will be solveable so you will not need to worry about that.

```if:python
The clues will be a tuple of the horizontal clues, then the vertical clues, which will contain the individual clues. For example, for the Nonogram:
```

```if:java
The clues will be a three dimensional array of the horizontal clues, then the vertical clues, which will contain the individual clues. For example, for the Nonogram:
```

```
    |   |   | 1 |   |   |
    | 1 |   | 1 |   |   |
    | 1 | 4 | 1 | 3 | 1 |
-------------------------
  1 |   |   |   |   |   |
-------------------------
  2 |   |   |   |   |   |
-------------------------
  3 |   |   |   |   |   |
-------------------------
2 1 |   |   |   |   |   |
-------------------------
  4 |   |   |   |   |   |
-------------------------
```
The clues are on the top and the left of the puzzle, so in this case:
```if:python
The horizontal clues are: `((1, 1), (4,), (1, 1, 1), (3,), (1,))`, and the vertical clues are: `((1,), (2,), (3,), (2, 1), (4,))`. The horizontal clues are given from left to right. If there is more than one clue for the same column, the upper clue is given first. The vertical clues are given from top to...


Solve in Python:
Once, a genius guy Cristo visited NASA where he met many scientists. A young intern Mark at NASA asked Cristo to observe the strange behaviour of two

independent particles (say Alpha and Beta) moving in the free space.Cristo was astonished to see the movement of Alpha and Beta. However, he formulated a procedure

to evaluate the distance covered by the particles in given time.
The procedure calculates the distance covered by Alpha and Beta for a given time. Mark, however struggles

to evaluate the procedure manually and asks you to help him.
Cristo's Procedure :-
alpha = 0
beta = 0
Procedure CristoSutra( Ti ) :
if Ti <= 0 :
alpha = alpha + 1
else if Ti == 1 :
	beta = beta + 1
else :
CristoSutra(Ti-1)
	         CristoSutra(Ti-2)
	         CristoSutra(Ti-3)
end procedure
Note: Print the answer by taking mod from 109+7 .

-----Constraints:-----
- 1<=T<=105
- 1<=Ti<=105

-----Input Format:-----
First line consists an integer t, number of Test cases.For each test case, there is an integer denoting time Ti.

-----Output Format:-----
For each test case, a single output line contains two space seperated numbers ,distance covered by alpha and beta in the given time.

-----Subtasks:-----
Subtask 1 (30 points)
- 1<=T<=10
- 1<=Ti<=1000
Subtask 2 (70 points)
original contraints
Sample Input:
2
1
2
Sample Output:
0 1
2 1


Solve in Python:
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.

We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company.

To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer a_{i}, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.

The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.

Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2·10^5) — the number of workers of the Big Software Company.

Then n lines follow, describing the company employees. The i-th line contains two integers p_{i}, a_{i} (1 ≤ a_{i} ≤ 10^5) — the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p_1 =  - 1, for all other people the condition 1 ≤ p_{i} < i is fulfilled.

-----Output-----

Print a single integer — the maximum possible efficiency of the workgroup.

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

Output
17

-----Note-----

In the...

n = int(input())
t = [list(map(int, input().split())) for q in range(n)]
n += 1
u = [-1e7] * n
v = [0] * n
for i, (j, a) in list(enumerate(t, 1))[::-1]:
    u[i] = max(u[i], v[i] + a)
    v[j], u[j] = max(v[j] + v[i], u[j] + u[i]), max(v[j] + u[i], u[j] + v[i])
print(u[1])


Solve in Python:
One day Chef was playing with numbers. He loves Lowest Common Multiple (LCM) too much and he is a very curious guy. He always try to do new things. Now he want to make a large number with it. But he doesn't want to take too many numbers.

He is willing to take only three numbers less than or equal to N (not necessarily distinct ) and from those three number he want get the maximum number by taking LCM of the numbers.

As he is busy in playing some more tricks of maths, he assign this task to you.

-----Input-----
First line of input contains an integer t ( t<=1000 ), Number of test cases.

t line follows an integer N

-----Output-----
Print t lines contains a single integer — the maximum possible LCM of three not necessarily distinct positive integers that are not greater than N.

-----Constraints-----
1<= N <= 10^6

-----Example-----
Input:
2
9
7

Output:
504
210

-----Explanation-----
Example case 2. For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7•6•5 = 210. It is the maximum value we can get.

from fractions import gcd
for testCases in range(eval(input())):
 n = eval(input())
 if n == 1:
  print('1')
 elif n == 2:
  print('2')
 elif n == 3:
  print('6')
 else:
  c = n*(n-1)
  k = n - 2
  while True:
   if gcd(k,n-1) == 1 and gcd(k,n) == 1:
    break
   k -= 1
  d = (n-1)*(n - 2)
  k1 = n - 3
  while True:
   if gcd(k1,n-1) == 1 and gcd(k1,n-2) == 1:
    break
   k1 -= 1
  print(max(c*k,d*k1))


Solve in Python:
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play a_{i} rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?

-----Input-----

The first line contains integer n (3 ≤ n ≤ 10^5). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the i-th number in the list is the number of rounds the i-th person wants to play.

-----Output-----

In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least a_{i} rounds.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
4

Input
4
2 2 2 2

Output
3

-----Note-----

You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).

n = int(input())
a = list(map(int, input().split()))
ans = (sum(a) // (n - 1)) + int(sum(a) % (n - 1) != 0)
print(max(max(a), ans))


Solve in Python:
One day, Chef found a cube which has each of its sides painted in some color out of black, blue, red, green, yellow and orange.
Now he asks you to check if he can choose three sides such that they are pairwise adjacent and painted in the same color.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases.
- A single line of each test case contains six words denoting the colors of painted sides in the order: front, back, left, right, top and bottom, respectively.

-----Output-----
For each test case, output a single line containing the word "YES" or "NO" (without quotes) corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ T ≤  50000
- Each color will be from the list {"black", "blue", "red", "green", "yellow", "orange"}

-----Subtasks-----
Subtask 1: (25 points)
- 1 ≤ T ≤  12000
- For each test case there will be at most three different colors

Subtask 2: (75 points)
- Original constraints

-----Example-----
Input:
2
blue yellow green orange black green
green yellow green orange black green

Output:
NO
YES

-----Explanation-----

Example case 1.
There are no three sides with the same color.

Example case 2.
In this test case, the front, bottom and left sides are green (see picture).

import math
import sys

def _int():
 return int(sys.stdin.readline())

def _ints():
 return list(map(int, sys.stdin.readline().split()))

def _intarr():
 return list(map(int, sys.stdin.readline().split()))

def _str():
 return sys.stdin.readline()

def _strarr():
 return sys.stdin.readline().split()

def adj(a, b, c):
 if b != opp[a] and b != opp[c] and a != opp[c]:
  return True
 return False

t = _int()

opp = [1, 0, 3, 2, 5, 4]

for _ in range(t):
 c = _strarr()
 cd = dict()
 for i in range(len(opp)):
  ind = cd.get(c[i], [])
  ind.append(i)
  cd[c[i]] = ind

 #print(cd)

 found = False
 for k in list(cd.keys()):
  ind = cd.get(k, [])
  if len(ind) == 3:
   if adj(ind[0], ind[1], ind[2]):
     found = True
  elif len(ind) == 4:
   if adj(ind[0], ind[1], ind[2]):
    found = True
   elif adj(ind[0], ind[1], ind[3]):
    found = True
   elif adj(ind[0], ind[2], ind[3]):
    found = True
   elif adj(ind[1], ind[2], ind[3]):
    found = True
  elif len(ind) >= 5:
   found = True
  if found:
   break
 print("YES" if found else "NO")


Solve in Python:
One day, Chef prepared D brand new dishes. He named the i-th dish by a string Si. After the cooking, he decided to categorize each of these D dishes as special or not.

A dish Si is called special if it's name (i.e. the string Si) can be represented in the form of a double string by removing at most one (possibly zero) character from it's name from any position.

A string is called a double string if it can be represented as a concatenation of two identical, non-empty strings.
e.g. "abab" is a double string as it can be represented as "ab" + "ab" where + operation denotes concatenation.
Similarly, "aa", "abcabc" are double strings whereas "a", "abba", "abc" are not.

-----Input-----
- First line of the input contains an integer D denoting the number of dishes prepared by Chef on that day.
- Each of the next D lines will contain description of a dish.

- The i-th line contains the name of i-th dish Si.

-----Output-----
For each of the D dishes, print a single line containing "YES" or "NO" (without quotes) denoting whether the dish can be called as a special or not.

-----Constraints-----
- 1 ≤ D ≤ 106
- 1 ≤ |Si| ≤ 106.
- Each character of string Si will be lower case English alphabet (i.e. from 'a' to 'z').

-----Subtasks-----
Subtask #1 : (20 points)
- Sum of |Si| in an input file doesn't exceed 2 * 103

Subtask 2 : (80 points)
- Sum of |Si| in an input file doesn't exceed 2 * 106

-----Example-----
Input:
3
aba
abac
abcd

Output:
YES
NO
NO

-----Explanation-----
Example case 1.
We can remove the character at position 1 (0-based index) to get "aa" which is a double string. Hence, it is a special dish.

Example case 2.
It is not possible to remove the character at any of the position to get the double string. Hence, it is not a special dish.

t = int(input())
for i in range(t):
 s = input()
 if len(s)==0:
  print("NO")
 else:
  if len(s)%2==0:
   flag = False
   half = int(len(s)/2)
   if s[0:half]== s[half:len(s)]:
    flag=True
   else:
    pass
  else:
   flag = False
   for j in range(len(s)):
    news = s[0:j]+s[j+1:len(s)]
    if len(news) == 0:
     flag = False
     break
    if len(news) % 2 == 0:
     half = int(len(news) / 2)
     if news[0:half] == news[half:len(news)]:
      flag = True
      break
     else:
      continue
  if flag:
   print("YES")
  else:
   print("NO")


Solve in Python:
One day, Delta, the dog, got very angry. He has $N$ items with different values, and he decided to destroy a few of them. However, Delta loves his hooman as well. So he only destroyed those items whose Least Significant Bit in binary representation is 0.
Can you help Delta to find the total damage he did so he could make an equally sorry face?

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of Each test case a single integer $N$.
- Next line contains $N$ integers denoting values of items.

-----Output:-----
For each testcase, output in a single line the total damage caused by Delta.

-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^3$
- $1 \leq value \leq 10^3$

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

1 2 3 4 5

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

-----EXPLANATION:-----
Total Damage: $2  + 4 = 6$.

for _ in range(int(input())):
    n=int(input())
    li=list(map(int,input().split()))
    s=0
    for item in li:
        if item%2==0:
            s+=item
    print(s)


Solve in Python:
One day, Tanya was studying graph theory. She is very inquisitive, so the following problem soon came to her mind.
Find the number of undirected unweighted connected simple graphs with $N$ vertices (numbered $1$ through $N$) and $M$ edges, such that for each $i$ ($2 \le i \le N$), the shortest path from vertex $1$ to vertex $i$ is unique and its length is equal to $A_i$. In other words, for each $i$ ($2 \le i \le N$), there should be exactly one path with length $A_i$ between vertices $1$ and $i$, and there should be no paths with smaller length between these vertices.
Two graphs with $N$ vertices are distinct if we can find two vertices $u$ and $v$ such that there is an edge between these vertices in one graph, but not in the other graph.
Since the answer could be very large, compute it modulo $1,000,000,007$ ($10^9 + 7$).

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

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

-----Constraints-----
- $1 \le T \le 1,000$
- $2 \le N \le 10^5$
- $N-1 \le M \le \mathrm{min}\left(2\cdot 10^5, \frac{N(N-1)}{2}\right)$
- $1 \le A_i \le N-1$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$
- the sum of $M$ over all test cases does not exceed $2 \cdot 10^5$

-----Subtasks-----
Subtask #1 (50 points): $M = N-1$
Subtask #2 (50 points): original constraints

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

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

-----Explanation-----
Example case 1: The two graphs which satisfy all conditions are:

mod=pow(10,9)+7
for tt in range(int(input())):
 n,m=list(map(int,input().split()))
 l=list(map(int,input().split()))

 d=[0 for i in range(n+1)]
 for i in l:
  d[i]+=1
 ans=1
 for i in range(2,n+1):
  ans*=pow(d[i-1],d[i])
  ans%=mod
 print(ans%mod)


Solve in Python:
One of Chef's friends offered him a deal: during $D$ days, they are going to exchange money. For each $i$ ($1 \le i \le D$), on the $i$-th day, Chef's friend would give Chef $A$ rupees, while Chef would give his friend $2^{i-1}$ rupees ($1$ rupee on day $1$, $2$ rupees on day $2$, $4$ rupees on day $3$, and so on). Chef's profit from the deal is the total number of rupees he received from his friend minus the total number of rupees he gave his friend.
Chef decided to ask for your advice before accepting the deal. You want to help him by telling him two numbers $D_1$ and $D_2$, where $D_1$ is the maximum value of $D$ such that Chef should accept the deal, i.e. his profit from the deal is positive if $D = D_1$, and $D_2$ is the value of $D$ that leads to the maximum possible profit for Chef. If there are multiple values of $D$ that lead to the maximum profit, $D_2$ is the smallest of these values.

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

-----Output-----
For each test case, print a single line containing two space-separated integers $D_1$ and $D_2$.

-----Constraints-----
- $1 \le T \le 100,000$
- $5 \le A \le 10^9$

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

-----Example Input-----
4
5
8
9
1000000000

-----Example Output-----
4 3
5 3
5 4
35 30

for _ in range(int(input())):
 a=int(input())
 s=1
 s1=a
 p=a-s
 d=1
 b=[]
 for i in range(2,100):
  if p<=0:
   d=i-2
   break
  else:
   b.append(p)
   s+=pow(2,i-1)
   a+=s1
   p=a-s
 print(d,b.index(max(b))+1)


Solve in Python:
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.

Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.

Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length [Image] The picture corresponds to the first example

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 5·10^5) — the number of rectangles.

n lines follow. The i-th of these lines contains four integers x_1, y_1, x_2 and y_2 ( - 10^9 ≤ x_1 < x_2 ≤ 10^9,  - 10^9 ≤ y_1 < y_2 ≤ 10^9), that means that points (x_1, y_1) and (x_2, y_2) are the coordinates of two opposite corners of the i-th rectangle.

It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.

-----Output-----

Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.

Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer c_{i} (1 ≤ c_{i} ≤ 4) — the color of i-th rectangle.

-----Example-----
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1

Output
YES
1
2
2
3
2
2
4
1

n = int(input())
print('YES')
for _ in range(n):
    x, y, *z = list(map(int, input().split()))
    print((x & 1) * 2 + (y & 1) + 1)


Solve in Python:
One of the first algorithm used for approximating the integer square root of a positive integer `n` is known as "Hero's method",
named after the first-century Greek mathematician Hero of Alexandria who gave the first description
of the method. Hero's method can be obtained from Newton's method which came 16 centuries after.

We approximate the square root of a number `n` by taking an initial guess `x`, an error `e` and repeatedly calculating a new approximate *integer* value `x` using: `(x + n / x) / 2`; we are finished when the previous `x` and the `new x` have an absolute difference less than `e`.

We supply to a function (int_rac) a number `n` (positive integer) and a parameter `guess` (positive integer) which will be our initial `x`. For this kata the parameter 'e' is set to `1`.

Hero's algorithm is not always going to come to an exactly correct result! For instance: if n = 25 we get 5 but for n = 26 we also get 5. Nevertheless `5` is the *integer* square root of `26`.

The kata is to return the count of the progression of integer approximations that the algorithm makes.

Reference:

Some examples:
```
int_rac(25,1): follows a progression of [1,13,7,5] so our function should return 4.

int_rac(125348,300): has a progression of [300,358,354] so our function should return 3.

int_rac(125348981764,356243): has a progression of [356243,354053,354046] so our function should return 3.
```

#

You can use Math.floor (or similar) for each integer approximation.

#

Note for JavaScript, Coffescript, Typescript:

Don't use the double bitwise NOT ~~ at each iteration if you want to have the same results as in the tests and the other languages.

def int_rac(n, guess):
    cnt = 0

    while True:
        cnt += 1
        next_guess = (guess + n // guess) // 2

        if next_guess == guess:
            return cnt

        guess = next_guess


Solve in Python:
One of the first chain emails I ever received was about a supposed Cambridge  University study that suggests your brain can read words no matter what order the letters are in, as long as the first and last letters of each word are correct.

Your task is to **create a function that can take any string and randomly jumble the letters within each word while leaving the first and last letters of the word in place.**

For example,

    mixwords('Winter is coming') // returns 'Wntier is cminog' or 'Wtiner is conimg'
    mixwords('Hey, friends!') // returns 'Hey, fierdns!' or 'Hey, fernids!'

* All punctuation should remain in place
* Words smaller than 3 letters should not change
* Letters must be randomly moved (and so calling the function multiple times with the same string should return different values
* Parameters that are not strings should return undefined

The tests do the following things to ensure a valid string is returned:

1. Check that the string returned is not equal to the string passed (you may have to revalidate the solution if your function randomly returns the same string)
2. Check that first and last letters of words remain in place
3. Check that punctuation remains in place
4. Checks string length remains the same
5. Checks the function returns `undefined` for non-strings
6. Checks that word interiors (the letters between the first and last) maintain the same letters, albeit in a different order
7. Checks that letters are randomly assigned.

import re
from random import sample

def mix_words(string):
    return re.sub(
        r'(?<=[a-zA-Z])([a-zA-Z]{2,})(?=[a-zA-Z])',
        lambda match: ''.join(sample(match.group(1), len(match.group(1)))),
        string)


Solve in Python:
One of the services provided by an operating system is memory management. The OS typically provides an API for allocating and releasing memory in a process's address space. A process should only read and write memory at addresses which have been allocated by the operating system. In this kata you will implement a simulation of a simple memory manager.

The language you will be using has no low level memory API, so for our simulation we will simply use an array as the process address space. The memory manager constructor will accept an array (further referred to as `memory`) where blocks of indices will be allocated later.

___

# Memory Manager Contract

## allocate(size)

`allocate` reserves a sequential block (sub-array) of `size` received as an argument in `memory`. It should return the index of the first element in the allocated block, or throw an exception if there is no block big enough to satisfy the requirements.

## release(pointer)

`release` accepts an integer representing the start of the block allocated ealier, and frees that block. If the released block is adjacent to a free block, they should be merged into a larger free block. Releasing an unallocated block should cause an exception.

## write(pointer, value)

To support testing this simulation our memory manager needs to support read/write functionality. Only elements within allocated blocks may be written to. The `write` method accepts an index in `memory` and a `value`. The `value` should be stored in `memory` at that index if it lies within an allocated block, or throw an exception otherwise.

## read(pointer)

This method is the counterpart to `write`. Only indices within allocated blocks may be read. The `read` method accepts an index. If the `index` is within an allocated block, the value stored in `memory` at that index should be returned, or an exception should be thrown otherwise.

class MemoryManager:
    def __init__(self, memory):
        """
        @constructor Creates a new memory manager for the provided array.
        @param {memory} An array to use as the backing memory.
        """
        self.memory = memory
        self.allocated = {}
        self.free_memory = {0:len(memory)}

    def allocate(self, size):
        """
        Allocates a block of memory of requested size.
        @param {number} size - The size of the block to allocate.
        @returns {number} A pointer which is the index of the first location in the allocated block.
        @raises If it is not possible to allocate a block of the requested size.
        """
        if size > len(self.memory):
            raise 'Cannot allocate more memory than exists'
        for pointer, block_size in list(self.free_memory.items()):
            if block_size >= size:
                self.allocated[pointer] = size
                self.free_memory[pointer+size]= block_size-size
                del self.free_memory[pointer]
                return pointer
        raise 'Cannot allocate more memory than available'

    def release(self, pointer):
        """
        Releases a previously allocated block of memory.
        @param {number} pointer - The pointer to the block to release.
        @raises If the pointer does not point to an allocated block.
        """
        self.free_memory[pointer] = self.allocated[pointer]
        del self.allocated[pointer]
        for p, b_size in sorted(self.free_memory.items()):
            if self.free_memory.get(p+b_size):
                self.free_memory[p] += self.free_memory[p+b_size]
                del self.free_memory[p+b_size]

    def read(self, pointer):
        """
        Reads the value at the location identified by pointer
        @param {number} pointer - The location to read.
        @returns {number} The value at that location.
        @raises If pointer is in unallocated memory.
        """
        for p, b_size in list(self.allocated.items()):
            if p <=...


Solve in Python:
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.

A positive integer $a$ is initially on the screen. The player can put a coin into the machine and then add $1$ to or subtract $1$ from any two adjacent digits. All digits must remain from $0$ to $9$ after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add $1$ to $9$, to subtract $1$ from $0$ and to subtract $1$ from the leading $1$. Once the number on the screen becomes equal to $b$, the player wins the jackpot. $a$ and $b$ have the same number of digits.

Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^5$) standing for the length of numbers $a$ and $b$.

The next two lines contain numbers $a$ and $b$, each one on a separate line ($10^{n-1} \le a, b < 10^n$).

-----Output-----

If it is impossible to win the jackpot, print a single integer $-1$.

Otherwise, the first line must contain the minimal possible number $c$ of coins the player has to spend.

$\min(c, 10^5)$ lines should follow, $i$-th of them containing two integers $d_i$ and $s_i$ ($1\le d_i\le n - 1$, $s_i = \pm 1$) denoting that on the $i$-th step the player should add $s_i$ to the $d_i$-th and $(d_i + 1)$-st digits from the left (e. g. $d_i = 1$ means that two leading digits change while $d_i = n - 1$ means that there are two trailing digits which change).

Please notice that the answer may be very big and in case $c > 10^5$ you should print only the first $10^5$ moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.

-----Examples-----
Input
3
223
322

Output
2
1 1
2 -1

Input
2
20
42

Output
2
1 1
1 1

Input
2
35
44

Output
-1

-----Note-----

In the...

def main():
    n = int(input())
    a = list(map(int, (x for x in input())))
    b = list(map(int, (x for x in input())))
    x = [0] * (n - 1)
    x[0] = b[0] - a[0]
    for i in range(1, n - 1):
        x[i] = b[i] - a[i] - x[i - 1]
    if a[n - 1] + x[n - 2] != b[n - 1]:
        print(-1)
        return
    cnt = sum(map(abs, x))  # prevbug: ftl
    print(cnt)
    cnt = min(cnt, 10 ** 5)
    index = 0

    def handle_zero_nine(cur_zero):
        nonlocal cnt
        nxt = index + 1
        # cur_zero = True prevbug: preserved this line
        while True:
            if cur_zero and a[nxt + 1] != 9:
                break
            if not cur_zero and a[nxt + 1] != 0:
                break
            nxt += 1
            cur_zero = not cur_zero
        while nxt > index:
            if cnt == 0:
                break
            if cur_zero:
                print(nxt + 1, 1)
                a[nxt] += 1
                a[nxt + 1] += 1
            else:
                print(nxt + 1, -1)
                a[nxt] -= 1
                a[nxt + 1] -= 1
            nxt -= 1
            cnt -= 1
            # print(a)
            cur_zero = not cur_zero

    while cnt > 0:
        if a[index] == b[index]:
            index += 1
            continue
        elif a[index] > b[index] and a[index + 1] == 0:
            handle_zero_nine(True)
        elif a[index] < b[index] and a[index + 1] == 9:
            handle_zero_nine(False)
        elif a[index] > b[index]:
            print(index + 1, -1)
            a[index] -= 1
            a[index + 1] -= 1
            cnt -= 1
            # print(a)
        elif a[index] < b[index]:
            print(index + 1, 1)
            a[index] += 1
            a[index + 1] += 1
            cnt -= 1
            # print(a)

def __starting_point():
    main()

__starting_point()


Solve in Python:
One suggestion to build a satisfactory password is to start with a memorable phrase or sentence and make a password by extracting the first letter of each word.

Even better is to replace some of those letters with numbers (e.g., the letter `O` can be replaced with the number `0`):

* instead of including `i` or `I` put the number `1` in the password;
* instead of including `o` or `O` put the number `0` in the password;
* instead of including `s` or `S` put the number `5` in the password.

## Examples:
```
"Give me liberty or give me death"  --> "Gml0gmd"
"Keep Calm and Carry On"            --> "KCaC0"
```

def make_password(phrase):

  return ''.join(w[0] for w in phrase.split()).translate(str.maketrans('iIoOsS', '110055'))


Solve in Python:
One upon a time there were three best friends Abhinav, Harsh, and Akash decided to form a
team and take part in ICPC from KIIT. Participants are usually offered several problems during
the programming contest. Long before the start, the friends decided that they will implement a
problem if at least two of them are sure about the solution. Otherwise, friends won't write the
problem's solution.
This contest offers $N$ problems to the participants. For each problem we know, which friend is
sure about the solution. Help the KIITians find the number of problems for which they will write a
solution.
Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the
line equals 1, then Abhinav is sure about the problem's solution, otherwise, he isn't sure. The
second number shows Harsh's view on the solution, the third number shows Akash's view. The
numbers on the lines are

-----Input:-----
- A single integer will contain $N$, number of problems.

-----Output:-----
Print a single integer — the number of problems the friends will implement on the contest.

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

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

1 1 0

1 1 1

1 0 0

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

-----EXPLANATION:-----
In the first sample, Abhinav and Harsh are sure that they know how to solve the first problem
and all three of them know how to solve the second problem. That means that they will write
solutions for these problems. Only Abhinav is sure about the solution for the third problem, but
that isn't enough, so the group won't take it.

# cook your dish here
c = 0
for _ in range(int(input())):
 s = input()
 if s.count('1') >= 2:
  c = c + 1
print(c)


Solve in Python:
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.

     _9_
    /   \
   3     2
  / \   / \
 4   1  #  6
/ \ / \   / \
# # # #   # #

For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character '#' representing null pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".

Example 1:

Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true

Example 2:

Input: "1,#"
Output: false

Example 3:

Input: "9,#,#,1"
Output: false

class Solution:
     def isValidSerialization(self, preorder):
         """
         :type preorder: str
         :rtype: bool
         """
         preorder, first = preorder.split(","), preorder.split(",")
         def backward(index):
             if index >= len(preorder) or index < 0: return
             if index+1<len(preorder) and preorder[index+1] == preorder[index] == "#" and index-1 >= 0 and preorder[index-1] != "#":
                 preorder.pop(index)
                 preorder.pop(index)
                 preorder[index-1] = "#"
                 backward(index-2)
             else: backward(index+1)
         backward(0)
         return True if (preorder != first and preorder == ["#"]) or (preorder == first == ["#"]) else False


Solve in Python:
Our AAA company is in need of some software to help with logistics: you will be given the width and height of a map, a list of x coordinates and a list of y coordinates of the supply points, starting to count from the top left corner of the map as 0.

Your goal is to return a two dimensional array/list with every item having the value of the distance of the square itself from the closest supply point expressed as a simple integer.

Quick examples:

```python
logistic_map(3,3,[0],[0])
#returns
#[[0,1,2],
# [1,2,3],
# [2,3,4]]
logistic_map(5,2,[0,4],[0,0])
#returns
#[[0,1,2,1,0],
# [1,2,3,2,1]]
```

Remember that our company is operating with trucks, not drones, so you can simply use Manhattan distance. If supply points are present, they are going to be within the boundaries of the map; if no supply point is present on the map, just return `None`/`nil`/`null` in every cell.

```python
logistic_map(2,2,[],[])
#returns
#[[None,None],
# [None,None]]
```

**Note:** this one is taken (and a bit complicated) from a problem a real world AAA company [whose name I won't tell here] used in their interview. It was done by a friend of mine. It is nothing that difficult and I assume it is their own version of the FizzBuzz problem, but consider candidates were given about 30 mins to solve it.

def logistic_map(width,height,xs,ys):
    return [ [ min([abs(x-x2)+abs(y-ys[i]) for (i,x2) in enumerate(xs)]) if len(xs) else None for x in range(width) ] for y in range(height) ]


Solve in Python:
Our Chef is doing what he is best at, COOKING A BARBECUE for his guests. He has invited all of us, and taking the help of his apprentice to smoke the barbecues. The chef has got BBQ sticks, each can take N fillings, and he presents N distinctly filled sticks in front his guests forming a N*N  matrix

But here is the problem, he has got only two type of fillings, meat and capsicum, but still wants the N  sticks to look "presentable", he is very particular about it. As a solution he fills the main diagonal of the N*N  matrix with the same type of filling (either meat or capsicum) forming a "presentable" set

The Chef's apprentice is a fool, so the Chef asks him to cook M distinctly filled sticks ,so that the Chef is sure that among M there exist N sticks forming a "presentable" set. Your job is to determine smallest possible value of M.

-----Input-----
T, the number of test cases, followed by T lines.
Each line containing the positive integer N >= 4

-----Output-----
T lines of output, each line contain the positive integer M

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

Output:
5

#!/usr/bin/python
t = int(input())
while t :
 n= int(input())
 k =(2**(n-2))+1
 print(k)
 t = t-1


Solve in Python:
Our Chef who was a renouned mathematician has recently got into diamonds' business.
She has accidentally misplaced $Q$ diamonds into a jar which already had $N$ chocolates. She then started wondering about an interesting question as following.
If we pick items one by one at random without replacement, what would be the expected number of picks required to get all diamonds out.

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

-----Output:-----
For each testcase, output the answer in a single line. Your answer is considered if its absolute or relative error doesn't exceed $10^{-6}$

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

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

-----Sample Output:-----
3.3333333333

-----EXPLANATION:-----
Here there are 2 Diamonds, 2 chocolates in the jar.
Say C is chocolate, D is diamond.
If the random order of picking them from left to right is "CDDC", after 3 picks (CDD) all diamonds are out.
Similarly, for the remaining orders it would be the following:
"CDCD" => 4
"CCDD" => 4
"DDCC" => 2
"DCDC" => 3
"DCCD" => 4
Hence the expected number of picks would be (3+4+4+2+3+4)/6 = 3.333333

from itertools import permutations
for _ in range(int(input())):
 pick=0
 n,q=map(int,input().split(' '))
 print(round((q*(n+q+1)/(q+1)),10))