Solve in Python:
There is a popular apps named “Exbook” like “Facebook”. To sign up in this app , You have to make a strong password with more than 3 digits and less than 10 digits . But I am a pro hacker and so I make a Exbook hacking site . You need to login in this site to hack exbook account and then you will get a portal. You can give any user exbook login link using this site and when anyone login into exbook using your link ,you can see his/her password .
But I made a mistake and so you cannot find original password in your portal . The portal showing you by adding two in every digit . So , now you have to find out the original password of an user if I give you the password which is showing in your portal .

-----Input:-----
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains a single integer n which is showing in your portal . Mind it , every digit of n is greater than one .

-----Output:-----
Print , original password of user .

-----Sample Input:-----
2
3527
47269

-----Sample Output:-----
1305
25047

# cook your dish here
for _ in range(int(input())):
    s=input()
    for i in s:
        print(int(i)-2,end="")
    print("")


Solve in Python:
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!

### input
```if-not:c
* customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* n: a positive integer, the number of checkout tills.
```
```if:c
* customers: a pointer to an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* customers_length: the length of the array that `customers` points to.
* n: a positive integer, the number of checkout tills.
```

### output
The function should return an integer, the total time required.

-------------------------------------------

## Important
**Please look at the examples and clarifications below, to ensure you understand the task correctly :)**

-------

### Examples

```python
queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times

queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the
# queue finish before the 1st person has finished.

queue_time([2,3,10], 2)
# should return 12
```

### Clarifications

 * There is only ONE queue serving many tills, and
 * The order of the queue NEVER changes, and
 * The front person in the queue (i.e. the first element in the array/list) proceeds to a till as soon as it becomes free.

N.B. You should assume that all the test input will be valid, as specified above.

P.S. The situation in this kata can be likened to the more-computer-science-related idea of a thread pool, with relation to running multiple processes at the same time: https://en.wikipedia.org/wiki/Thread_pool

def queue_time(customers, n):
    tills = [0 for i in range(n)]

    for time in customers:
        min_index = tills.index(min(tills))
        tills[min_index] += time

    return max(tills)


Solve in Python:
There is a rectangular grid of cells consisting of n rows and m columns.
You will place a robot on one of the grid cells and provide it with a command string s, consisting of characters ‘L’, ‘R’, ‘U’, ‘D’.
After being placed, the robot will follow the instructions of the command string, where 'L' corresponds moving to the left, 'R' towards the right, 'U' for moving up, and 'D' means down.

You have already selected the command string s, and are wondering if it is possible to place the robot in one of the grid cells initially and have it always stay entirely within the grid upon execution of the command string s.
Output “safe” if there is a starting cell for which the robot doesn’t fall off the grid on following command s, otherwise, output "unsafe".

-----Input-----

The first line of input will contain an integer T, the number of test cases.

Each test case will be on two lines.

The first line will have two space separated integers n,m.

The second line will have the command string s.

-----Output-----

For each test case, output "safe" (without quotes) or "unsafe" (without quotes) in a new line.

-----Constraints-----
-  1 ≤ T ≤ 1,000
-  1 ≤ n,m ≤ 10
-  1 ≤ |s| ≤ 10

-----Example-----
Input:
5
1 1
R
2 3
LLRU
3 2
LLRU
4 3
ULURUDRDLD
3 6
RURUR

Output:
unsafe
safe
unsafe
safe
safe

-----Explanation-----

For the first case, there is only one grid square, so we must place our robot there. When the robot follows the command, it'll fall off, so it is unsafe.

For the second case, we can place the robot on the bottom right grid square. Here is an image denoting the moves that the robot will make.

import math
t=int(input())
for test in range(t):
 n,m=list(map(int,input().split()))
 up=0
 down=0
 left=0
 right=0
 s=input()
 f=0
 for i in s:
  if i=="L":
   left+=1
   if right>0:
    right-=1
   if left==m:
    break
  if i=="R":
   right+=1
   if left>0:
    left-=1
   if right==m:
    break
  if i=="U":
   up+=1
   if down>0:
    down-=1
   if up==n:
    break
  if i=="D":
   down+=1
   if up>0:
    up-=1
   if down==n:
    break
 if abs(down)<n and abs(up)<n and abs(left)<m and abs(right)<m:
  print("safe")
 else:
  print("unsafe")


Solve in Python:
There is a rectangular grid of size $n \times m$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $(i, j)$ is $c_{i, j}$. You are also given a map of directions: for each cell, there is a direction $s_{i, j}$ which is one of the four characters 'U', 'R', 'D' and 'L'.

  If $s_{i, j}$ is 'U' then there is a transition from the cell $(i, j)$ to the cell $(i - 1, j)$;  if $s_{i, j}$ is 'R' then there is a transition from the cell $(i, j)$ to the cell $(i, j + 1)$;  if $s_{i, j}$ is 'D' then there is a transition from the cell $(i, j)$ to the cell $(i + 1, j)$;  if $s_{i, j}$ is 'L' then there is a transition from the cell $(i, j)$ to the cell $(i, j - 1)$.

It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.

You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied.

  Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction.  Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells $(1, 1)$ and $(1, 2)$, but if the grid is "RLL" then you cannot place robots in cells $(1, 1)$ and $(1, 3)$ because during the first second both robots will occupy the cell $(1, 2)$.

The robots make an infinite number of moves.

Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all...

import sys
from collections import deque
input = sys.stdin.readline

t = int(input())
for _ in range(t):
    n, m = map(int, input().split())
    s = [input() for i in range(n)]
    grid = [input() for i in range(n)]
    robot_cnt = 0
    black_cnt = 0

    graph = [-1] * (n * m)
    rev_graph = [[] for i in range(n * m)]
    for i in range(n):
        for j in range(m):
            if grid[i][j] == "U":
                graph[i * m + j] = (i - 1) * m + j
                rev_graph[(i - 1) * m + j].append(i * m + j)
            elif grid[i][j] == "R":
                graph[i * m + j] = i * m + (j + 1)
                rev_graph[i * m + (j + 1)].append(i * m + j)
            elif grid[i][j] == "D":
                graph[i * m + j] = (i + 1) * m + j
                rev_graph[(i + 1) * m + j].append(i * m + j)
            elif grid[i][j] == "L":
                graph[i * m + j] = i * m + (j - 1)
                rev_graph[i * m + (j - 1)].append(i * m + j)

    is_start = [True] * (n * m)
    for i in graph:
        is_start[i] = False

    is_cycle = [False] * (n * m)
    period = [0] * (n * m)
    for i in range(n * m):
        if not is_start[i]:
            continue
        st = i
        period[i] = 1
        while True:
            nxt_i = graph[i]
            if period[nxt_i] < 0:
                tmp = period[nxt_i]
                break
            if period[nxt_i] > 0:
                tmp = -(period[i] - period[nxt_i] + 1)
                is_cycle[nxt_i] = True
                break
            period[graph[i]] = period[i] + 1
            i = graph[i]
        i = st
        period[i] = tmp
        while True:
            nxt_i = graph[i]
            if period[nxt_i] < 0:
                break
            period[graph[i]] = tmp
            i = graph[i]

    # cycle without side road
    for i in range(n * m):
        if period[i] == 0:
            robot_cnt += 1
            if s[i // m][i % m] == "0":
                black_cnt += 1

    # cycle with road
    for i in range(n * m):
      ...


Solve in Python:
There is a road with length $l$ meters. The start of the road has coordinate $0$, the end of the road has coordinate $l$.

There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.

Initially, they will drive with a speed of $1$ meter per second. There are $n$ flags at different coordinates $a_1, a_2, \ldots, a_n$. Each time when any of two cars drives through a flag, the speed of that car increases by $1$ meter per second.

Find how long will it take for cars to meet (to reach the same coordinate).

-----Input-----

The first line contains one integer $t$ ($1 \leq t \leq 10^4$): the number of test cases.

The first line of each test case contains two integers $n$, $l$ ($1 \leq n \leq 10^5$, $1 \leq l \leq 10^9$): the number of flags and the length of the road.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ in the increasing order ($1 \leq a_1 < a_2 < \ldots < a_n < l$).

It is guaranteed that the sum of $n$ among all test cases does not exceed $10^5$.

-----Output-----

For each test case print a single real number: the time required for cars to meet.

Your answer will be considered correct, if its absolute or relative error does not exceed $10^{-6}$. More formally, if your answer is $a$ and jury's answer is $b$, your answer will be considered correct if $\frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}$.

-----Example-----
Input
5
2 10
1 9
1 10
1
5 7
1 2 3 4 6
2 1000000000
413470354 982876160
9 478
1 10 25 33 239 445 453 468 477

Output
3.000000000000000
3.666666666666667
2.047619047619048
329737645.750000000000000
53.700000000000000

-----Note-----

In the first test case cars will meet in the coordinate $5$.

The first car will be in the coordinate $1$ in $1$ second and after that its speed will increase by $1$ and will be equal to $2$ meters per second. After $2$ more seconds it will be in the...

import sys
input = sys.stdin.readline

from bisect import bisect_right

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

	c1 = []
	speed = 1
	x = 0
	t = 0.
	for a in A:
		t += (a-x)/speed
		c1.append(t)
		speed += 1
		x = a

	c2 = []
	speed = 1
	x = l
	t = 0.
	for a in reversed(A):
		t += (x-a)/speed
		c2.append(t)
		speed += 1
		x = a

	lo = 0.
	hi = float(l)

	while hi - lo > 1e-7:
		m = (lo + hi) / 2

		i1 = bisect_right(c1, m)-1
		if i1 == -1:
			x1 = m
		else:
			tpass = c1[i1]
			textra = m - tpass
			x1 = A[i1] + textra * (i1+2)

		i2 = bisect_right(c2, m)-1
		if i2 == -1:
			x2 = l-m
		else:
			tpass = c2[i2]
			textra = m - tpass
			x2 = A[-1-i2] - textra * (i2+2)

		if x1 < x2: lo = m
		else: hi = m

	print((lo+hi)/2)


Solve in Python:
There is a room with n bulbs, numbered from 1 to n, arranged in a row from left to right. Initially, all the bulbs are turned off.
At moment k (for k from 0 to n - 1), we turn on the light[k] bulb. A bulb change color to blue only if it is on and all the previous bulbs (to the left) are turned on too.
Return the number of moments in which all turned on bulbs are blue.

Example 1:

Input: light = [2,1,3,5,4]
Output: 3
Explanation: All bulbs turned on, are blue at the moment 1, 2 and 4.

Example 2:
Input: light = [3,2,4,1,5]
Output: 2
Explanation: All bulbs turned on, are blue at the moment 3, and 4 (index-0).

Example 3:
Input: light = [4,1,2,3]
Output: 1
Explanation: All bulbs turned on, are blue at the moment 3 (index-0).
Bulb 4th changes to blue at the moment 3.

Example 4:
Input: light = [2,1,4,3,6,5]
Output: 3

Example 5:
Input: light = [1,2,3,4,5,6]
Output: 6

Constraints:

n == light.length
1 <= n <= 5 * 10^4
light is a permutation of  [1, 2, ..., n]

class Solution:
    def numTimesAllBlue(self, light: List[int]) -> int:
        total = 0
        count = 0
        for k in range(len(light)):
            total += light[k]
            if total == ((k + 1) * (k + 2)) // 2:
                count += 1
        return count


Solve in Python:
There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be.

Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:

Flip all the lights.
Flip lights with even numbers.
Flip lights with odd numbers.
Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...

Example 1:

Input: n = 1, m = 1.
Output: 2
Explanation: Status can be: [on], [off]

Example 2:

Input: n = 2, m = 1.
Output: 3
Explanation: Status can be: [on, off], [off, on], [off, off]

Example 3:

Input: n = 3, m = 1.
Output: 4
Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].

Note:
n and m both fit in range [0, 1000].

class Solution(object):
     def flipLights(self, n, m):
         """
         :type n: int
         :type m: int
         :rtype: int
         """
         if not n: return 0
         n,b=min(6,n),set()
         b.add(tuple([1]*n))
         for j in range(m):
             c=set()
             for x in b:
                 for t in tuple([(x[i]+1)%2 for i in range(n)]),tuple([x[i] if i%2==0 else (x[i]+1)%2 for i in range(n)]),tuple([(x[i]+1)%2 if i%2==0 else x[i] for i in range(n)]),tuple([(x[i]+1)%2 if i%3==0 else x[i] for i in range(n)]):
                     if t not in c:
                         c.add(t)
             b=c
             if len(b)==8: return 8
         return len(b)


Solve in Python:
There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.

A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup".

As a simplification, you may assume that no letter occurs more than once in the secret string.

You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.

def recoverSecret(a):
    out = list(zip(*a))  # transpose the list
    h = [j for j in (set(out[0])-set(out[1]+out[2]))]  # find the first letter
    for i in a:
        if i[0] in h:  # find triplets starting with that letter
            i[:2], i[2] = i[1:], ''   # remove the first letter and move other letters up

    return h[0]+recoverSecret(a) if h else str()  # return the first letter plus the recursion on the rest


Solve in Python:
There is a simple undirected graph with N vertices and M edges.
The vertices are numbered 1 through N, and the edges are numbered 1 through M.
Edge i connects Vertex U_i and V_i.
Also, Vertex i has two predetermined integers A_i and B_i.
You will play the following game on this graph.
First, choose one vertex and stand on it, with W yen (the currency of Japan) in your pocket.
Here, A_s \leq W must hold, where s is the vertex you choose.
Then, perform the following two kinds of operations any number of times in any order:
 - Choose one vertex v that is directly connected by an edge to the vertex you are standing on, and move to vertex v. Here, you need to have at least A_v yen in your pocket when you perform this move.
 - Donate B_v yen to the vertex v you are standing on. Here, the amount of money in your pocket must not become less than 0 yen.
You win the game when you donate once to every vertex.
Find the smallest initial amount of money W that enables you to win the game.

-----Constraints-----
 - 1 \leq N \leq 10^5
 - N-1 \leq M \leq 10^5
 - 1 \leq A_i,B_i \leq 10^9
 - 1 \leq U_i < V_i \leq N
 - The given graph is connected and simple (there is at most one edge between any pair of vertices).

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
:
A_N B_N
U_1 V_1
U_2 V_2
:
U_M V_M

-----Output-----
Print the smallest initial amount of money W that enables you to win the game.

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

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

If you have 6 yen initially, you can win the game as follows:
 - Stand on Vertex 4. This is possible since you have not less than 6 yen.
 - Donate 2 yen to Vertex 4. Now you have 4 yen.
 - Move to Vertex 3. This is possible since you have not less than 4 yen.
 - Donate 1 yen to Vertex 3. Now you have 3 yen.
 - Move to Vertex 2. This is possible since you have not less than 1 yen.
 - Move to Vertex 1. This is possible since you have not less than 3 yen.
 - Donate 1 yen to Vertex 1. Now you have 2 yen.
...

class dsu:
    def __init__(self, n=0):
        self._n = n
        self.parent_or_size = [-1] * n

    def merge(self, a: int, b: int) -> int:
        x = self.leader(a)
        y = self.leader(b)
        if x == y:
            return x
        if self.parent_or_size[x] > self.parent_or_size[y]:
            x, y = y, x
        self.parent_or_size[x] += self.parent_or_size[y]
        self.parent_or_size[y] = x
        return x

    def same(self, a: int, b: int) -> bool:
        return self.leader(a) == self.leader(b)

    def leader(self, a: int) -> int:
        x = a
        while self.parent_or_size[x] >= 0:
            x = self.parent_or_size[x]
        while a != x:
            self.parent_or_size[a], a = x, self.parent_or_size[a]
        return x

    def size(self, a: int) -> int:
        return -self.parent_or_size[self.leader(a)]

    def groups(self):
        g = [[] for _ in range(self._n)]
        for i in range(self._n):
            g[self.leader(i)].append(i)
        return list(c for c in g if c)

n, m = list(map(int, input().split()))
vdata = [] # (required, gain)
for _ in range(n):
    a, b = list(map(int, input().split()))
    vdata.append((max(a - b, 0), b))
to = [[] for _ in range(n)]
for _ in range(m):
    u, v = list(map(int, input().split()))
    u -= 1; v -= 1
    to[u].append(v)
    to[v].append(u)
s = dsu(n)
dp = vdata.copy() # (extra, tot_gain)
visited = [False] * n
for u in sorted(list(range(n)), key=lambda i: vdata[i][0]):
    req, gain = vdata[u]
    frm = {u}
    for v in to[u]:
        if visited[v]:
            frm.add(s.leader(v))
    mnextra = 10 ** 18
    for v in frm:
        e, g = dp[v]
        e += max(req - (e + g), 0)
        if e < mnextra:
            mnextra, mni = e, v
    extra, tot_gain = mnextra, sum(dp[v][1] for v in frm)
    for v in frm:
        s.merge(u, v)
    dp[s.leader(u)] = extra, tot_gain
    visited[u] = True
ans = sum(dp[s.leader(0)])
print(ans)


Solve in Python:
There is a strange printer with the following two special requirements:

On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
Once the printer has used a color for the above operation, the same color cannot be used again.

You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.
Return true if it is possible to print the matrix targetGrid, otherwise, return false.

Example 1:

Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]
Output: true

Example 2:

Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]
Output: true

Example 3:
Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]
Output: false
Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.
Example 4:
Input: targetGrid = [[1,1,1],[3,1,3]]
Output: false

Constraints:

m == targetGrid.length
n == targetGrid[i].length
1 <= m, n <= 60
1 <= targetGrid[row][col] <= 60

from collections import defaultdict
class Solution:
    def all_same(self, left, right, bottom, top, color):
        for i in range(bottom, top+1):
            for j in range(left, right+1):
                if self.grid[i][j] and self.grid[i][j] != color:
                    return False
        return True

    def fill(self, left, right, bottom, top):
        for i in range(bottom, top+1):
            for j in range(left, right+1):
                self.grid[i][j] = 0

    def isPrintable(self, targetGrid: List[List[int]]) -> bool:
        self.rect = defaultdict(lambda : [10**9, -10**9, 10**9, -10**9])
        for i, row in enumerate(targetGrid):
            for j, color in enumerate(row):
                self.rect[color][0] = min(self.rect[color][0], j)
                self.rect[color][1] = max(self.rect[color][1], j)
                self.rect[color][2] = min(self.rect[color][2], i)
                self.rect[color][3] = max(self.rect[color][3], i)
        self.grid = targetGrid
        while self.rect:
            for color in self.rect:
                left, right, bottom, top = self.rect[color]
                if self.all_same(left, right, bottom, top, color):
                    self.fill(left, right, bottom, top)
                    self.rect.pop(color)
                    break
            else:
                return False
        return True


Solve in Python:
There is a task in Among Us in which $N$ temperature scale with unique readings are given and you have to make all of them equal. In one second you can choose an odd number and add or subtract that number in any one temperature value. Find minimum time (in seconds) required to complete the task.
$Note$: Equal value may or may not belong to array.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains single integer $N$, the number of temperature scales
- Next line contain $A_i$ for $1 \leq i \leq N$, reading of temperature scales

-----Output:-----
For each testcase, output a single line the time (in seconds) required to complete the task.

-----Constraints-----
- $1 \leq T \leq 10^3$
- $1 \leq N \leq 10^3$
- $0 \leq A_i \leq 10^9$

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

5

1 2 3 4 5

4

5 2 3 8

2

50 53

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

4

1

-----EXPLANATION:-----
- In the $2^{nd}$ test case we need $2$ seconds to change $2$ to $8$ , $1$ second to change $3$ and $5$ to $8$ . So total time required is $2+1+1=4$ seconds.

for _ in range(int(input())):
 n=int(input())
 a=list(map(int,input().split()))
 ce=co=0
 if n==1:
  print(n-1)
 else:
  for i in a:
   if i%2==0:
    ce+=1
   else:
    co+=1
  if ce==0 or co==0:
   print(n)
  else:
   c1=max(co,ce)
   c2=min(co,ce)
   print(c1+2*(c2-1))


Solve in Python:
There is a tree with N vertices numbered 1 through N.
The i-th edge connects Vertex x_i and y_i.
Each vertex is painted white or black.
The initial color of Vertex i is represented by a letter c_i.
c_i = W represents the vertex is white; c_i = B represents the vertex is black.
A cat will walk along this tree.
More specifically, she performs one of the following in one second repeatedly:
 - Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.
 - Invert the color of the vertex where she is currently.
The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex.
At least how many seconds does it takes for the cat to achieve her objective?

-----Constraints-----
 - 1 ≤ N ≤ 10^5
 - 1 ≤ x_i,y_i ≤ N (1 ≤ i ≤ N-1)
 - The given graph is a tree.
 - c_i = W or c_i = B.

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
c_1c_2..c_N

-----Output-----
Print the minimum number of seconds required to achieve the objective.

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

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

The objective can be achieved in five seconds, for example, as follows:
 - Start at Vertex 1. Change the color of Vertex 1 to black.
 - Move to Vertex 2, then change the color of Vertex 2 to white.
 - Change the color of Vertex 2 to black.
 - Move to Vertex 4, then change the color of Vertex 4 to black.
 - Move to Vertex 5, then change the color of Vertex 5 to black.

"""

https://atcoder.jp/contests/arc097/tasks/arc097_d

始点と終点関係ある？
→逆にしても問題はない

黒い葉は完全に無視できる(落とせる)
よって、葉はすべて白
葉以外は白黒どっちもあり得る

すべての葉をめぐる最短経路？
ある葉からスタートするのは自明っぽい？
ある白からスタートするのはそう

→自分を塗ってからdfsする
→全方位木dp?

行きのみで帰らない場所が1つ存在するはず
→始点と終点のパスとそこから生える木って感じのイメージ

足踏み(停止)の回数を極力少なくしたい
→始点でも終点でもない場合、 e本の辺がつながってたらe回訪問は確定
　e^colorが黒でない場合は+1
→つまり、各頂点で消費する回数は始点・終点でない限り常に一定？

終点はまず葉→始点も葉でおｋ
始点は足踏みなので1秒つかう　終点も1秒使う
パス上の点は、e-1回訪問(ここが根本的に違う！)

つまり、あるパスがあって　その長さがL(両端除く)の時、最大でL減る
ただし、パス上にあっても回数が減らない点もある

B=0 W=1とするか
(color^E) == 1 の点は、E-1回訪問になると足踏みがいらないから2減る
つまり、そのような点が最大数あるパスを求めればいい

"""

import sys
sys.setrecursionlimit(200000)
from collections import deque

MM = 0

def dfs(v,p):
    nonlocal MM

    if v != p and linknum[v] == 1:
        return 0

    cl = []
    for nex in lis[v]:
        if nex != p and exist[nex]:
            tmp = dfs(nex,v)
            cl.append(tmp)
    cl.sort()
    cl.reverse()

    if len(cl) == 1:
        MM = max(MM , cl[0])
    else:
        if (linknum[v]+c[v])%2 == 1:
            MM = max(MM , cl[0] + cl[1] + 2)
        else:
            MM = max(MM , cl[0] + cl[1])

    if (linknum[v]+c[v]) % 2 == 1:
        return cl[0]+ 2
    else:
        return cl[0]

N = int(input())

lis =  [ [] for i in range(N) ]
linknum = [0] * N
for i in range(N-1):
    u,v = list(map(int,input().split()))
    u -= 1
    v -= 1

    lis[u].append(v)
    lis[v].append(u)
    linknum[u] += 1
    linknum[v] += 1

ctmp = input()
c = []

for i in ctmp:
    if i == "B":
        c.append(0)
    else:
        c.append(1)

exist = [True] * N

q = deque([])
for i in range(N):
    if linknum[i] <= 1 and c[i] == 0:
        q.append(i)

while len(q) > 0:
    now = q.popleft()
    exist[now] = False
    linknum[now] = 0

    for nex in lis[now]:
        linknum[nex] -= 1

        if linknum[nex] == 1 and c[nex] == 0:
            q.append(nex)

#print (exist)
start = None
for i in range(N):
    if exist[i]:
        start = i
        break
else:
    print((0))
    return

if linknum[start] == 0:
    print((1))
    return

ans =...


Solve in Python:
There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.
Answer the following Q queries:
 - Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq Q \leq 10^5
 - 1 \leq a_i, b_i \leq N
 - 1 \leq c_i \leq N-1
 - 1 \leq d_i \leq 10^4
 - 1 \leq x_j \leq N-1
 - 1 \leq y_j \leq 10^4
 - 1 \leq u_j < v_j \leq N
 - The given graph is a tree.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

-----Output-----
Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

-----Sample Input-----
5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

-----Sample Output-----
130
200
60

The graph in this input is as follows:

Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.
 - Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.
 - Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.
 - Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have...

from bisect import bisect_left, bisect_right
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

def solve():
    INF = float('inf')

    N, Q = list(map(int, input().split()))
    adjL = [[] for _ in range(N)]
    for _ in range(N-1):
        A, B, C, D = list(map(int, input().split()))
        A, B, C = A-1, B-1, C-1
        adjL[A].append((B, C, D))
        adjL[B].append((A, C, D))
    querys = [tuple(map(int, input().split())) for _ in range(Q)]

    def dfs(vNow, vPar, depth):
        iVFirsts[vNow] = len(vs)
        vs.append(vNow)
        depths.append(depth)
        for v2, clr, dist in adjL[vNow]:
            if v2 == vPar: continue
            iVColorss[clr].append(len(numEs))
            numEs.append(1)
            sumDs.append(dist)

            dfs(v2, vNow, depth+1)

            vs.append(vNow)
            depths.append(depth)
            iVColorss[clr].append(len(numEs))
            numEs.append(-1)
            sumDs.append(-dist)

    vs = []
    iVFirsts = [-1] * N
    depths = []
    numEs = [0]
    sumDs = [0]
    iVColorss = [[0] for _ in range(N-1)]

    dfs(0, -1, 0)

    dists = [0] * N
    accD = 0
    for i, sumD in enumerate(sumDs):
        accD += sumD
        if iVFirsts[vs[i]] == i:
            dists[vs[i]] = accD

    for iVColors in iVColorss:
        for i in range(1, len(iVColors)):
            numEs[iVColors[i]] += numEs[iVColors[i-1]]
            sumDs[iVColors[i]] += sumDs[iVColors[i-1]]

    idEle = (INF, -1)
    def _binOpe(x, y):
        return x if x <= y else y  # min
    def makeSegTree(numEle):
        numPow2 = 2 ** (numEle-1).bit_length()
        data = [idEle] * (2*numPow2)
        return data, numPow2
    def setInit(As):
        for iST, A in enumerate(As, numPow2):
            data[iST] = A
        for iST in reversed(list(range(1, numPow2))):
            data[iST] = _binOpe(data[2*iST], data[2*iST+1])
    def getValue(iSt, iEn):
        L = iSt + numPow2
        R = iEn + numPow2
        ans = idEle
        while L < R:
            if L & 1:
 ...


Solve in Python:
There is a universal library, where there is a big waiting room with seating capacity for maximum $m$ people, each of whom completes reading $n$ books sequentially. Reading each book requires one unit of time.
Unfortunately, reading service is provided sequentially. After all of the $m$ people enter the library, the entrance gate is closed. There is only one reading table. So when someone reads, others have to wait in the waiting room.
At first everybody chooses $n$ books they want to read. It takes $x$ amount of time. People can choose books simultaneously. Then they enter the waiting room. After reading $n$ books the person leaves the library immediately.
As nothing is free, the cost of reading is also not free. If a person stays in the library $t$ units of time then the cost of reading is $\left \lfloor \frac{t-n}{m} \right \rfloor$ units of money. So, the $i^{th}$ person pays for time $x$ he needs to choose books and the time $(i-1)*n$ he needs to wait for all the persons before him to complete reading.
Note: $\left \lfloor a \right \rfloor$ denotes the floor($a$).

-----Input-----
- Each case contains three space-separated positive integers $n$, $m$ and $x$ where $n, x \leq 1000$ and $m \leq 10^{15}$.
- End of input is determined by three zeros.
- There are no more than 1000 test cases.

-----Output-----
- For each case, output in a single line the total unit of money the library gets in that day.

-----Sample Input-----
1 100 9
11 2 10
12 2 11
0 0 0

-----Sample Output-----
9
15
16

-----Explanation:-----
Testcase 2: Here, $n=11$, $m=2$, $x=10$.
For 1st person,
$t=21$ and he/she gives $\left \lfloor \frac{21-11}{2} \right \rfloor = 5$ units of money.
For 2nd person,
$t=32$ and he/she gives $\left \lfloor \frac{32-11}{2} \right \rfloor= 10$ units of money.
So, total units of money $= 5+10 = 15$

while True:

 n,m,x = list(map(int,input().split()))

 if n == m == x == 0:
  break
 cost = 0
 for i in range(n):
  cost+=((m*i+x)//n)
 print(cost)


Solve in Python:
There is an array of strings. All strings contains similar _letters_ except one. Try to find it!

```python
find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb'
find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo'
```

Strings may contain spaces. Spaces is not significant, only non-spaces symbols matters. E.g. string that contains only spaces is like empty string.

It’s guaranteed that array contains more than 3 strings.

This is the second kata in series:

1. [Find the unique number](https://www.codewars.com/kata/585d7d5adb20cf33cb000235)
2. Find the unique string (this kata)
3. [Find The Unique](https://www.codewars.com/kata/5862e0db4f7ab47bed0000e5)

import numpy as np
def find_uniq(arr):
    arr1 = [''.join(sorted(set(i.lower().replace(' ','')))) for i in arr]
    lst = np.unique(arr1)
    for i in lst:
        if arr1.count(i) == 1:
            return arr[arr1.index(i)]


Solve in Python:
There is an array with some numbers. All numbers are equal except for one. Try to find it!

```python
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
```

It’s guaranteed that array contains at least 3 numbers.

The tests contain some very huge arrays, so think about performance.

This is the first kata in series:

1. Find the unique number (this kata)
2. [Find the unique string](https://www.codewars.com/kata/585d8c8a28bc7403ea0000c3)
3. [Find The Unique](https://www.codewars.com/kata/5862e0db4f7ab47bed0000e5)

from collections import Counter

def find_uniq(a):
    return Counter(a).most_common()[-1][0]


Solve in Python:
There is an automatic door at the entrance of a factory. The door works in the following way:  when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside,  when one or several people come to the door and it is open, all people immediately come inside,  opened door immediately closes in d seconds after its opening,  if the door is closing and one or several people are coming to the door at the same moment, then all of them will have enough time to enter and only after that the door will close.

For example, if d = 3 and four people are coming at four different moments of time t_1 = 4, t_2 = 7, t_3 = 9 and t_4 = 13 then the door will open three times: at moments 4, 9 and 13. It will close at moments 7 and 12.

It is known that n employees will enter at moments a, 2·a, 3·a, ..., n·a (the value a is positive integer). Also m clients will enter at moments t_1, t_2, ..., t_{m}.

Write program to find the number of times the automatic door will open. Assume that the door is initially closed.

-----Input-----

The first line contains four integers n, m, a and d (1 ≤ n, a ≤ 10^9, 1 ≤ m ≤ 10^5, 1 ≤ d ≤ 10^18) — the number of the employees, the number of the clients, the moment of time when the first employee will come and the period of time in which the door closes.

The second line contains integer sequence t_1, t_2, ..., t_{m} (1 ≤ t_{i} ≤ 10^18) — moments of time when clients will come. The values t_{i} are given in non-decreasing order.

-----Output-----

Print the number of times the door will open.

-----Examples-----
Input
1 1 3 4
7

Output
1

Input
4 3 4 2
7 9 11

Output
4

-----Note-----

In the first example the only employee will come at moment 3. At this moment the door will open and will stay open until the moment 7. At the same moment of time the client will come, so at first he will enter and only after it the door will close. Thus the door will open one time.

def solve():
    n1, m, a, d = list(map(int, input().split()))
    t = list(map(int, input().split()))
    from bisect import insort
    from math import floor
    insort(t, a * n1)
    pred = 0
    k = 0
    kpred = 0
    n = 0
    step = d // a + 1
    sol = 0
    fl = 0
    for i in t:
        if (i > pred):
            if fl == 0:
                n = (i - pred + (pred % a)) // a
                if n != 0:
                    k += (n // step) * step - step * (n % step == 0) + 1
                    if k > n1:
                        k = n1
                        fl = 1
                # print(k)
                if (k * a + d >= i) and (n != 0):
                    pred = k * a + d
                else:
                    pred = i + d
                    k = floor(pred // a)
                    sol += 1
                # if n==0:
                k = min(floor(pred // a), n1)
                sol += n // step + (n % step != 0)
            else:
                sol += 1
                pred = i + d
        if i == a * n1:
            fl = 1
            # print(i,pred,sol,n,step,k, fl)
    print(sol)
solve()


Solve in Python:
There is an event in DUCS where boys get a chance to show off their skills to impress girls. The boy who impresses the maximum number of girls will be honoured with the title “Charming Boy of the year”.
There are $N$ girls in the department. Each girl gives the name of a boy who impressed her the most. You need to find the name of a boy who will be honoured with the title.
If there are more than one possible winners, then the one with the lexicographically smallest name is given the title.
It is guaranteed that each boy participating in the event has a unique name.

-----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 an integer $N$ denoting the number of girls.
- The second line contains $N$ space-separated strings $S_1, S_2, \ldots, S_N$, denoting the respective names given by the girls.

-----Output-----
For each test case, print a single line containing a string — the name of the boy who impressed the maximum number of girls. In case of a tie, print the lexicographically smallest name.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^5$
- $1 \leq |S_i| \leq 10$, for each valid $i$
$(|S_i|$ is the length of the string $S_i)$
- For each valid $i$, $S_i$ contains only lowercase English alphabets
- Sum of $N$ over all the test cases is $\leq 10^6$

-----Subtasks-----
- 30 points: $1 \leq N \leq 100$
- 70 points: original constraints

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

10

john berry berry thomas thomas john john berry thomas john

4

ramesh suresh suresh ramesh

-----Sample Output-----
john

ramesh

testCase=int(input())
for _ in range(testCase):
    numBoys=int(input())
    finalList=[]
    boysList=[i for i in input().split()]
    boysList.sort()
    while len(boysList)!=0:
        coun=boysList.count(boysList[0])
        finalList.append([boysList[0],coun])
        for _ in range(coun):
            boysList.remove(boysList[0])

    finalList.sort(key=lambda x:x[1])
    finalList.reverse()
    test=[]
    name=[]
    for z in finalList:
        if len(test)==0:
            test.append(z[1])
            name.append(z[0])
        else:
            if z[1] in test:
                name.append(z[0])
            else:
                break
    if len(name)>1:
        name.sort()
        print(name[0])
    else:
        print(name[0]  )


Solve in Python:
There is an infinitely long street that runs west to east, which we consider as a number line.
There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.
Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.
Find the distance each of the Q people will walk.

-----Constraints-----
 - All values in input are integers.
 - 1 \leq N, Q \leq 2 \times 10^5
 - 0 \leq S_i < T_i \leq 10^9
 - 1 \leq X_i \leq 10^9
 - 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9
 - If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

-----Input-----
Input is given from Standard Input in the following format:
N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

-----Output-----
Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

-----Sample Input-----
4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

-----Sample Output-----
2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.
The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.
The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.

def main():
    from heapq import heappush, heappop
    import sys
    sys.setrecursionlimit(10 ** 7)

    n,q=map(int,input().split())

    event=[]
    for _ in range(n):
        s,t,x=map(int,input().split())
        event.append((s-x,1,x))
        event.append((t-x,-1,x))

    for i in range(q):
        event.append((int(input()),2,i))
    event.sort()

    ans=[0]*q

    stop=set()
    hq=[]
    for t,op,x in event:
        if op==1:
            heappush(hq,x)
            stop.add(x)
        elif op==-1:
            stop.remove(x)

        else:
            while hq and hq[0] not in stop:
                heappop(hq)
            ans[x]=hq[0] if hq else -1

    for x in ans:
        print(x)

main()


Solve in Python:
There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)
For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:
 - Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K.
Here, or denotes the bitwise OR.

-----Constraints-----
 - 1 \leq N \leq 18
 - 1 \leq A_i \leq 10^9
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
A_0 A_1 ... A_{2^N-1}

-----Output-----
Print 2^N-1 lines.
In the i-th line, print the answer of the problem above for K=i.

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

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

For K=1, the only possible pair of i and j is (i,j)=(0,1), so the answer is A_0+A_1=1+2=3.
For K=2, the possible pairs of i and j are (i,j)=(0,1),(0,2).
When (i,j)=(0,2), A_i+A_j=1+3=4. This is the maximum value, so the answer is 4.
For K=3, the possible pairs of i and j are (i,j)=(0,1),(0,2),(0,3),(1,2),(1,3),(2,3) .
When (i,j)=(1,2), A_i+A_j=2+3=5. This is the maximum value, so the answer is 5.

import sys
input = sys.stdin.readline
from itertools import accumulate

def merge(x, y):
  a, b = dp[x]
  c, d = dp[y]
  if a >= c:
    return (a, max(c, b))
  return (c, max(a, d))

n = int(input())
A = tuple(map(int, input().split()))
dp = [(a, 0) for a in A]
for j in range(n):
  for i in range(1<<n):
    if i & (1<<j):
      dp[i] = merge(i, i & ~(1<<j))
L = tuple(accumulate((sum(d) for d in dp), max))
print(*L[1:], sep="\n")


Solve in Python:
There is an undirected tree of $n$ vertices, connected by $n-1$ bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex $a$ and its tail is at vertex $b$. The snake's body occupies all vertices on the unique simple path between $a$ and $b$.

The snake wants to know if it can reverse itself  — that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.

In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail. [Image] Let's denote a snake position by $(h,t)$, where $h$ is the index of the vertex with the snake's head, $t$ is the index of the vertex with the snake's tail. This snake can reverse itself with the movements $(4,7)\to (5,1)\to (4,2)\to (1, 3)\to (7,2)\to (8,1)\to (7,4)$.

Determine if it is possible to reverse the snake with some sequence of operations.

-----Input-----

The first line contains a single integer $t$ ($1\le t\le 100$)  — the number of test cases. The next lines contain descriptions of test cases.

The first line of each test case contains three integers $n,a,b$ ($2\le n\le 10^5,1\le a,b\le n,a\ne b$).

Each of the next $n-1$ lines contains two integers $u_i,v_i$ ($1\le u_i,v_i\le n,u_i\ne v_i$), indicating an edge between vertices $u_i$ and $v_i$. It is guaranteed that the given edges form a tree.

It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$.

-----Output-----

For each test case, output "YES" if it is possible for the snake to reverse itself, or "NO" otherwise.

-----Example-----
Input
4
8 4 7
1 2
2 3
1 4
4 5
4 6
1 7
7 8
4 3 2
4 3
1 2
2 3
9 3 5
1 2
2 3
3 4
1 5
5 6
6 7
1 8
8...

from sys import stdin
import itertools
input = stdin.readline
def getint(): return int(input())
def getints(): return list(map(int, input().split()))
def getint1(): return list([int(x) - 1 for x in input().split()])
def getstr(): return input()[:-1]

def solve():
    n, a, b = getint1()
    n += 1
    adj = [[] for _ in range(n)]
    for _ in range(n - 1):
        u, v = getint1()
        adj[u].append(v)
        adj[v].append(u)
    # dfs 1
    max_child = [[-1] * 3 for _ in range(n)]
    stack = [(a, -1, 1)]  # (node, parent)
    while stack:
        u, p, flag = stack.pop()
        if p != -1 and len(adj[u]) < 2:
            max_child[u][0] = 1
            continue
        if flag == 1:
            stack.append((u, p, 0))
            for v in adj[u]:
                if v == p:
                    continue
                stack.append((v, u, 1))
        else:
            for v in adj[u]:
                if v == p:
                    continue
                len_v = max_child[v][0] + 1
                if len_v > max_child[u][0]:
                    max_child[u][2] = max_child[u][1]
                    max_child[u][1] = max_child[u][0]
                    max_child[u][0] = len_v
                elif len_v > max_child[u][1]:
                    max_child[u][2] = max_child[u][1]
                    max_child[u][1] = len_v
                elif len_v > max_child[u][2]:
                    max_child[u][2] = len_v
    # end of dfs 1
    # dfs 2
    body = []
    ret = [False] * n
    max_parent = [-1] * n
    stack.clear()
    stack = [(a, -1, 0)]  # (node, parent, max len from parent)
    while stack:
        u, p, mxp = stack.pop()
        if mxp >= 0:
            stack.append((u, p, -1))
            if p != -1 and len(adj[u]) < 2:
                continue
            max_parent[u] = mxp + 1
            chlen = [max_parent[u], -3]
            for v in adj[u]:
                if v == p:
                    continue
                len_v = max_child[v][0] + 1
                if len_v > chlen[0]:
                 ...


Solve in Python:
There is crazy man named P29892P. He always tries to do crazy things as he thinks. One day he invented a machine and named it as ANGEN. The ANGEN is used to perform range operations. The range operation means performing operations on range values from {L..R}. At any time it performs operations on values in between L to R.
ANGEN can perform following operations
U I V - Update the value present at I  with value V
A L R - Find the sum between range L and R
M L R - Find the maximum number between L and R
m L R - Find the minimum number between L and R
S L R - Find second maximum value in between L and R
s L R - Find second mimimum value in between L and R
If it is not possible perform operation ANGEN returns “NA” with out quotes.
For Invalid operations ANGEN returns “!!!” with out quotes.
Now P29892P challenging his friends and you too, to build his invention with yourown code. So it's your time to defeat P29892P by implementing his invention with your own ability. Let's go and solve the problem.

-----Input-----
Input description.
- The first line of the input contains an integer N denoting the number of integers.
- The next line contains N space separated integers."
- The next line contains a single integer Q denoting the number of Questions.
-  The next Q lines contains T Question type , L and R.

-----Output-----
Print output for each question in separate line.

-----Constraints-----
Should contain all the constraints on the input data that you may have. Format it like:
- 1 ≤ N ≤ 100000
- 1 ≤ values[i] ≤ 1000000000
- 1 ≤ Q ≤ 10000
- T in { A..Z, a..z }
- 1 ≤ L ≤ R ≤ N

-----Example-----
Input:
6
1 2 5 3 10 6
6
A 1 5
M 1 3
m 5 6
s 3 6
U 1 7
S 1 2

Output:
21
5
6
5
2

-----Explanation-----
...

#rjohari23

n = eval(input())
a = list(map(int,input().split()))
q = eval(input())
while q:

 s = input().split()
 #print s
 if s[0]=='U':
  l = int(s[1])
  v = int(s[2])
  a[l-1] = v
 if s[0]=='A':
  l = int(s[1])
  r = int(s[2])
  print(sum(a[l-1:r]))
 if s[0]=='M':
  l = int(s[1])
  r = int(s[2])
  print(max(a[l-1:r]))
 if s[0]=='m':
  l = int(s[1])
  r = int(s[2])
  print(min(a[l-1:r]))
 if s[0]=='S':
  l = int(s[1])
  r = int(s[2])
  A = sorted(a[l-1:r],reverse=True)
  print(A[1])
 if s[0]=='s':
  l = int(s[1])
  r = int(s[2])
  A = sorted(a[l-1:r])
  print(A[1])

 q -= 1


Solve in Python:
There is enough money available on ATM in nominal value 10, 20, 50, 100, 200 and 500 dollars.

You are given money in nominal value of `n` with `1<=n<=1500`.

Try to find minimal number of notes that must be used to repay in dollars, or output -1 if it is impossible.

Good Luck!!!

def solve(n):
    t=0
    for d in [500,200,100,50,20,10]:
        a,n=divmod(n,d)
        t+=a
    if n: return -1
    return t


Solve in Python:
There is no single treatment that works for every phobia, but some people cure it by being gradually exposed to the phobic situation or object. In this kata we will try curing arachnophobia by drawing primitive spiders.

Our spiders will have legs, body, eyes and a mouth. Here are some examples:
```
/\((OOwOO))/\

/╲(((0000w0000)))╱\

^(oWo)^
```
You will be given four values:
1) `leg size` where each value stands for its own leg type: `1 for "^ ^", 2 for "/\ /\", 3 for "/╲ ╱\", 4 for "╱╲ ╱╲"`
2) `body size` where each value stands for its own body type: `1 for "( )", 2 for "(( ))", 3 for "((( )))"`
3) `mouth` representing the spider's mouth
4) `eye` representing the spider's eye

**Note:** the eyes are symmetric, and their total amount is `2 to the power of body size`.

You will also be given only valid data. That's it for the instructions, you can start coding!

def draw_spider(leg,body,mouth,eye):
    legs=["^ ^","/\\ /\\","/╲ ╱\\","╱╲ ╱╲"][leg-1].split()
    return legs[0]+"("*body+eye*2**(body-1)+mouth+eye*2**(body-1)+")"*body+legs[1]


Solve in Python:
There is only little time left until the New Year! For that reason, Chef decided to make a present for his best friend. He made a connected and undirected simple graph with N$N$ vertices and M$M$ edges.
Since Chef does not like odd numbers and his friend does not like undirected graphs, Chef decided to direct each edge in one of two possible directions in such a way that the indegrees of all vertices of the resulting graph are even. The indegree of a vertex is the number of edges directed to that vertex from another vertex. As usual, Chef is busy in the kitchen, so you need to help him with directing the edges. Find one possible way to direct them or determine that it is impossible under the given conditions, so that Chef could bake a cake as a present instead.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- M$M$ lines follow. For each i$i$ (1≤i≤M$1 \le i \le M$), the i$i$-th of these lines contains two space-separated integers ui$u_i$ and vi$v_i$ denoting an edge between vertices ui$u_i$ and vi$v_i$.

-----Output-----
For each test case:
- If a valid way to direct the edges does not exist, print a single line containing one integer −1$-1$.
- Otherwise, print a single line containing M$M$ space-separated integers. For each valid i$i$, the i$i$-th of these integers should be 0$0$ if edge i$i$ is directed from ui$u_i$ to vi$v_i$ or 1$1$ if it is directed from vi$v_i$ to ui$u_i$.

-----Constraints-----
- 1≤T≤5$1 \le T \le 5$
- 1≤N,M≤105$1 \le N, M \le 10^5$
- 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$
- the graph on the input is connected, does not contain multiple edges or self-loops

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

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

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

import sys
from collections import deque

def minspan(n,edges):

    nodelist = []
    finale = []

    for i in range(n):
        nodelist.append(set([i+1]))

    for e in edges:
        u = e[0]
        v = e[1]

        for each_set in nodelist:
            if u in each_set:
                save1 = each_set
            if v in each_set:
                save2 = each_set

        if save1 != save2:
            finale.append((u,v))
            merged = save1 | save2
            nodelist.remove(save1)
            nodelist.remove(save2)
            nodelist.append(merged)

        if len(nodelist) == 1:
            break

    return finale

def main():

    t = int(input())

    for i in range(t):

        n,m = [int(item) for item in input().split()]
        e = set()
        elist = []

        for i in range(m):
            u,v = [int(item) for item in input().split()]
            elist.append((u,v))
            e.add((u,v))

        finale = set(minspan(n,e))
        tofix = e - finale

        indegree = {}
        for i in range(n):
            indegree[i+1] = 0

        decided = set()

        # randomly assign directions to edges not in min span
        for t in tofix:
            indegree[t[1]] += 1
            decided.add((t[0],t[1]))

        ## find leaf in finale
        ## fix random root i = 1
        cf = {}
        pf = {}

        for i in range(n):
            cf[i+1] = set()
            pf[i+1] = set()

        for f in finale:
            cf[f[0]].add(f[1])
            cf[f[1]].add(f[0])

        root = 1
        visit = set([root])
        visited = set()
        parent = {}

        #create the min span tree , every child with one parent
        # root is 1
        while len(visited) < n and len(visit) > 0:

            v = visit.pop()
            d = cf[v]
            visited.add(v)

            for i in d:
                if i not in visited:
                    parent[i] = v
                   ...


Solve in Python:
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that has been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color. (For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods  [{1}, {2,2}, {3,3}, {2}, {1,1}]).
Given an array houses, an m * n matrix cost and an integer target where:

houses[i]: is the color of the house i, 0 if the house is not painted yet.
cost[i][j]: is the cost of paint the house i with the color j+1.

Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods, if not possible return -1.

Example 1:
Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 9
Explanation: Paint houses of this way [1,2,2,1,1]
This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].
Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.

Example 2:
Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3
Output: 11
Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]
This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}].
Cost of paint the first and last house (10 + 1) = 11.

Example 3:
Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[1,10],[10,1],[1,10]], m = 5, n = 2, target = 5
Output: 5

Example 4:
Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3
Output: -1
Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.

Constraints:

m == houses.length == cost.length
n == cost[i].length
1 <= m <= 100
1 <= n <= 20
1 <= target <= m
0 <= houses[i] <= n
1 <= cost[i][j] <= 10^4

from collections import defaultdict
class Solution:
    def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
        '''

        m houses - n colors (1~n)
        neighborhoods of same color
        0 = not colored yet
        cost[i][j] - cost to paint i with color j+1

        return minimal cost of painting remaining houses to get exactly target neighborhoods

        -have to keep track of min cost
        -num neighbors==target at end

        dp => cost,numNeighbors
        dp[house][lastneighbor] = min(dp[house][lastneighbor], min(cost + dp[house-1][neighbors])

        best now = last house with same color, correct num of neighbors or last house diff color, 1 less num of neighbors

        dp[h][numNeighbors][color] = colorCost + min(
                dp[h-1][numNeighbors][color],
                dp[h-1][numNeighbors-1][diffColor] <- iterate
            )

        at house h,
        dp[neighbors][color] = colorCost (if it's 0)
                                + prev[neighbors][color]
                                + prev[neighbors-1][anothercolor]
        neighbors: [j-target,j+1]

        edge cases:
        -if # of color neighborhoods > target: return -1
        -num houses < target: return -1
        '''
        prev = [[0]*n for _ in range(target+1)]
        for h,house in enumerate(houses):
            dp = [[float('inf')]*n for _ in range(target+1)]
            for numNeighbors in range(1,min(h+2,target+1)):
                if house==0:
                    for color in range(n):
                        colorCost = cost[h][color]
                        dp[numNeighbors][color] = min(
                            dp[numNeighbors][color],
                            colorCost + prev[numNeighbors][color],
                            colorCost + min(prev[numNeighbors-1][c] for c in range(n) if c!=color)
                        )
                else:
                    color = house-1
       ...


Solve in Python:
There is a sale in a supermarket, there will be a discount every n customer.
There are some products in the supermarket where the id of the i-th product is products[i] and the price per unit of this product is prices[i].
The system will count the number of customers and when the n-th customer arrive he/she will have a discount on the bill. (i.e if the cost is x the new cost is x - (discount * x) / 100). Then the system will start counting customers again.
The customer orders a certain amount of each product where product[i] is the id of the i-th product the customer ordered and amount[i] is the number of units the customer ordered of that product.
Implement the Cashier class:

Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, the products and their prices.
double getBill(int[] product, int[] amount) returns the value of the bill and apply the discount if needed. Answers within 10^-5 of the actual value will be accepted as correct.

Example 1:
Input
["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]
Output
[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
Explanation
Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);
cashier.getBill([1,2],[1,2]);                        // return 500.0, bill = 1 * 100 + 2 * 200 = 500.
cashier.getBill([3,7],[10,10]);                      // return 4000.0
cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]);    // return 800.0, The bill was 1600.0 but as this is the third customer, he has a discount of 50% which means his bill is only 1600 - 1600 * (50 / 100) = 800.
cashier.getBill([4],[10]);                           // return 4000.0
cashier.getBill([7,3],[10,10]);                      // return 4000.0
cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return...

class Cashier:

    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
        self.num_disc = n
        self.disc = discount
        self.prod = products
        self.pric = prices
        self.count = 0

    def getBill(self, product: List[int], amount: List[int]) -> float:
        self.count+=1
        total = 0
        for i in range(len(product)):
            ind = self.prod.index(product[i])
            total += (self.pric[ind] * amount[i])
        if(self.count != 0 and self.count % self.num_disc == 0):
            total = (total - (self.disc * total) / 100)
            self.count = 0
        return total

# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)


Solve in Python:
There is a special square room with mirrors on each of the four walls.  Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.
Return the number of the receptor that the ray meets first.  (It is guaranteed that the ray will meet a receptor eventually.)

Example 1:
Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.

Note:

1 <= p <= 1000
0 <= q <= p

class Solution:
    def mirrorReflection(self, p: int, q: int) -> int:
        def gcd(p, q):
            while q > 0:
                p, q = q, p % q
            return p

        lcm = p * q // gcd(p, q)
        if (lcm // q) % 2 == 0:
            return 2
        elif (lcm // p) % 2 == 1:
            return 1
        else:
            return 0


Solve in Python:
There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.

Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Each district has its own unique name “(X, Y)”, where X and Y are the coordinates of the district in the grid. The thief’s movement is as

Every hour the thief will leave the district (X, Y) he is currently hiding in, and move to one of the districts: (X - 1, Y), (X + 1, Y), (X - 1, Y - 1), (X - 1, Y + 1), (X + 1, Y - 1), (X + 1, Y + 1) as long as it exists in Tablecity.

Below is an example of thief’s possible movements if he is located in district (7,1):

[Image]

Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.

-----Input-----

There is no input for this problem.

-----Output-----

The first line of output contains integer N – duration of police search in hours. Each of the following N lines contains exactly 4 integers X_{i}1, Y_{i}1, X_{i}2, Y_{i}2 separated by spaces, that represent 2 districts (X_{i}1, Y_{i}1), (X_{i}2, Y_{i}2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief’s initial position and movement.  N ≤ 2015  1 ≤ X ≤ 1000  1 ≤ Y ≤ 2

-----Examples-----
Input
В этой задаче нет примеров ввода-вывода.
This problem doesn't have sample input and output.
Output
Смотрите замечание ниже.
See the note below.

-----Note-----

Let's consider the following output:

2

5 1 50 2

8 1 80 2

This output is not guaranteed to catch the...

print(1999)
for i in range(1,1001):
    print(i,1,i,2)
for i in range(2,1001):
    print(i,1,i,2)


Solve in Python:
There was a test in your class and you passed it. Congratulations!
But you're an ambitious person. You want to know if you're better than the average student in your class.

You receive an array with your peers' test scores. Now calculate the average and compare your score!

~~~if-not:nasm,racket
Return `True` if you're better, else `False`!
~~~

~~~if:racket
Return #t if you're better, else #f.
~~~

~~~if:nasm
Return `1` if you're better, else `0`!
~~~

### Note:

Your points are not included in the array of your class's points. For calculating the average point you may add your point to the given array!

def better_than_average(class_points, your_points):
    x = 0
    for i in range(len(class_points)):
        x = x + class_points[i]
    y = x / len(class_points)
    if your_points > y:
        return True
    else:
        return False


Solve in Python:
There were $N$ students (numbered $1$ through $N$) participating in the Indian Programming Camp (IPC) and they watched a total of $K$ lectures (numbered $1$ through $K$). For each student $i$ and each lecture $j$, the $i$-th student watched the $j$-th lecture for $T_{i, j}$ minutes.
Additionally, for each student $i$, we know that this student asked the question, "What is the criteria for getting a certificate?" $Q_i$ times.
The criteria for getting a certificate is that a student must have watched at least $M$ minutes of lectures in total and they must have asked the question no more than $10$ times.
Find out how many participants are eligible for a certificate.

-----Input-----
- The first line of the input contains three space-separated integers $N$, $M$ and $K$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains $K+1$ space-separated integers $T_{i, 1}, T_{i, 2}, \ldots, T_{i, K}, Q_i$.

-----Output-----
Print a single line containing one integer — the number of participants eligible for a certificate.

-----Constraints-----
- $1 \le N, K \le 1,000$
- $1 \le M \le 10^6$
- $1 \le Q_i \le 10^6$ for each valid $i$
- $1 \le T_{i, j} \le 1,000$ for each valid $i$ and $j$

-----Example Input-----
4 8 4
1 2 1 2 5
3 5 1 3 4
1 2 4 5 11
1 1 1 3 12

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

-----Explanation-----
- Participant $1$ watched $1 + 2 + 1 + 2 = 6$ minutes of lectures and asked the question $5$ times. Since $6 < M$, this participant does not receive a certificate.
- Participant $2$ watched $3 + 5 + 1 + 3 = 12$ minutes of lectures and asked the question $4$ times. Since $12 \ge M$ and $4 \le 10$, this participant receives a certificate.
- Participant $3$ watched $1 + 2 + 4 + 5 = 12$ minutes of lectures and asked the question $11$ times. Since $12 \ge M$ but $11 > 10$, this participant does not receive a certificate.
- Participant $4$ watched $1 + 1 + 1 + 3 = 6$ minutes of lectures and asked the question $12$ times. Since $6 < M$ and $12 > 10$, this participant does not receive a certificate.
Only...

inputs = list(map(int, input().split()))
n = inputs[0]
m = inputs[1]
k = inputs[2]
cnt=0
for _ in range(0,n):
 arr = list(map(int, input().split()))
 ques = arr[len(arr)-1]
 s=sum(arr)-ques
 if s<m:
  continue
 else:
  if ques<=10:
   cnt=cnt+1
print(cnt)


Solve in Python:
There were and still are many problem in CW about palindrome numbers and palindrome strings. We suposse that you know which kind of numbers they are. If not, you may search about them using your favourite search engine.

In this kata you will be given a positive integer, ```val``` and you have to create the function ```next_pal()```(```nextPal``` Javascript) that will output the smallest palindrome number higher than ```val```.

Let's see:
```python
For Python
next_pal(11) == 22

next_pal(188) == 191

next_pal(191) == 202

next_pal(2541) == 2552
```

You will be receiving values higher than 10, all valid.

Enjoy it!!

def next_pal(val):
    int_to_digits = lambda n: [int(d) for d in str(n)]
    digits_to_int = lambda a: int("".join(map(str, a)))

    digits = int_to_digits(val)
    half, odd = len(digits) // 2, len(digits) % 2
    build = lambda start: digits_to_int(start + start[::-1][-half:])

    base_start = digits[:half + odd]
    possible = build(base_start)
    if possible > val:
        return possible
    return build(int_to_digits(digits_to_int(base_start) + 1))


Solve in Python:
There's a **"3 for 2"** (or **"2+1"** if you like) offer on mangoes. For a given quantity and price (per mango), calculate the total cost of the mangoes.

### Examples
```python
mango(3, 3) ==> 6    # 2 mangoes for 3 = 6; +1 mango for free
mango(9, 5) ==> 30   # 6 mangoes for 5 = 30; +3 mangoes for free
```

mango = lambda q, p: (q // 3 * 2 + q % 3) * p;


Solve in Python:
There's a new security company in Paris, and they decided to give their employees an algorithm to make first name recognition faster. In the blink of an eye, they can now detect if a string is a first name, no matter if it is a one-word name or an hyphenated name. They're given this documentation with the algorithm:

*In France, you'll often find people with hyphenated first names. They're called "prénoms composés".
There could be two, or even more words linked to form a new name, quite like jQuery function chaining ;).
They're linked using the - symbol, like Marie-Joelle, Jean-Michel, Jean-Mouloud.
Thanks to this algorithm, you can now recognize hyphenated names quicker than Flash !*
(yeah, their employees know how to use jQuery. Don't ask me why)

Your mission if you accept it, recreate the algorithm.
Using the function **showMe**, which takes a **yourID** argument, you will check if the given argument is a name or not, by returning true or false.

*Note that*

- String will either be a one-word first name, or an hyphenated first name , its words being linked by "-".
- Words can only start with an uppercase letter, and then lowercase letters (from a to z)

Now is your time to help the guards !

import re

def show_me(name):
    return bool(re.match('[A-Z][a-z]+(-[A-Z][a-z]+)*$', name))


Solve in Python:
There's a tree and every one of its nodes has a cost associated with it. Some of these nodes are labelled special nodes. You are supposed to answer a few queries on this tree. In each query, a source and destination node (SNODE$SNODE$ and DNODE$DNODE$) is given along with a value W$W$. For a walk between SNODE$SNODE$ and DNODE$DNODE$ to be valid you have to choose a special node and call it the pivot P$P$. Now the path will be SNODE$SNODE$ ->P$ P$ -> DNODE$DNODE$. For any valid path, there is a path value (PV$PV$) attached to it. It is defined as follows:
Select a subset of nodes(can be empty)  in the path from SNODE$SNODE$ to P$P$ (both inclusive) such that sum of their costs (CTOT1$CTOT_{1}$) doesn't exceed W$W$.
Select a subset of nodes(can be empty) in the path from P$P$ to DNODE$DNODE$ (both inclusive) such that sum of their costs (CTOT2$CTOT_{2}$) doesn't exceed W$W$.
Now define PV=CTOT1+CTOT2$PV = CTOT_{1} + CTOT_{2}$ such that the absolute difference  x=|CTOT1−CTOT2|$x = |CTOT_{1} - CTOT_{2}|$ is as low as possible. If there are multiple pairs of subsets that give the same minimum absolute difference, the pair of subsets which maximize PV$PV$ should be chosen.
For each query, output the path value PV$PV$ minimizing x$x$ as defined above.
Note that the sum of costs of an empty subset is zero.

-----Input-----
- First line contains three integers N$N$ - number of vertices in the tree, NSP$NSP$ - number of special nodes in the tree and Q$Q$ - number of queries to answer.
- Second line contains N−1$N-1$ integers. If the i$i$th integer is Vi$V_i$ then there is an undirected edge between i+1$i + 1$ and Vi$V_i$ (i$i$ starts from 1$1$ and goes till N−1$N-1$).
- Third line contains N$N$ integers, the i$i$th integer represents cost of the i$i$th vertex.
- Fourth line contains NSP$NSP$ integers - these represent which nodes are the special nodes.
- Following Q$Q$ lines contains three integers each - SNODE$SNODE$, DNODE$DNODE$ and W$W$ for each query.

-----Output-----
For each query output...

# cook your dish here
# cook your dish here
import numpy as np
n, s, q = [int(j) for j in input().split()]
edges = [int(j)-1 for j in input().split()]
costs = [int(j) for j in input().split()]
special = [int(j)-1 for j in input().split()]
queries = [[0] * 3 for _ in range(q)]
for i in range(q):
   queries[i] = [int(j)-1 for j in input().split()]

edge_set = [[] for _ in range(n)]
for i in range(n-1):
   edge_set[i+1].append(edges[i])
   edge_set[edges[i]].append(i+1)

stored = np.zeros((s,n,1001),dtype=bool)
visited = [[] for _ in range(s)]
for i in range(s):
   s_vertex = special[i]
   s_cost = costs[s_vertex]
   s_visited = visited[i]
   s_visited.append(s_vertex)
   s_stored = stored[i]
   s_stored[s_vertex][0] = True
   s_stored[s_vertex][s_cost] = True
   for edge in edge_set[s_vertex]:
      s_visited.append(edge)
      s_stored[edge] = np.array(s_stored[s_vertex])
   for j in range(1,n):
      vertex = s_visited[j]
      cost = costs[vertex]
      s_stored[vertex][cost:1001] = np.logical_or(s_stored[vertex][0:1001-cost],s_stored[vertex][cost:1001])
      for edge in edge_set[vertex]:
         if edge not in s_visited:
            s_visited.append(edge)
            s_stored[edge] = np.array(s_stored[vertex])

for i in range(q):
   first, second, max_cost = queries[i]
   bool_array = np.zeros(max_cost+2,dtype=bool)
   for j in range(s):
      bool_array = np.logical_or(bool_array,np.logical_and(stored[j][first][:max_cost+2],stored[j][second][:max_cost+2]))
   for j in range(max_cost+1,-1,-1):
      if bool_array[j]:
         print(2 * j)
         break


Solve in Python:
There's a waiting room with N chairs set in single row. Chairs are consecutively numbered from 1 to N. First is closest to the entrance (which is exit as well).

For some reason people choose a chair in the following way

1. Find a place as far from other people as possible
2. Find a place as close to exit as possible

All chairs must be occupied before the first person will be served

So it looks like this for 10 chairs and 10 patients

Chairs
1
2
3
4
5
6
7
8
9
10

Patients
1
7
5
8
3
9
4
6
10
2

Your task is to find last patient's chair's number.

Input - N - integer greater than 2 - number of chairs.
Output should positive integer too - last patient's chair's number

Have fun :)


Solve in Python:
There's an array A consisting of N non-zero integers A1..N. A subarray of A is called alternating if any two adjacent elements in it have different signs (i.e. one of them should be negative and the other should be positive).

For each x from 1 to N, compute the length of the longest alternating subarray that starts at x - that is, a subarray Ax..y for the maximum possible y ≥ x. The length of such a subarray is y-x+1.

-----Input-----
- The first line of the input contains an integer T - the number of test cases.
- The first line of each test case contains N.
- The following line contains N space-separated integers A1..N.

-----Output-----
For each test case, output one line with N space-separated integers - the lengths of the longest alternating subarray starting at x, for each x from 1 to N.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- -109 ≤ Ai ≤ 109

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

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

-----Explanation-----
Example case 1. No two elements have different signs, so any alternating subarray may only consist of a single number.
Example case 2. Every subarray is alternating.
Example case 3. The only alternating subarray of length 3 is A3..5.

t=int(input())
while(t):
 t-=1
 n=int(input())
 a=list(map(int,input().strip().split(" ")))
 a=a[::-1]
 arr=[1]
 for i in range(1,n):
  if (a[i-1]<0 and a[i]>=0) or (a[i-1]>=0 and a[i]<0):
   arr.append(1+arr[i-1])
  else:
   arr.append(1)

 print(' '.join(str(i) for i in arr[::-1]))


Solve in Python:
These days, chef is very much interested in Mathematics. He has started attending Recitations too! His hunger for problems is increasing day by day!
Today, chef was a given a crumpled maths problem, which he is stuck with . He needs your help to do it
Here's what his teacher said: "Find sum of all numbers till N, do not include numbers which are powers of K from K, K2, K3... which are less than or equal to N"
Easy, right? Can you solve it?

-----INPUT-----
The first line of the input contains an integer T, denoting the number of test cases. The description of T test cases follows. The first line of each test contains two integers N and K, as per the above given problem specification.

-----OUTPUT-----
For each test case, output a single line printing the sum of the each test case, in format Case #T: S, where T is the Tth test case running and S is sum of corresponding test case.

-----CONSTRAINTS-----

10 < T < 50

10 < N < 104

0 < K < 100

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

2

10 3

20 2

Output:

Case #1: 43

Case #2: 180

for j in range(int(input())):
 n,k = list(map(int, input().split()))
 s = (n*(n+1))/2
 i = k
 while i<=n:
  s -= i
  i *= k
 print("Case #%d: %d" % (j+1, s))


Solve in Python:
Think about Zuma Game. You have a row of balls on the table, colored red(R), yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.

Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.

Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.

Examples:
Input: "WRRBBW", "RB"
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW

Input: "WWRRBBWW", "WRBRW"
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty

Input:"G", "GGGGG"
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty

Input: "RBYYBBRRB", "YRBGB"
Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty

Note:

You may assume that the initial row of balls on the table won’t have any 3 or more consecutive balls with the same color.
The number of balls on the table won't exceed 20, and the string represents these balls is called "board" in the input.
The number of balls in your hand won't exceed 5, and the string represents these balls is called "hand" in the input.
Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.

class Solution:
     def findMinStep(self, board, hand):
         """
         :type board: str
         :type hand: str
         :rtype: int
         """
         res=float("inf")
         hmap=collections.defaultdict(int)
         for c in hand:
             hmap[c]+=1
         res=self.helper(board,hmap)
         if res == float("inf"):
             return -1
         return res

     def helper(self,board,hmap):
         board=self.removeConsecutive(board)
         if len(board) ==0:
             return 0
         cnt=float("inf")
         j=0
         for i in range(len(board)+1):
             if i<len(board) and board[i] ==board[j]:
                 continue
             need=3-(i-j)
             if hmap[board[j]]>=need:
                 hmap[board[j]]-=need
                 res=self.helper(board[0:j]+board[i:],hmap)
                 if res!=float("inf"):
                     cnt=min(cnt,res+need)
                 hmap[board[j]]+=need
             j=i
         return cnt

     def removeConsecutive(self,board):
         j=0
         for i in range(len(board)+1):
             if i<len(board) and board[i] ==board[j]:
                 continue
             if i-j>=3:
                 return self.removeConsecutive(board[0:j]+board[i:])
             else:
                 j=i
         return board


Solve in Python:
Third day at your new cryptoanalyst job and you come across your toughest assignment yet. Your job is to implement a simple keyword cipher. A keyword cipher is a type of monoalphabetic substitution where two parameters are provided as such (string, keyword). The string is encrypted by taking the keyword, dropping any letters that appear more than once. The rest of the letters of the alphabet that aren't used are then appended to the end of the keyword.

For example, if your string was "hello" and your keyword was "wednesday", your encryption key would be 'wednsaybcfghijklmopqrtuvxz'.

To encrypt 'hello' you'd substitute as follows,
```
              abcdefghijklmnopqrstuvwxyz
  hello ==>   |||||||||||||||||||||||||| ==> bshhk
              wednsaybcfghijklmopqrtuvxz

```

hello encrypts into bshhk with the keyword wednesday. This cipher also uses lower case letters only.

Good Luck.

import string
def keyword_cipher(msg, keyword):
    s = []
    for i in keyword.lower():
        if i not in s:
            s.append(i)
    return msg.lower().translate(str.maketrans(string.ascii_lowercase, ''.join(s + [i for i in string.ascii_lowercase if i not in keyword]).lower()))


Solve in Python:
This Kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fusc-function-part-1). The `fusc` function is defined recursively as follows:

    fusc(0) = 0
    fusc(1) = 1
    fusc(2n) = fusc(n)
    fusc(2n + 1) = fusc(n) + fusc(n + 1)

Your job is to produce the code for the `fusc` function. In this kata, your function will be tested with large values of `n` more than 1000 bits (in JS and PHP: at most 52 bits), so you should be concerned about stack overflow and timeouts.

Method suggestion:

Imagine that instead of `fusc(n)`, you were to implement `fib(n)`, which returns the n'th Fibonacci number.

The function is recursively defined by:

```
1.    fib(0) = 1
2.    fib(1) = 1
3.    fib(n + 2) = fib(n) + fib(n + 1), if n + 2 > 1
```
If one translates the above definition directly into a recursive function, the result is not very efficient. One can try memoization, but that requires lots of space and is not necessary. So, first step is to try and find a _tail recursive_ definition. In order to do that we try to write both sides of equation 3) on the same form. Currently, the left side of the equation contains a single term, whereas the right side is the sum of two terms. A first attempt is to add `fib(n + 1)` to both sides of the equation:
```
3.    fib(n + 1) + fib(n + 2) = fib(n) + 2 * fib(n + 1)
```
The two sides of the equation look much more alike, but there is still an essential difference, which is the coefficient of the second term of each side. On the left side of the equation, it is `1`  and, on the right, it is `2`. To remedy this, we can introduce a variable `b`:
```
3.    fib(n + 1) + b * fib(n + 2) = b * fib(n) + (b + 1) * fib(n + 1)
```
We notice that the coefficients of the first term are not the same (`1` on the left and `b` on the right), so we introduce a variable `a`:
```
3.    a * fib(n + 1) + b * fib(n + 2) = b * fib(n) + (a + b) * fib(n + 1)
```
Now the two sides have the same form (call it `F`), which we can define as:

```F(a, b, n) = a * fib(n) + b * fib(n +...

def fusc(n):
    s = [1,0]
    for i in map(int, bin(n)[2:]):
        s[i]+=s[1-i]
    return s[1]


Solve in Python:
This Kata is the first in the [Rubiks Cube collection](https://www.codewars.com/collections/rubiks-party).

[This](https://ruwix.com/the-rubiks-cube/notation/) or [this](https://ruwix.com/the-rubiks-cube/notation/advanced/) websites will be very usefull for this kata, if there will be some lack of understanding after the description. There are plenty of examples and a 3D model that can perform all needed rotations.

In this Kata you will give the cube the ability to rotate.

The Rubik's Cube is made of six faces. F(ront), L(eft), R(ight), B(ack), U(p), D(own)

Below a two dimensional representation of the cube.
```
      +-----+
      |     |
      |  U  |
      |     |
+-----+-----+-----+-----+
|     |     |     |     |
|  L  |  F  |  R  |  B  |
|     |     |     |     |
+-----+-----+-----+-----+
      |     |
      |  D  |
      |     |
      +-----+
```

On every face you can see nine stickers. Every sticker can be one of the six colors: Yellow, Blue, Red, Green, Orange, White. In this Kata they are represented with according small letters (y, b, r, g, o, w,).

A solved cube has on every face only one color:
```
      +-----+
      |y y y|
      |y y y|
      |y y y|
+-----+-----+-----+-----+
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
+-----+-----+-----+-----+
      |w w w|
      |w w w|
      |w w w|
      +-----+
```
Every sticker on a face in this Kata has a positional number
```
+-----+
|1 2 3|
|4 5 6|
|7 8 9|
+-----+
```
So the state of the face could be represented in a 9 character string consisting of the possible colors.
```
+-----+
|y r b|
|o o w|   state == "yrboowygb"
|y g b|
+-----+
```
So a state of the cube is a 54 character long string consisting of the state of every face in this order: U L F R B D
```
      +-----+
      |y y y|
      |y y y|      state == "yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww"
      |y y y|
+-----+-----+-----+-----+
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
+-----+-----+-----+-----+
 ...


Solve in Python:
This calculator takes values that could be written in a browsers route path as a single string. It then returns the result as a number (or an error message).

Route paths use the '/' symbol so this can't be in our calculator. Instead we are using the '$' symbol as our divide operator.

You will be passed a string of any length containing numbers and operators:

* '+' = add
* '-' = subtract
* '*' = multiply
* '$' = divide

Your task is to break the string down and calculate the expression using this order of operations. (division => multiplication => subtraction => addition)

If you are given an invalid input (i.e. any character except `.0123456789+-*$`) you should return the error message:`'400: Bad request'`

### Remember:

1. Operations are infinite
2. Order of operations is imperitive
3. No `eval` or equivalent functions

**Examples:**
```python
calculate('1+1')     => '2'
calculate('10$2')    => '5'
calculate('1.5*3')   => '4.5'

calculate('5+5+5+5') => '20'

calculate('1000$2.5$5+5-5+6$6') =>'81'

calculate('10-9p')   =>  '400: Bad request'
```

### Further Notes - Parameters outside of this challenge:

- Brackets e.g. 10*(1+2)
- Square root, log, % or any other operators
- Unary minus (10*-1)
- Bad mathematical input (10**$10 or 5+5$)
- You may have to deal with floats

If enjoy this and want something harder please see http://www.codewars.com/kata/evaluate-mathematical-expression/ for making a much more complicated calculator. This is a good kata leading up to that.

def calculate(expression):
    print(expression)
    expression = "".join([" {} ".format(num) if num in "+-*$" else num for num in expression]).split()
    while '$' in expression:
        try:
            for num in expression:
                if num == '$':
                    first = expression.pop(expression.index(num)-1)
                    second = expression.pop(expression.index(num)+1)
                    ans = str(float(float(first)/float(second)))
                    expression[expression.index(num)] = ans
        except ValueError:
            return '400: Bad request'
    while '*' in expression:
        try:
            for num in expression:
                if num == '*':
                    first = expression.pop(expression.index(num)-1)
                    second = expression.pop(expression.index(num)+1)
                    ans = str(float(float(first)*float(second)))
                    expression[expression.index(num)] = ans
        except ValueError:
            return '400: Bad request'
    while '-' in expression:
        try:
            for num in expression:
                if num == '-':
                    first = expression.pop(expression.index(num)-1)
                    second = expression.pop(expression.index(num)+1)
                    ans = str(float(float(first)-float(second)))
                    expression[expression.index(num)] = ans
        except ValueError:
            return '400: Bad request'
    while '+' in expression:
        try:
            for num in expression:
                if num == '+':
                    first = expression.pop(expression.index(num)-1)
                    second = expression.pop(expression.index(num)+1)
                    ans = str(float(float(first)+float(second)))
                    expression[expression.index(num)] = ans
        except ValueError:
            return '400: Bad request'
    try:
        return float(expression[0])
    except ValueError:
        return '400: Bad request'


Solve in Python:
This challenge extends the previous [repeater()](https://www.codewars.com/kata/thinkful-string-drills-repeater) challenge. Just like last time, your job is to write a function that accepts a string and a number as arguments. This time, however, you should format the string you return like this:
```python
>>> repeater('yo', 3)
'"yo" repeated 3 times is: "yoyoyo"'
>>> repeater('WuB', 6)
'"WuB" repeated 6 times is: "WuBWuBWuBWuBWuBWuB"'
```

def repeater(string, n):
    # Habit of escaping double quotes regardless of context
    return '"{}" repeated {} times is: "{}"'.format(string, n, string * n)


Solve in Python:
This challenge is an extension of the kata of Codewars: **Missing and Duplicate Number"**, authored by the user **Uraza**. (You may search for it and complete it if you have not done it)

In this kata, we have an unsorted sequence of consecutive numbers from  ```a``` to ```b```, such that ```a < b``` always (remember ```a```, is the minimum, and ```b``` the maximum value).

They were introduced an unknown amount of duplicates in this sequence and we know that there is an only missing value such that all the duplicate values and the missing value are between ```a``` and ```b```, but never coincide with them.

Find the missing number with the duplicate numbers (duplicates should be output in a sorted array).

Let's see an example:

```arr = [10,9,8,9,6,1,2,4,3,2,5,5,3]```

```find_dups_miss([10,9,8,9,6,1,2,4,3,2,5,5,3]) == [7,[2,3,5,9]]```

The code should be fast to process long arrays (maximum length aprox. = 1.000.000).
The values for the randon tests:
```
500 <= a <= 50000
a + k <= b and 100 <= k <= 1000000
amount of duplicates variable, according to the length of the array
```

from collections import Counter

def find_dups_miss(arr):
    c = Counter(arr)
    return [next(i for i in range(min(c), max(c)) if i not in c), sorted(x for x in c if c[x] > 1)]


Solve in Python:
This challenge is based on [the kata](https://www.codewars.com/kata/n-smallest-elements-in-original-order) by GiacomoSorbi. Before doing this one it is advisable to complete the non-performance version first.

___

# Task

You will be given an array of random integers and a number `n`. You have to extract `n` smallest integers out of it **preserving the original order**.

# Examples

```python
performant_smallest([1, 2, 3, 4, 5], 3)     ==   [1, 2, 3]
performant_smallest([5, 4, 3, 2, 1], 3)     ==   [3, 2, 1]
performant_smallest([1, 2, 3, 4, 1], 3)     ==   [1, 2, 1]
performant_smallest([2, 1, 3, 2, 3], 3)     ==   [2, 1, 2]
```

# Notes

* There will be duplicates in the array, and they have to be returned in the order of their each separate appearence.
* This kata is an example of the "know your data" principle. Remember this while searching for the correct approach.

# Performance tests

```python
Tests: 15
Array size: 800,000
Values range: [1; 50]
Number of elements to return: 25-50% of the array
```

import numpy as np

def performant_smallest(arr, n):
    return np.asarray(arr)[np.sort(np.argsort(arr, kind='mergesort')[:n])].tolist()


Solve in Python:
This function should take two string parameters: a person's name (`name`) and a quote of theirs (`quote`), and return a string attributing the quote to the person in the following format:

```python
'[name] said: "[quote]"'
```

For example, if `name` is `'Grae'` and `'quote'` is `'Practice makes perfect'` then your function should return the string
```python
'Grae said: "Practice makes perfect"'
```
Unfortunately, something is wrong with the instructions in the function body. Your job is to fix it so the function returns correctly formatted quotes.

Click the "Train" button to get started, and be careful with your quotation marks.

def quotable(name, quote):
    return '{} said: "{}"'.format(name, quote)


Solve in Python:
This function should test if the `factor` is a factor of `base`.

Return `true` if it is a factor or `false` if it is not.

## About factors
Factors are numbers you can multiply together to get another number.

2 and 3 are factors of 6 because: `2 * 3 = 6`

- You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor.
- You can use the mod operator (`%`) in most languages to check for a remainder

For example 2 is not a factor of 7 because: `7 % 2 = 1`

Note: `base` is a non-negative number, `factor` is a positive number.

def check_for_factor(base, factor):
    remainder = base % factor
    if remainder > 0:
        return False
    else:
        return True


Solve in Python:
This function takes two numbers as parameters, the first number being the coefficient, and the second number being the exponent.

Your function should multiply the two numbers, and then subtract 1 from the exponent. Then, it has to print out an expression (like 28x^7). `"^1"` should not be truncated when exponent = 2.

For example:
```
derive(7, 8)
```
In this case, the function should multiply 7 and 8, and then subtract 1 from 8. It should output `"56x^7"`, the first number 56 being the product of the two numbers, and the second number being the exponent minus 1.

```
derive(7, 8) --> this should output "56x^7"
derive(5, 9) --> this should output "45x^8"
```

**Notes:**
* The output of this function should be a string
* The exponent will never be 1, and neither number will ever be 0

def derive(a, b):
    x = a*b
    y = b-1
    return f'{x}x^{y}'


Solve in Python:
This is a beginner friendly kata especially for UFC/MMA fans.

It's a fight between the two legends: Conor McGregor vs George Saint Pierre in Madison Square Garden. Only one fighter will remain standing, and after the fight in an interview with Joe Rogan the winner will make his legendary statement. It's your job to return the right statement depending on the winner!

If the winner is George Saint Pierre he will obviously say:
- "I am not impressed by your performance."

If the winner is Conor McGregor he will most undoubtedly say:
- "I'd like to take this chance to apologize.. To absolutely NOBODY!"

Good Luck!

def quote(fighter):
    if fighter == 'george saint pierre':
        return "I am not impressed by your performance."
    if fighter == 'Conor McGregor':
        return "I'd like to take this chance to apologize.. To absolutely NOBODY!"
    if fighter == 'George Saint Pierre':
        return "I am not impressed by your performance."
    if fighter == 'conor mcgregor':
        return "I'd like to take this chance to apologize.. To absolutely NOBODY!"