Solve in Python:
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.

The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $N$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves:  Take one gold coin from the chest.  Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even.

Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.

-----Input-----

The first line contains a single integer $T$ $(1 \le T \le 10^5)$ denotes the number of test cases.

The next $T$ lines each contain a single integer $N$ $(1 \le N \le 10^{18})$.

-----Output-----

$T$ lines, each line is the answer requested by Mr. Chanek.

-----Example-----
Input
2
5
6

Output
2
4

-----Note-----

For the first case, the game is as follows:   Mr. Chanek takes one coin.  The opponent takes two coins.  Mr. Chanek takes one coin.  The opponent takes one coin.

For the second case, the game is as follows:   Mr. Chanek takes three coins.  The opponent takes one coin.  Mr. Chanek takes one coin.  The opponent takes one coin.

from sys import stdin
input = stdin.readline

def max_pos_coins(n):
	a = 0
	while n != 0:
		if n == 4:
			a += 3
			n = 0
			continue
		if n % 4 == 0:
			n -= 2
			a += 1
		else:
			a += n // 2
			n = n // 2 - 1
	return a

for _ in range(int(input())):
	n = int(input())
	print(max_pos_coins(n) if n % 2 == 0 else n - max_pos_coins(n - 1))


Solve in Python:
Laura Bassi was the first female professor at a European university.
Despite her immense intellect, she was not always allowed to lecture publicly.

One day a professor with very strong beliefs against women in academia sent some `agents` to find Bassi and end her career.

Help her escape by telling her the safest places in town!

Task

```if:python,javascript
Implement the function `advice(agents, n)` where
```
```if:haskell
Implement the function `advice agents n :: [(Int,Int)] -> Int -> [(Int,Int)]` where
```
```if:swift
Implement the function `advice(agents: [[Int]], n: Int) -> [[Int]]` where
```

- `agents` is an array of agent coordinates.
- `n` defines the size of the city that Bassi needs to hide in, in other words the side length of the square grid.

The function should return a list of coordinates that are the furthest away (by Manhattan distance) from all agents.

As an example, say you have a 6x6 map, and agents at locations

```python
[(0, 0), (1, 5), (5, 1)]
```

The distances to the nearest agent look like this.

The safest spaces are the ones with distance `4`, marked in bright red. So the function should return

```python
[(2, 2), (3, 3), (4, 4), (5, 5)]
```

in any order.

Edge cases:
- If there is an agent on every grid cell, there is no safe space, so return an empty list.
- If there are no agents, then every cell is a safe spaces, so return all coordinates.
- if `n` is `0`, return an empty list.
- If agent coordinates are outside of the map, they are simply not considered.
- There are no duplicate agents on the same square.

Performance

All reference solutions run in around 6 seconds.
You might not pass the tests if you use a brute-force solution.

```if-not:swift,javascript
There are `200` random tests with `n <= 50`. Inefficient solutions might time out.
```
```if:javascript
There are `300` random tests with `n <= 70`. Inefficient solutions might time out.
```
```if:swift
There are `200` random tests with `n <= 70`. Inefficient solutions might time out.
```

This kata is inspired...

def advice(agents, n):
    if n <= 0:
        return []
    city = [[-1] * n for _ in range(n)]
    agents = [(i, j) for (i, j) in agents if i >= 0 and j >= 0 and i < n and j < n]
    d = 0
    while agents:
        t = []
        for i, j in agents:
            city[i][j] = d
        d += 1
        for i, j in agents:
            for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                x, y = i + di, j + dj
                if x < 0 or y < 0 or x >= n or y >= n or city[x][y] >= 0:
                    continue
                city[x][y] = d
                t.append((x, y))
        agents = t
    m = max(max(r) for r in city)
    return [(i, j) for i in range(n) for j in range(n) if city[i][j] == m] if m != 0 else []


Solve in Python:
Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present.

Any combination of three or more letters in upper case will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string.

For any string:

All instances of 'KPI' must become "key performance indicators"
All instances of 'EOD' must become "the end of the day"
All instances of 'TBD' must become "to be decided"
All instances of 'WAH' must become "work at home"
All instances of 'IAM' must become "in a meeting"
All instances of 'OOO' must become "out of office"
All instances of 'NRN' must become "no reply necessary"
All instances of 'CTA' must become "call to action"
All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats"
If there are any unknown acronyms in the string, Laura wants you to return only the message:
'[acronym] is an acronym. I do not like acronyms. Please remove them from your email.'
So if the acronym in question was 'BRB', you would return the string:
'BRB is an acronym. I do not like acronyms. Please remove them from your email.'
If there is more than one unknown acronym in the string, return only the first in your answer.

If all acronyms can be replaced with full words according to the above, however, return only the altered string.

If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used.

import re

D = {"KPI": "key performance indicators",
     "EOD": "the end of the day",
     "TBD": "to be decided",
     "WAH": "work at home",
     "IAM": "in a meeting",
     "OOO": "out of office",
     "NRN": "no reply necessary",
     "CTA": "call to action",
     "SWOT": "strengths, weaknesses, opportunities and threats"}

acronym = re.compile(r"(?:^|(?<=\W))[A-Z]{3,}(?=\W|$)")
capital = re.compile(r"(?:^|(?<=\.\s))[a-z]")

def acronym_buster(message):
    try:
        return capital.sub(lambda w: w.group().upper(), acronym.sub(lambda w: D[w.group()], message))
    except Exception as e:
        return f"{str(e)[1:-1]} is an acronym. I do not like acronyms. Please remove them from your email."


Solve in Python:
Lavanya and Nikhil have K months of holidays ahead of them, and they want to go on exactly K road trips, one a month. They have a map of the various cities in the world with the roads that connect them. There are N cities, numbered from 1 to N. We say that you can reach city B from city A if there is a sequence of roads that starts from city A and ends at city B. Note that the roads are bidirectional. Hence, if you can reach city B from city A, you can also reach city A from city B.
Lavanya first decides which city to start from. In the first month, they will start from that city, and they will visit every city that they can reach by road from that particular city, even if it means that they have to pass through cities that they have already visited previously. Then, at the beginning of the second month, Nikhil picks a city that they haven't visited till then. In the second month, they first fly to that city and visit all the cities that they can reach from that city by road. Then, in the third month, Lavanya identifies a city, and they fly there and visit all cities reachable from there by road. Then in the fourth month it is Nikhil's turn to choose an unvisited city to start a road trip, and they alternate like this. Note that the city that they fly to (that is, the city from where they start each month's road trip) is also considered as being visited.
Each city has some museums, and when they visit a city for the first time, Lavanya makes them visit each of the museums there. Lavanya loves going to museums, but Nikhil hates them. Lavanya always makes her decisions so that they visit the maximum number of museums possible that month, while Nikhil picks cities so that the number of museums visited that month is minimized.
Given a map of the roads, the number of museums in each city, and the number K, find the total number of museums that they will end up visiting at the end of K months. Print -1 if they will have visited all the cities before the beginning of the Kth month, and hence they will be left bored...

t = int(input())
while(t):
 t -= 1
 n, m, k = list(map(int, input().split()))
 g = []
 for i in range(1000001):
  g.append([])
 while(m):
  m -= 1
  x, y = list(map(int, input().split()))
  g[x].append(y)
  g[y].append(x)
 a = [0] + list(map(int, input().split()))
 ans = []
 vis = [0]*1000001
 for i in range(1, n+1):
  if(vis[i] == 0):
   vis[i] = 1
   val = a[i]
   bfsQ = [i]
   while(bfsQ):
    x = bfsQ[0]
    del bfsQ[0]
    for y in g[x]:
     if(vis[y] == 0):
      val += a[y]
      vis[y] = 1
      bfsQ.append(y)
   ans.append(val)
 ans = sorted(ans)
 if(k>len(ans)):
  print(-1)
 else:
  print(sum(ans[:k//2]) + sum(ans[len(ans)-(k-k//2):]))


Solve in Python:
Laxman, a great Mathematician and Thinker, gives Sugreev an integer, $N$, and asks him to make an array $A$ of length $N$, such that  $\sum A$i$^3 = X^2$, to prove the purity of the bond of his friendship with Ram. Sugreev is facing difficulty in forming the array. So, help Sugreev to form this array.

-----Note:-----
- $A$i must be an integer between $1$ to $10^3$ (both inclusive), where $A$i denotes the $i$$th$ element of the array, $A$.
- $X$ must be an integer (Any Integer).
- If there are multiple solutions, satisfying the condition, you can print any "one" solution.

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

-----Output:-----
For each testcase, output in a single line, array $A$ of $N$ integers, where each element is between $1$ to $1000$ (both inclusive), satisfying the equation $\sum A$i$^3 = X^2$, where $X$ is "any" integer.

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

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

-----Sample Output:-----
4
5 10 5 10 5 5

# cook your dish here
t = int(input())

while(t>0):
    n = int(input())
    k=1
    while(k<=n):
        print(k, end=' ')
        k+=1
    print('\n')
    t-=1


Solve in Python:
Learning to code around your full time job is taking over your life. You realise that in order to make significant steps quickly, it would help to go to a coding bootcamp in London.

Problem is, many of them cost a fortune, and those that don't still involve a significant amount of time off work - who will pay your mortgage?!

To offset this risk, you decide that rather than leaving work totally, you will request a sabbatical so that you can go back to work post bootcamp and be paid while you look for your next role.

You need to approach your boss. Her decision will be based on three parameters:

val=your value to the organisation
happiness=her happiness level at the time of asking and finally
The numbers of letters from 'sabbatical' that are present in string `s`.

Note that if `s` contains three instances of the letter 'l', that still scores three points, even though there is only one in the word sabbatical.

If the sum of the three parameters (as described above) is > 22, return 'Sabbatical! Boom!', else return 'Back to your desk, boy.'.

~~~if:c
NOTE: For the C translation you should return a string literal.
~~~

def sabb(s, value, happiness):
    return 'Sabbatical! Boom!' if sum(1 for x in s if x.lower() in 'sabbatical') + value + happiness > 22 else 'Back to your desk, boy.'


Solve in Python:
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...

Lee thinks a regular $n$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $OX$-axis and at least one of its edges is parallel to the $OY$-axis at the same time.

Recall that a regular $n$-sided polygon is a convex polygon with $n$ vertices such that all the edges and angles are equal.

Now he is shopping: the market has $t$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of polygons in the market.

Each of the next $t$ lines contains a single integer $n_i$ ($3 \le n_i \le 10^9$): it means that the $i$-th polygon is a regular $n_i$-sided polygon.

-----Output-----

For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).

-----Example-----
Input
4
3
4
12
1000000000

Output
NO
YES
YES
YES

-----Note-----

In the example, there are $4$ polygons in the market. It's easy to see that an equilateral triangle (a regular $3$-sided polygon) is not beautiful, a square (a regular $4$-sided polygon) is beautiful and a regular $12$-sided polygon (is shown below) is beautiful as well. [Image]

import sys

def ii():
    return sys.stdin.readline().strip()

def idata():
    return [int(x) for x in ii().split()]

def solve():
    n = int(ii())
    if n % 4 == 0:
        print('YES')
    else:
        print('NO')
    return

for t in range(int(ii())):
    solve()


Solve in Python:
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $n$ integers, now it's time to distribute them between his friends rationally...

Lee has $n$ integers $a_1, a_2, \ldots, a_n$ in his backpack and he has $k$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $i$-th friend will get exactly $w_i$ integers and each integer will be handed over to exactly one friend.

Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.

Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.

-----Input-----

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

Next $3t$ lines contain test cases — one per three lines.

The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$; $1 \le k \le n$) — the number of integers Lee has and the number of Lee's friends.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$) — the integers Lee has.

The third line contains $k$ integers $w_1, w_2, \ldots, w_k$ ($1 \le w_i \le n$; $w_1 + w_2 + \ldots + w_k = n$) — the number of integers Lee wants to give to each friend.

It's guaranteed that the sum of $n$ over test cases is less than or equal to $2 \cdot 10^5$.

-----Output-----

For each test case, print a single integer — the maximum sum of happiness Lee can achieve.

-----Example-----
Input
3
4 2
1 13 7 17
1 3
6 2
10 10 10 10 11 11
3 3
4 4
1000000000 1000000000 1000000000 1000000000
1 1 1 1

Output
48
42
8000000000

-----Note-----

In the first test case, Lee should give the greatest integer to the first friend (his happiness will be $17 + 17$) and remaining integers to the second friend (his happiness will be $13 + 1$).

In the second test case, Lee should give $\{10, 10,...

from sys import stdin, stdout
import math

t = int(stdin.readline())
for _ in range(t):
    n, k = list(map(int, stdin.readline().split()))
    a = list(map(int, stdin.readline().split()))
    w = list(map(int, stdin.readline().split()))

    a = sorted(a)
    w = sorted(w)
    st, end = 0, n-1
    ans = 0
    idx = 0
    while idx < k and w[idx] == 1:
        ans += a[end]*2
        end -= 1
        idx += 1
    for i in range(k-1, idx-1, -1):
        wi = w[i]
        ans += a[st] + a[end]
        end -= 1
        st += wi-1
    print(ans)


Solve in Python:
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...

The string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s).

In one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.

Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.

Now you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.

Small reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$.

-----Input-----

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

Next $2t$ lines contain test cases — one per two lines.

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

The second line contains the binary string $s$. The string $s$ is a string of length $n$ which consists only of zeroes and ones.

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

-----Output-----

Print $t$ answers — one per test case.

The answer to the $i$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).

-----Example-----
Input
5
10
0001111111
4
0101
8
11001101
10
1110000000
1
1

Output
0001111111
001
01
0
1

-----Note-----

In the first test case, Lee can't perform any moves.

In the second test...

for _ in range(int(input())):
    # a, b = map(int, input().split())
    n = int(input())
    # arr = list(map(int, input().split()))
    s = input()
    l = 0
    r = n - 1
    if s.count('0') == n:
        print(s)
        continue
    if s.count('1') == n:
        print(s)
        continue
    while s[l] == '0':
        l += 1
    while s[r] == '1':
        r -= 1
    if r <= l:
        print(s)
        continue
    print(l * '0' + '0' + (n - r - 1) * '1')


Solve in Python:
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.
You are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.
Access times are given in the 24-hour time format "HH:MM", such as "23:51" and "09:49".
Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.
Notice that "10:00" - "11:00" is considered to be within a one-hour period, while "22:51" - "23:52" is not considered to be within a one-hour period.

Example 1:
Input: keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]
Output: ["daniel"]
Explanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").

Example 2:
Input: keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]
Output: ["bob"]
Explanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30").

Example 3:
Input: keyName = ["john","john","john"], keyTime = ["23:58","23:59","00:01"]
Output: []

Example 4:
Input: keyName = ["leslie","leslie","leslie","clare","clare","clare","clare"], keyTime = ["13:00","13:20","14:00","18:00","18:51","19:30","19:49"]
Output: ["clare","leslie"]

Constraints:

1 <= keyName.length, keyTime.length <= 105
keyName.length == keyTime.length
keyTime are in the format "HH:MM".
[keyName[i], keyTime[i]] is unique.
1 <= keyName[i].length <= 10
keyName[i] contains only lowercase English letters.

class Solution:
    def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:
        from collections import defaultdict

        key_pairs = [(time, name) for name, time in zip(keyName, keyTime)]
        key_pairs.sort()
        keys = defaultdict(list)
        names = set()
        for pair in key_pairs:
            time, name = pair
            if name in names:
                continue

            keys[name].append(time)

            if len(keys[name]) < 3:
                continue

            hour, minute = time.split(':')
            hour, minute = int(hour), int(minute)
            first_access_time = keys[name][-3]
            first_hour, first_minute = first_access_time.split(':')
            first_hour, first_minute = int(first_hour), int(first_minute)
            if hour - first_hour <= 1:
                if hour - first_hour == 1:
                    if minute - first_minute > 0:
                        continue
                    else:
                        names.add(name)
                else:
                    names.add(name)
        res = list(names)
        res.sort()

        return res


Solve in Python:
Leha is a bright mathematician. Today he is investigating whether an integer is divisible by some square number or not.
He has a positive integer X represented as a product of N integers a1, a2, .... aN. He has somehow figured out that there exists some integer P such that the number X is divisible by P2, but he is not able to find such P himself. Can you find it for him? If there are more than one possible values of P possible, you can print any one of them.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. T test cases follow.
The first line of each test case contains one integer N denoting the number of intgers in presentation of X.
The second line contains N space-separated integers a1, a2, .... aN.

-----Output-----
For each test case, output a single integer P deoting the answer for this test case. Note that P must be in range from 2 to 1018 inclusive. It's guaranteed that at least one answer exists. If there are more than one possible answers, print any.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 100
- 1 ≤ ai ≤ 1018

-----Subtasks-----
- Subtask 1[19 points]: 1 ≤ a1*a2*...*aN ≤ 106
- Subtask 2[22 points]: 1 ≤ a1*a2*...*aN ≤ 1012
- Subtask 3[23 points]: 1 ≤ ai ≤ 1012
- Subtask 4[36 points]: no additional constraints

-----Example-----
Input:
1
3
21 11 6

Output:
3

-----Explanation-----
Example case 1. X = 21 * 11 * 6 = 1386. It's divisible by 9 which is a square number, as 9 = 32. So P = 3.

import math
for i in range(int(input())):
 y=int(input())
 x=list(map(int,input().split()))
 p=1
 for j in x:
  p=p*j

 m=max(x)

 r=1

 for k in range(2,m):

  if p%k**2==0:
   r=k
   break
 print(r)


Solve in Python:
Leha is a usual student at 'The Usual University for Usual Students'. Sometimes he studies hard; at other times he plays truant and gets busy with other things besides academics. He has already studied at the university for N months. For the ith month (1 ≤ i ≤ N), he has received some non-negative integer grade A[i].
Now he wants to analyse his progress for some periods of his university education. An arbitrary period, defined by two positive integers L and R, begins at Leha's Lth month at the university and ends at the Rth. The analysis is performed via the following steps.

1. Write down all the grades for each month from L to R and sort them. Let's call the sorted list S.

2. Calculate the sum of squared differences of consecutive elements in S, that is, (S[2] - S[1])2 + (S[3] - S[2])2 + ... + (S[R-L+1] - S[R-L])2.

-----Input-----
The first line contains one integer N — the number of months Leha has already studied at the university.
The second line contains N integers — list A of Leha's grades.
The third line contains one integer M — the number of periods Leha is interested in analyzing.
Each of the following M lines contain two integers L and R describing each period.

-----Output-----
For each query, output one integer — the result of the progress analysis for the corresponding period.

-----Constraints-----
- 1 ≤ N, M ≤ 5*104
- 0 ≤ A[i] ≤ 106

-----Subtasks-----
- Subtask 1 (19 points) 1 ≤ N, M ≤ 200, time limit = 2 sec
- Subtask 2 (31 points) 1 ≤ N, M ≤ 10 000, time limit = 2 sec
- Subtask 3 (26 points) 0 ≤ A[i] ≤ 100, time limit = 5 sec
- Subtask 4 (24 points) no additional constraints, , time limit = 5 sec

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

Output:4
3
2
0
5

Explanation

The first query: sorted array looks like (1, 2, 3, 4, 5) and the answer is calculated as (2-1)2 + (3-2)2 + (4-3)2 + (5-4)2 = 4

The second query: sorted array looks like (1, 2, 3, 4) and the answer is calculated as (2-1)2 + (3-2)2 + (4-3)2 = 3

The last query: sorted array looks like (2, 4, 5) and the...

n=eval(input())
a=list(map(int,input().split()))
for i in range(eval(input())):
 l,r=(int(x) for x in input().split())
 b=a[l-1:r]
 b.sort()
 sum=0
 for i in range(1,len(b)):
  j=b[i]-b[i-1]
  sum+=pow(j,2)
 print(sum)


Solve in Python:
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.

But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition A_{i} ≥ B_{j} holds. Help Leha rearrange the numbers in the array A so that the sum $\sum_{i = 1}^{m} F(A_{i}^{\prime}, B_{i})$ is maximally possible, where A' is already rearranged array.

-----Input-----

First line of input data contains single integer m (1 ≤ m ≤ 2·10^5) — length of arrays A and B.

Next line contains m integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — array A.

Next line contains m integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 10^9) — array B.

-----Output-----

Output m integers a'_1, a'_2, ..., a'_{m} — array A' which is permutation of the array A.

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

Output
4 7 3 5 3

Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2

Output
2 6 4 5 8 8 6

n=int(input())
a=list(map(int,input().strip().split(' ')))
b=list(map(int,input().strip().split(' ')))
c=[]
a.sort(reverse=True)
for i in range(n):
    d=[]
    d.append(b[i])
    d.append(i)
    c.append(d)
c = sorted(c)
d=[0 for i in range(n)]
for i in range(n):
    d[c[i][1]]=a[i]
for i in range(n):
    print(d[i],end=' ')


Solve in Python:
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer d_{i}, which can be equal to 0, 1 or  - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, d_{i} =  - 1 or it's degree modulo 2 is equal to d_{i}. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.

-----Input-----

The first line contains two integers n, m (1 ≤ n ≤ 3·10^5, n - 1 ≤ m ≤ 3·10^5) — number of vertices and edges.

The second line contains n integers d_1, d_2, ..., d_{n} ( - 1 ≤ d_{i} ≤ 1) — numbers on the vertices.

Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected.

-----Output-----

Print  - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.

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

Output
-1

Input
4 5
0 0 0 -1
1 2
2 3
3 4
1 4
2 4

Output
0

Input
2 1
1 1
1 2

Output
1
1

Input
3 3
0 -1 1
1 2
2 3
1 3

Output
1
2

-----Note-----

In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.

import sys

n, m = list(map(int, sys.stdin.readline().split()))
d = list(map(int, sys.stdin.readline().split()))
gph = [[] for _ in range(n)]

for _ in range(m):
    u, v = list(map(int, sys.stdin.readline().split()))
    u -= 1
    v -= 1
    gph[u].append((v, _))
    gph[v].append((u, _))

t = -1
if d.count(1) % 2 == 1:
    if -1 not in d:
        print(-1)
        return
    t = d.index(-1)

ans = [False] * m
vis = [False] * n
ed = [(-1, -1)] * n
rets = [(d[u] == 1) or (u == t) for u in range(n)]

stk = [[0, iter(gph[0])]]
while len(stk) > 0:
    u = stk[-1][0]
    vis[u] = True
    try:
        while True:
            v, i = next(stk[-1][1])
            if not vis[v]:
                ed[v] = (u, i)
                stk.append([v, iter(gph[v])])
                break
    except StopIteration:
        p, e = ed[u]
        if p >= 0 and rets[u]:
            rets[p] = not rets[p]
            ans[e] = True
        stk.pop()
        pass

print(ans.count(True))
print("\n".join([str(i+1) for i in range(m) if ans[i]]))
#1231


Solve in Python:
Leonardo Fibonacci in a rare portrait of his younger days

I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers).

While there are plenty of variation on it ([including](https://www.codewars.com/kata/tribonacci-sequence) [a few](https://www.codewars.com/kata/fibonacci-tribonacci-and-friends) [I wrote](https://www.codewars.com/kata/triple-shiftian-numbers/)), usually the catch is all the same: get a starting (signature) list of numbers, then proceed creating more with the given rules.

What if you were to get to get two parameters, one with the signature (starting value) and the other with the number you need to sum at each iteration to obtain the next one?

And there you have it, getting 3 parameters:

* a signature of length `length`
* a second parameter is a list/array of indexes of the last `length` elements you need to use to obtain the next item in the sequence (consider you can end up not using a few or summing the same number multiple times)' in other words, if you get a signature of length `5` and `[1,4,2]` as indexes, at each iteration you generate the next number by summing the 2nd, 5th and 3rd element (the ones with indexes `[1,4,2]`) of the last 5 numbers
* a third and final parameter is of course which sequence element you need to return (starting from zero, I don't want to bother you with adding/removing 1s or just coping with the fact that after years on CodeWars we all count as computers do):

```python
custom_fib([1,1],[0,1],2) == 2 #classical fibonacci!
custom_fib([1,1],[0,1],3) == 3 #classical fibonacci!
custom_fib([1,1],[0,1],4) == 5 #classical fibonacci!
custom_fib([3,5,2],[0,1,2],4) == 17 #similar to my Tribonacci
custom_fib([7,3,4,1],[1,1],6) == 2 #can you figure out how it worked ;)?
```

from collections import deque

def custom_fib(signature,indexes,n):
    s = deque(signature, maxlen=len(signature))
    for i in range(n):
        s.append(sum(s[i] for i in indexes))
    return s[0]


Solve in Python:
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer a_{i} — the current skill level. All skills have the same maximum level A.

Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values:  The number of skills that a character has perfected (i.e., such that a_{i} = A), multiplied by coefficient c_{f}. The minimum skill level among all skills (min a_{i}), multiplied by coefficient c_{m}.

Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force.

-----Input-----

The first line of the input contains five space-separated integers n, A, c_{f}, c_{m} and m (1 ≤ n ≤ 100 000, 1 ≤ A ≤ 10^9, 0 ≤ c_{f}, c_{m} ≤ 1000, 0 ≤ m ≤ 10^15).

The second line contains exactly n integers a_{i} (0 ≤ a_{i} ≤ A), separated by spaces, — the current levels of skills.

-----Output-----

On the first line print the maximum value of the Force that the character can achieve using no more than m currency units.

On the second line print n integers a'_{i} (a_{i} ≤ a'_{i} ≤ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces.

-----Examples-----
Input
3 5 10 1 5
1 3 1

Output
12
2 5 2

Input
3 5 10 1 339
1 3 1

Output
35
5 5 5

-----Note-----

In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1.

In the second test one should increase all skills to maximum.

f = lambda: list(map(int, input().split()))
g = lambda: m - l * p[l - 1] + s[l]

n, A, x, y, m = f()
t = sorted((q, i) for i, q in enumerate(f()))
p = [q for q, i in t]
s = [0] * (n + 1)
for j in range(n): s[j + 1] = p[j] + s[j]

l = r = n
F = L = R = B = -1
while 1:
    if p:
        while l > r or g() < 0: l -= 1
        b = min(p[l - 1] + g() // l, A)
    else: b, l = A, 0

    f = x * (n - r) + y * b
    if F < f: F, L, R, B = f, l, r, b

    if not p: break
    m += p.pop() - A
    r -= 1
    if m < 0: break

print(F)

p = [(i, B if j < L else q if j < R else A) for j, (q, i) in enumerate(t)]
for i, q in sorted(p): print(q)


Solve in Python:
Let $a$ and $b$ be two arrays of lengths $n$ and $m$, respectively, with no elements in common. We can define a new array $\mathrm{merge}(a,b)$ of length $n+m$ recursively as follows:  If one of the arrays is empty, the result is the other array. That is, $\mathrm{merge}(\emptyset,b)=b$ and $\mathrm{merge}(a,\emptyset)=a$. In particular, $\mathrm{merge}(\emptyset,\emptyset)=\emptyset$.  If both arrays are non-empty, and $a_1<b_1$, then $\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$. That is, we delete the first element $a_1$ of $a$, merge the remaining arrays, then add $a_1$ to the beginning of the result.  If both arrays are non-empty, and $a_1>b_1$, then $\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$. That is, we delete the first element $b_1$ of $b$, merge the remaining arrays, then add $b_1$ to the beginning of the result.

This algorithm has the nice property that if $a$ and $b$ are sorted, then $\mathrm{merge}(a,b)$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $a=[3,1]$ and $b=[2,4]$, then $\mathrm{merge}(a,b)=[2,3,1,4]$.

A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).

There is a permutation $p$ of length $2n$. Determine if there exist two arrays $a$ and $b$, each of length $n$ and with no elements in common, so that $p=\mathrm{merge}(a,b)$.

-----Input-----

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

The first line of each test case contains a single integer $n$ ($1\le n\le 2000$).

The second line of each test case contains $2n$ integers $p_1,\ldots,p_{2n}$ ($1\le p_i\le 2n$). It is...

t = int(input())

for _ in range(t):
    n = int(input())
    l = [int(x) for x in input().split()]
    cur = l[0]
    cll = 1
    blocks = []
    for x in l[1:]:
        if x > cur:
            blocks.append(cll)
            cur = x
            cll = 1
        else:
            cll += 1
    blocks.append(cll)

    poss = [[False]*(n+1) for _ in range(len(blocks) + 1)]
    poss[0][0] = True
    for i, b in enumerate(blocks):
        for j in range(n+1):
            poss[i+1][j] = poss[i][j]
            if b <= j:
                poss[i+1][j] |= poss[i][j-b]

    # print()
    # print(blocks)
    # for r in poss:
    #     print(r)
    print("YES" if poss[len(blocks)][n] else "NO")


Solve in Python:
Let $a_1, \ldots, a_n$ be an array of $n$ positive integers. In one operation, you can choose an index $i$ such that $a_i = i$, and remove $a_i$ from the array (after the removal, the remaining parts are concatenated).

The weight of $a$ is defined as the maximum number of elements you can remove.

You must answer $q$ independent queries $(x, y)$: after replacing the $x$ first elements of $a$ and the $y$ last elements of $a$ by $n+1$ (making them impossible to remove), what would be the weight of $a$?

-----Input-----

The first line contains two integers $n$ and $q$ ($1 \le n, q \le 3 \cdot 10^5$)  — the length of the array and the number of queries.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \leq a_i \leq n$) — elements of the array.

The $i$-th of the next $q$ lines contains two integers $x$ and $y$ ($x, y \ge 0$ and $x+y < n$).

-----Output-----

Print $q$ lines, $i$-th line should contain a single integer  — the answer to the $i$-th query.

-----Examples-----
Input
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12

Output
5
11
6
1
0

Input
5 2
1 4 1 2 4
0 0
1 0

Output
2
0

-----Note-----

Explanation of the first query:

After making first $x = 3$ and last $y = 1$ elements impossible to remove, $a$ becomes $[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$ (we represent $14$ as $\times$ for clarity).

Here is a strategy that removes $5$ elements (the element removed is colored in red):  $[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$  $[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$  $[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$  $[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$  $[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$  $[\times, \times, \times, 9, 4, 5, 3, \times]$ (final state)

It is impossible to remove more than $5$ elements, hence the weight is $5$.

from sys import stdin

def bitadd(a,w,bit):

    x = a
    while x <= (len(bit)-1):
        bit[x] += w
        x += x & (-1 * x)

def bitsum(a,bit):

    ret = 0
    x = a
    while x > 0:
        ret += bit[x]
        x -= x & (-1 * x)
    return ret

class RangeBIT:

    def __init__(self,N,indexed):
        self.bit1 = [0] * (N+2)
        self.bit2 = [0] * (N+2)
        self.mode = indexed

    def bitadd(self,a,w,bit):

        x = a
        while x <= (len(bit)-1):
            bit[x] += w
            x += x & (-1 * x)

    def bitsum(self,a,bit):

        ret = 0
        x = a
        while x > 0:
            ret += bit[x]
            x -= x & (-1 * x)
        return ret

    def add(self,l,r,w):

        l = l + (1-self.mode)
        r = r + (1-self.mode)
        self.bitadd(l,-1*w*l,self.bit1)
        self.bitadd(r,w*r,self.bit1)
        self.bitadd(l,w,self.bit2)
        self.bitadd(r,-1*w,self.bit2)

    def sum(self,l,r):
        l = l + (1-self.mode)
        r = r + (1-self.mode)
        ret =  self.bitsum(r,self.bit1) + r * self.bitsum(r,self.bit2)
        ret -= self.bitsum(l,self.bit1) + l * self.bitsum(l,self.bit2)

        return ret

n,q = list(map(int,stdin.readline().split()))
a = list(map(int,stdin.readline().split()))

qs = [ [] for i in range(n+1) ]
ans = [None] * q

for loop in range(q):
    x,y = list(map(int,stdin.readline().split()))
    l = x+1
    r = n-y
    qs[r].append((l,loop))

BIT = [0] * (n+1)

for r in range(1,n+1):

    b = r-a[r-1]

    if b >= 0:

        L = 1
        R = r+1
        while R-L != 1:
            M = (L+R)//2

            if bitsum(M,BIT) >= b:
                L = M
            else:
                R = M

        if bitsum(L,BIT) >= b:
            bitadd(1,1,BIT)
            bitadd(L+1,-1,BIT)

    for ql,qind in qs[r]:
        ans[qind] = bitsum(ql,BIT)

for i in ans:
    print (i)


Solve in Python:
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N).
Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence.
Then, perform the following operation until p becomes empty:
 - Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.

-----Constraints-----
 - N is an even number.
 - 2 ≤ N ≤ 2 × 10^5
 - p is a permutation of (1, 2, ..., N).

-----Input-----
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N

-----Output-----
Print the lexicographically smallest permutation, with spaces in between.

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

-----Sample Output-----
3 1 2 4

The solution above is obtained as follows:pq(3, 2, 4, 1)()↓↓(3, 1)(2, 4)↓↓()(3, 1, 2, 4)

import heapq
import sys
input=sys.stdin.readline

class SegmentTreeMin():
  def __init__(self,n,init):
    self.offset=2**((n-1).bit_length())
    self.tree=[init]*(2*self.offset)
    self.init=init
  def update(self,pos,val):
    pos+=self.offset
    self.tree[pos]=val
    while pos>1:
      pos=pos//2
      self.tree[pos]=min(self.tree[2*pos],self.tree[2*pos+1])
  def query(self,l,r):
    l+=self.offset
    r+=self.offset
    ret=self.init
    while l<=r:
      ret=min(ret,self.tree[r])
      r=(r-1)//2
      ret=min(ret,self.tree[l])
      l=(l+1)//2
    return ret

n=int(input())
arr=list(map(int,input().split()))
odds=SegmentTreeMin(n//2,10**18)
evens=SegmentTreeMin(n//2,10**18)
dic={}
for i in range(n):
  dic[arr[i]]=i
  if i%2==0:
    odds.update(i//2,arr[i])
  else:
    evens.update(i//2,arr[i])
q=[]
heapq.heappush(q,(odds.query(0,(n-1)//2),0,n-1))
ans=[]
while len(q)!=0:
  _,l,r=heapq.heappop(q)
  if l%2==0:
    a=odds.query(l//2,r//2)
    odds.update(dic[a]//2,10**18)
    b=evens.query(dic[a]//2,r//2)
    evens.update(dic[b]//2,10**18)
    ans.append(a)
    ans.append(b)
    tl=dic[a]
    tr=dic[b]
    if tl!=l:
      heapq.heappush(q,(odds.query(l//2,(tl-1)//2),l,tl-1))
    if tl+1<tr-1:
      heapq.heappush(q,(evens.query((tl+1)//2,(tr-1)//2),tl+1,tr-1))
    if tr!=r:
      heapq.heappush(q,(odds.query((tr+1)//2,r//2),tr+1,r))
  else:
    a=evens.query(l//2,r//2)
    evens.update(dic[a]//2,10**18)
    b=odds.query((dic[a]+1)//2,r//2)
    odds.update(dic[b]//2,10**18)
    ans.append(a)
    ans.append(b)
    tl=dic[a]
    tr=dic[b]
    if tl!=l:
      heapq.heappush(q,(evens.query(l//2,(tl-1)//2),l,tl-1))
    if tl+1<tr-1:
      heapq.heappush(q,(odds.query((tl+1)//2,(tr-1)//2),tl+1,tr-1))
    if tr!=r:
      heapq.heappush(q,(evens.query((tr+1)//2,r//2),tr+1,r))
print(*ans)


Solve in Python:
Let X be the set of all integers between 0 and n-1. Suppose we have a collection S1, S2, ..., Sm of subsets of X. Say an atom A is a subset of X such that for each Si we have either A is a subset of Si or A and Si do not have any common elements.

Your task is to find a collection A1, ..., Ak of atoms such that every item in X is in some Ai and no two Ai, Aj with i ≠ j share a common item. Surely such a collection exists as we could create a single set {x} for each x in X. A more interesting question is to minimize k, the number of atoms.

-----Input-----

The first line contains a single positive integer t ≤ 30 indicating the number of test cases. Each test case begins with two integers n,m where n is the size of X and m is the number of sets Si. Then m lines follow where the i'th such line begins with an integer vi between 1 and n (inclusive) indicating the size of Si. Following this are vi distinct integers between 0 and n-1 that describe the contents of Si.

You are guaranteed that 1 ≤ n ≤ 100 and 1 ≤ m ≤
30. Furthermore, each number between 0 and n-1 will appear in at least one set Si.

-----Output-----

For each test case you are to output a single integer indicating the minimum number of atoms that X can be partitioned into to satisfy the constraints.

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

Output:
3
4

# cook your dish here
for _ in range(int(input())):
 n,m=list(map(int,input().split()))
 atomlist = ['']*n
 for k in range(m):
  s=[]
  s.extend(input().split()[1:])
  #print(s)
  for w in range(n):
   if str(w) in s:
    atomlist[w]+="1"
   else:
    atomlist[w]+="0"
  #print(atomlist)
 print(len(set(atomlist)))


def cycle(n):
    if not n % 2 or not n % 5:
        return -1
    x, mods = 1, set()
    while x not in mods:
        mods.add(x)
        x = 10 * x % n
    return len(mods)


Solve in Python:
Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * ... * x, and by convention, 0! = 1.)

For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.

Example 1:
Input: K = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.

Example 2:
Input: K = 5
Output: 0
Explanation: There is no x such that x! ends in K = 5 zeroes.

Note:

       K will be an integer in the range [0, 10^9].

class Solution:
     def canTransform(self, start, end):
         """
         :type start: str
         :type end: str
         :rtype: bool
         """
         def countX(s, char='R'):
             if char == 'L':
                 s = s[::-1]
             countX = 0
             ans = []
             for c in s:
                 if c == char:
                     ans.append(countX)
                 elif c == 'X':
                     countX += 1
             return ans

         startLR = "".join(c for c in start if c != 'X')
         endLR   = "".join(c for c in end   if c != 'X')
         startR, startL = countX(start, 'R'), countX(start, 'L')
         endR, endL     = countX(end, 'R'), countX(end, 'L')

         return (startLR == endLR) and \
                all([startR[i] <= endR[i] for i in range(len(startR))]) and \
                all([startL[i] <= endL[i] for i in range(len(startL))])


Solve in Python:
Let us begin with an example:

A man has a rather old car being worth $2000.
He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.

He thinks he can save $1000 each month but the prices of his old
car and of the new one decrease of 1.5 percent per month.
Furthermore this percent of loss increases of `0.5` percent
at the end of every two months.
Our man finds it difficult to make all these calculations.

**Can you help him?**

How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over?

**Parameters and return of function:**
```
parameter (positive int or float, guaranteed) startPriceOld (Old car price)
parameter (positive int or float, guaranteed) startPriceNew (New car price)
parameter (positive int or float, guaranteed) savingperMonth
parameter (positive float or int, guaranteed) percentLossByMonth

nbMonths(2000, 8000, 1000, 1.5) should return [6, 766] or (6, 766)
```
###  Detail of the above example:
```
end month 1: percentLoss 1.5 available -4910.0
end month 2: percentLoss 2.0 available -3791.7999...
end month 3: percentLoss 2.0 available -2675.964
end month 4: percentLoss 2.5 available -1534.06489...
end month 5: percentLoss 2.5 available -395.71327...
end month 6: percentLoss 3.0 available 766.158120825...
return [6, 766] or (6, 766)

```

where `6` is the number of months at **the end of which** he can buy the new car and `766` is the nearest integer to `766.158...` (rounding `766.158` gives `766`).

**Note:**

Selling, buying and saving are normally done at end of month.
Calculations are processed at the end of each considered month
but if, by chance from the start, the value of the old car is bigger than the value of the new one or equal there is no saving to be made, no need to wait so he can at the beginning of the month buy the new car:
```
nbMonths(12000, 8000, 1000, 1.5) should return [0, 4000]
nbMonths(8000, 8000, 1000, 1.5) should return [0, 0]
```

We don't take care...

def nbMonths(priceOld, priceNew, savingMonth, percentLoss):
    if priceOld > priceNew:
        return [0, priceOld-priceNew]
    months = 0
    savings = 0
    loss = percentLoss/100
    while savings + priceOld < priceNew:
        months += 1
        savings += savingMonth
        if months%2 == 0:
            loss += 0.005
        priceOld -= priceOld*loss
        priceNew -= priceNew*loss
    saved = round(savings+priceOld-priceNew)
    return [months, saved]


Solve in Python:
Let us consider the following operations on a string consisting of A and B:
 - Select a character in a string. If it is A, replace it with BB. If it is B, replace with AA.
 - Select a substring that is equal to either AAA or BBB, and delete it from the string.
For example, if the first operation is performed on ABA and the first character is selected, the string becomes BBBA.
If the second operation is performed on BBBAAAA and the fourth through sixth characters are selected, the string becomes BBBA.
These operations can be performed any number of times, in any order.
You are given two string S and T, and q queries a_i, b_i, c_i, d_i.
For each query, determine whether S_{a_i} S_{{a_i}+1} ... S_{b_i}, a substring of S, can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, a substring of T.

-----Constraints-----
 - 1 \leq |S|, |T| \leq 10^5
 - S and T consist of letters A and B.
 - 1 \leq q \leq 10^5
 - 1 \leq a_i \leq b_i \leq |S|
 - 1 \leq c_i \leq d_i \leq |T|

-----Input-----
Input is given from Standard Input in the following format:
S
T
q
a_1 b_1 c_1 d_1
...
a_q b_q c_q d_q

-----Output-----
Print q lines. The i-th line should contain the response to the i-th query. If S_{a_i} S_{{a_i}+1} ... S_{b_i} can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, print YES. Otherwise, print NO.

-----Sample Input-----
BBBAAAABA
BBBBA
4
7 9 2 5
7 9 1 4
1 7 2 5
1 7 2 4

-----Sample Output-----
YES
NO
YES
NO

The first query asks whether the string ABA can be made into BBBA.
As explained in the problem statement, it can be done by the first operation.
The second query asks whether ABA can be made into BBBB, and the fourth query asks whether BBBAAAA can be made into BBB.
Neither is possible.
The third query asks whether the string BBBAAAA can be made into BBBA.
As explained in the problem statement, it can be done by the second operation.

import sys
input = sys.stdin.readline

S = input()[:-1]
T = input()[:-1]
acc0, acc1 = [0]*(len(S)+1), [0]*(len(S)+1)

for i in range(len(S)):
    acc0[i+1] = acc0[i]+(1 if S[i]=='A' else 0)
    acc1[i+1] = acc1[i]+(1 if S[i]=='B' else 0)

acc2, acc3 = [0]*(len(T)+1), [0]*(len(T)+1)

for i in range(len(T)):
    acc2[i+1] = acc2[i]+(1 if T[i]=='A' else 0)
    acc3[i+1] = acc3[i]+(1 if T[i]=='B' else 0)

q = int(input())

for _ in range(q):
    a, b, c, d = map(int, input().split())
    A_diff = acc0[b]-acc0[a-1]-(acc2[d]-acc2[c-1])
    B_diff = acc1[b]-acc1[a-1]-(acc3[d]-acc3[c-1])

    if A_diff%3==B_diff%3:
        print('YES')
    else:
        print('NO')


Solve in Python:
Let us define a function `f`such as:

- (1) for k positive odd integer > 2 :

- (2) for k positive even integer >= 2 :

- (3) for k positive integer > 1 :

where `|x|` is `abs(x)` and Bk the kth Bernoulli number.

`f` is not defined for `0, 1, -1`. These values will not be tested.

# Guidelines for Bernoulli numbers:

https://en.wikipedia.org/wiki/Bernoulli_number

http://mathworld.wolfram.com/BernoulliNumber.html

https://www.codewars.com/kata/bernoulli-numbers-1

There is more than one way to calculate them. You can make Pascal triangle and then with the basic formula below generate all Bernoulli numbers.

1 + 2B1 = 0 ... gives ...
  B1 = - 1/2

1 + 3B1 + 3B2 = 0 ... gives ...    B2        = 1/6

1 + 4B1 + 6B2 + 4B3 = 0 ... gives ... B3 = 0

1 + 5B1 + 10B2 + 10B3 + 5B4 = 0 ... gives ... B4 = - 1/30

... and so on

# Task

Function `series(k, nb)` returns (1), (2) or (3) where `k` is the `k` parameter of `f` and `nb` the upper bound in the summation of (1). `nb` is of no use for (2) and (3) but for the sake of simplicity it will always appear in the tests even for cases (2) and (3) with a value of `0`.

```
Examples
S(2, 0) = 1.644934066848224....
S(3, 100000) = 1.20205690310973....
S(4, 0) = 1.08232323371113.....
S(-5, 0) = -0.003968253968....
S(-11, 0) = 0.02109279609279....
```

# Notes

- For Java, C#, C++: `k` should be such as `-27 <= k <= 20`; otherwise `-30 <= k <= 30` and be careful of 32-bit integer overflow.
- Translators are welcome.

from math import factorial as f
import numpy as np

def combination(n, k):
    return f(n) // (f(k) * f(n-k))

def bern(target_level):
    b0 = 1
    b1 = -(1./2.)
    bern_nums = [b0,b1]
    n = 3
    while n <= target_level + 1:
        ser = []
        k = 0
        comb_list = []
        while k < n - 1:
            comb_list.append(combination(n, k))
            k += 1
        result_l = [c*b for c,b in zip(comb_list, bern_nums)]
        result_s = 0
        for element in result_l:
            result_s += element
        b_k = -result_s / combination(n,k)
        bern_nums.append(b_k)
        n += 1
    return bern_nums[-1]

def series(k, nb) :
    if k > 2 and k % 2 != 0:
        n = 1
        result = 0
        while n <= nb:
            result += 1/(n**k)
            n += 1
        return result
    elif k >= 2 and k % 2 == 0:
        bern_num = bern(k)
        return 1./2. * abs(bern_num) * (2*np.pi)**k / f(k)
    else:
        k = abs(k)
        bern_num = bern(k+1)
        return (-1)**k * bern_num / (k + 1)
    return 0


Solve in Python:
Let us define two functions f and g on positive integer numbers.  $f(n) = \text{product of non-zero digits of} n$

$g(n) = \left\{\begin{array}{ll}{n} & {\text{if} n < 10} \\{g(f(n))} & {\text{otherwise}} \end{array} \right.$

You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x) = k.

-----Input-----

The first line of the input contains an integer Q (1 ≤ Q ≤ 2 × 10^5) representing the number of queries.

Q lines follow, each of which contains 3 integers l, r and k (1 ≤ l ≤ r ≤ 10^6, 1 ≤ k ≤ 9).

-----Output-----

For each query, print a single line containing the answer for that query.

-----Examples-----
Input
4
22 73 9
45 64 6
47 55 7
2 62 4

Output
1
4
0
8

Input
4
82 94 6
56 67 4
28 59 9
39 74 4

Output
3
1
1
5

-----Note-----

In the first example:  g(33) = 9 as g(33) = g(3 × 3) = g(9) = 9  g(47) = g(48) = g(60) = g(61) = 6  There are no such integers between 47 and 55.  g(4) = g(14) = g(22) = g(27) = g(39) = g(40) = g(41) = g(58) = 4

from collections import defaultdict
import sys
def f(n): # O(digits)
    out = 1
    while(n > 0):
        digit = n % 10
        if digit != 0:
            out *= digit
        n = n//10
    return out

memorization = defaultdict(int) # For much faster calculation g(n)
def g(n):
    if n < 10:return n
    f_n = f(n)
    if f_n in memorization:
        return memorization[f_n]
    else:
        ans = g(f_n)
        memorization[f_n] = ans
        return ans

def s(L,l,r,k):
    if l > r:return l
    m = (l+r)//2
    if L[m] == k:return m
    if L[m] > k:return s(L,l,m-1,k)
    else:return s(L,m+1,r,k)

ans = {i : [1000001] for i in range(1,10)}

for i in range(1,1000001): # O(n) because 9*9*9*9*9*9 = 531441 -> Maxnimum each number between [1,531441] will calculated only once
    g_i = g(i)             # due to memorization
    if g_i != 0:ans[g_i].append(i)
for i in ans: # O( nlog(n) )
    ans[i].sort()

input = sys.stdin.readline
n = int(input())
for i in range(n): # O( Qlog(n) )
    l,r,k = [int(i) for i in input().split()] #O (logn) for each Q
    l_idx,r_idx = s(ans[k],0,len(ans[k])-1,l) , s(ans[k],0,len(ans[k])-1,r)
    #FIX l_idx to Upper_bound
    if ans[k][l_idx] != l and ans[k][l_idx] < l and ans[k][l_idx+1] > l : l_idx += 1
    #FIX r_idx to Lower_bound
    if ans[k][r_idx] != r and not (ans[k][r_idx] < r and ans[k][r_idx+1] > r) : r_idx -= 1
    print(r_idx - l_idx + 1)


Solve in Python:
Let x be a string of length at least 1.
We will call x a good string, if for any string y and any integer k (k \geq 2), the string obtained by concatenating k copies of y is different from x.
For example, a, bbc and cdcdc are good strings, while aa, bbbb and cdcdcd are not.
Let w be a string of length at least 1.
For a sequence F=(\,f_1,\,f_2,\,...,\,f_m) consisting of m elements,
we will call F a good representation of w, if the following conditions are both satisfied:
 - For any i \, (1 \leq i \leq m), f_i is a good string.
 - The string obtained by concatenating f_1,\,f_2,\,...,\,f_m in this order, is w.
For example, when w=aabb, there are five good representations of w:
 - (aabb)
 - (a,abb)
 - (aab,b)
 - (a,ab,b)
 - (a,a,b,b)
Among the good representations of w, the ones with the smallest number of elements are called the best representations of w.
For example, there are only one best representation of w=aabb: (aabb).
You are given a string w. Find the following:
 - the number of elements of a best representation of w
 - the number of the best representations of w, modulo 1000000007 \, (=10^9+7)
(It is guaranteed that a good representation of w always exists.)

-----Constraints-----
 - 1 \leq |w| \leq 500000 \, (=5 \times 10^5)
 - w consists of lowercase letters (a-z).

-----Partial Score-----
 - 400 points will be awarded for passing the test set satisfying 1 \leq |w| \leq 4000.

-----Input-----
The input is given from Standard Input in the following format:
w

-----Output-----
Print 2 lines.
 - In the first line, print the number of elements of a best representation of w.
 - In the second line, print the number of the best representations of w, modulo 1000000007.

-----Sample Input-----
aab

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

from collections import Counter
*W, = map(ord, input())
N = len(W)

C = Counter(W)
if len(C) == 1:
    print(N)
    print(1)
    return

def z_algo(S):
    A = [0]*N
    i = 1; j = 0
    A[0] = l = len(S)
    while i < l:
        while i+j < l and S[j] == S[i+j]:
            j += 1
        A[i] = j
        if not j:
            i += 1
            continue
        k = 1
        while l-i > k < j - A[k]:
            A[i+k] = A[k]
            k += 1
        i += k; j -= k
    return A

def calc(W):
    Z = z_algo(W)
    G = [0]*N
    for i in range(N):
        G[i] = 1
    for p in range(1, N):
        if not G[p-1]:
            continue
        for k in range(2, Z[p]//p+2):
            G[k*p-1] = 0
    return G
G0 = calc(W)
W.reverse()
G1 = calc(W)

if G0[N-1]:
    print(1)
    print(1)
    return

print(2)
print(sum(p and q for p, q in zip(G0[:-1], reversed(G1[:-1]))))


Solve in Python:
Let's assume that   v(n) is the largest prime number, that does not exceed n;

 u(n) is the smallest prime number strictly greater than n.

Find $\sum_{i = 2}^{n} \frac{1}{v(i) u(i)}$.

-----Input-----

The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases.

Each of the following t lines of the input contains integer n (2 ≤ n ≤ 10^9).

-----Output-----

Print t lines: the i-th of them must contain the answer to the i-th test as an irreducible fraction "p/q", where p, q are integers, q > 0.

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

Output
1/6
7/30

T = int( input() )

#for every prime x
#(b-a)/ab
#1/a-1/b

MAX = 33000

bePrime = [0] * MAX;
primNum = []

for j in range(2, MAX):
    if bePrime[j] == 0:
        primNum.append( j )
        i = j
        while i < MAX:
            bePrime[i] = 1
            i = i + j

def isPrime( a ):
    for j in primNum:
        if j >= a:
            return True
        if a % j == 0:
            return False
    return True

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

while T > 0:
    num = 0;
    n = int( input() )

    m = n
    while isPrime(m) == False:
        m -= 1
    while isPrime(n + 1) == False:
        n += 1
        num += 1

    a = n - 1
    b = 2 * ( n+1 )

    a = a * (n+1) * m - num * b
    b = b * (n+1) * m

    g = gcd( a, b)
    a //= g
    b //= g

    print( '{0}/{1}'.format( a, b  ) )
    T -= 1;


Solve in Python:
Let's assume we need "clean" strings. Clean means a string should only contain letters `a-z`, `A-Z` and spaces. We assume that there are no double spaces or line breaks.

Write a function that takes a string and returns a string without the unnecessary characters.

### Examples

```python
remove_chars('.tree1')    ==> 'tree'

remove_chars("that's a pie$ce o_f p#ie!")  ==> 'thats a piece of pie'

remove_chars('john.dope@dopington.com')    ==> 'johndopedopingtoncom'

remove_chars('my_list = ["a","b","c"]')    ==> 'mylist  abc'

remove_chars('1 + 1 = 2')    ==> '    ' (string with 4 spaces)

remove_chars("0123456789(.)+,|[]{}=@/~;^$'<>?-!*&:#%_")  ==> '' (empty string)
```

def remove_chars(s):
    for x in s:
            if x != ' ':
                    if not x.isalpha():
                            s = s.replace(x,'')
    return s


Solve in Python:
Let's call a sequence good if the sum of all its elements is $0$.
You have a sequence of integers $A_1, A_2, \ldots, A_N$. You may perform any number of operations on this sequence (including zero). In one operation, you should choose a valid index $i$ and decrease $A_i$ by $i$. Can you make the sequence good using these operations?

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

-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to make the given sequence good or "NO" if it is impossible.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10$
- $|A_i| \le 100$ for each valid $i$

-----Subtasks-----
Subtask #1 (10 points): $N = 1$
Subtask #2 (30 points): $N \le 2$
Subtask #3 (60 points): original constraints

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

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

-----Explanation-----
Example case 2: We can perform two operations ― subtract $1$ from $A_1$ and $2$ from $A_2$.

for i in range(int(input())):
 n=int(input())
 l=list(map(int,input().split()))
 a,b=0,0
 if n==1:
  if l[0]>=0:
   print('YES')
  else:
   print('NO')
 else:
  for i in l:
   if i<0:
    b+=i
   else:
    a+=i
  if a>=abs(b):
   print('YES')
  else:
   print('NO')


Solve in Python:
Let's call an array $a_1, a_2, \dots, a_m$ of nonnegative integer numbers good if $a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$, where $\oplus$ denotes the bitwise XOR operation.

For example, array $[1, 2, 3, 6]$ is good, as $1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6)$. At the same time, array $[1, 2, 1, 3]$ isn't good, as $1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3)$.

You are given an array of length $n$: $a_1, a_2, \dots, a_n$. Append at most $3$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10\,000$). The description of the test cases follows.

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

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($0\le a_i \le 10^9$) — the elements of the array.

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

-----Output-----

For each test case, output two lines.

In the first line, output a single integer $s$ ($0\le s\le 3$) — the number of elements you want to append.

In the second line, output $s$ integers $b_1, \dots, b_s$ ($0\le b_i \le 10^{18}$) — the elements you want to append to the array.

If there are different solutions, you are allowed to output any of them.

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

Output
0

2
4 4
3
2 6 2

-----Note-----

In the first test case of the example, the sum of all numbers is $12$, and their $\oplus$ is $6$, so the condition is already satisfied.

In the second test case of the...

for _ in range(int(input())):
	n=int(input())
	l=list(map(int,input().split()))
	x=0
	for i in l:
		x^=i
	s=sum(l)
	if s==(2*x):
		print("0\n")
	else:
		if x==0:
			print("1")
			print(s)
		else:
			print("2")
			print(x,x+s)


Solve in Python:
Let's call an array arr a mountain if the following properties hold:

arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:

arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]

Given an integer array arr that is guaranteed to be a mountain, return any i such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

Example 1:
Input: arr = [0,1,0]
Output: 1
Example 2:
Input: arr = [0,2,1,0]
Output: 1
Example 3:
Input: arr = [0,10,5,2]
Output: 1
Example 4:
Input: arr = [3,4,5,1]
Output: 2
Example 5:
Input: arr = [24,69,100,99,79,78,67,36,26,19]
Output: 2

Constraints:

3 <= arr.length <= 104
0 <= arr[i] <= 106
arr is guaranteed to be a mountain array.

class Solution:
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        low = 0
        high = len(arr) - 1

        while low < high:
            mid1 = (low + high)//2
            mid2 = mid1 + 1

            if arr[mid1] <= arr[mid2]:
                low = mid2
            else:
                high = mid1
        return low


Solve in Python:
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:

B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]

(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.

Note:

0 <= A.length <= 10000
0 <= A[i] <= 10000

Follow up:

Can you solve it using only one pass?
Can you solve it in O(1) space?

class Solution:
    def longestMountain(self, A: List[int]) -> int:
        is_peak = False
        index = 1
        longest = 0
        while index < len(A) - 1:
            if A[index] > A[index-1] and A[index] > A[index+1]:
                is_peak = True
            if not is_peak:
                index += 1
                continue
            left = index-1
            while left-1 >= 0 and A[left] > A[left-1]:
                left -= 1
            right = index+1
            while right+1 < len(A) and A[right] > A[right+1]:
                right += 1
            longest = max(longest, right-left+1)
            index = right
            is_peak = False
        return longest


Solve in Python:
Let's call some positive integer classy if its decimal representation contains no more than $3$ non-zero digits. For example, numbers $4$, $200000$, $10203$ are classy and numbers $4231$, $102306$, $7277420000$ are not.

You are given a segment $[L; R]$. Count the number of classy integers $x$ such that $L \le x \le R$.

Each testcase contains several segments, for each of them you are required to solve the problem separately.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 10^4$) — the number of segments in a testcase.

Each of the next $T$ lines contains two integers $L_i$ and $R_i$ ($1 \le L_i \le R_i \le 10^{18}$).

-----Output-----

Print $T$ lines — the $i$-th line should contain the number of classy integers on a segment $[L_i; R_i]$.

-----Example-----
Input
4
1 1000
1024 1024
65536 65536
999999 1000001

Output
1000
1
0
2

from bisect import bisect_left as bl
c=[]
def gen(n,nz):
    if len(n)>=19:
        return
    nonlocal c
    c.append(int(n))
    if nz==3:
        n+="0"
        gen(n,nz)
        return
    gen(n+"0",nz)
    for i in ("123456789"):
        gen(n+i,nz+1)
for i in ("123456789"):
    gen(i,1)
c.append(10**18)
c.sort()
n=int(input())
for i in range(n):
    a,b=list(map(int,input().split()))
    x=min(bl(c,b),len(c)-1)
    y=bl(c,a)
    if x==y and b<c[x]:
        print(0)
    elif (c[x]==b and c[y]==a) or c[x]==b:
        print(x-y+1)
    else:
        print(x-y)


Solve in Python:
Let's call two strings $s$ and $t$ anagrams of each other if it is possible to rearrange symbols in the string $s$ to get a string, equal to $t$.

Let's consider two strings $s$ and $t$ which are anagrams of each other. We say that $t$ is a reducible anagram of $s$ if there exists an integer $k \ge 2$ and $2k$ non-empty strings $s_1, t_1, s_2, t_2, \dots, s_k, t_k$ that satisfy the following conditions:

  If we write the strings $s_1, s_2, \dots, s_k$ in order, the resulting string will be equal to $s$;  If we write the strings $t_1, t_2, \dots, t_k$ in order, the resulting string will be equal to $t$;  For all integers $i$ between $1$ and $k$ inclusive, $s_i$ and $t_i$ are anagrams of each other.

If such strings don't exist, then $t$ is said to be an irreducible anagram of $s$. Note that these notions are only defined when $s$ and $t$ are anagrams of each other.

For example, consider the string $s = $ "gamegame". Then the string $t = $ "megamage" is a reducible anagram of $s$, we may choose for example $s_1 = $ "game", $s_2 = $ "gam", $s_3 = $ "e" and $t_1 = $ "mega", $t_2 = $ "mag", $t_3 = $ "e":

 [Image]

On the other hand, we can prove that $t = $ "memegaga" is an irreducible anagram of $s$.

You will be given a string $s$ and $q$ queries, represented by two integers $1 \le l \le r \le |s|$ (where $|s|$ is equal to the length of the string $s$). For each query, you should find if the substring of $s$ formed by characters from the $l$-th to the $r$-th has at least one irreducible anagram.

-----Input-----

The first line contains a string $s$, consisting of lowercase English characters ($1 \le |s| \le 2 \cdot 10^5$).

The second line contains a single integer $q$ ($1 \le q \le 10^5$)  — the number of queries.

Each of the following $q$ lines contain two integers $l$ and $r$ ($1 \le l \le r \le |s|$), representing a query for the substring of $s$ formed by characters from the $l$-th to the $r$-th.

-----Output-----

For each query, print a single line containing "Yes" (without quotes) if the...

import sys
readline = sys.stdin.readline

S = list([ord(x)-97 for x in readline().strip()])
N = len(S)
table = [[0]*26 for _ in range(N)]
for i in range(N):
    table[i][S[i]] = 1
for i in range(1, N):
    for j in range(26):
        table[i][j] += table[i-1][j]

Q = int(readline())
Ans = [None]*Q
for qu in range(Q):
    l, r = list(map(int, readline().split()))
    l -= 1
    r -= 1
    if l == r or S[l] != S[r]:
        Ans[qu] = True
        continue
    K = [table[r][j] - table[l][j] for j in range(26)]
    if len([k for k in K if k]) <= 2:
        Ans[qu] = False
    else:
        Ans[qu] = True
print('\n'.join(['Yes' if s else 'No' for s in Ans]))


Solve in Python:
Let's consider a rectangular table R consisting of N rows and M columns. Rows are enumerated from 1  to N from top to bottom. Columns are enumerated from 1 to M from left to right. Each element of R is a non-negative integer. R is called steady if the sum of elements in the ith row is not less then the sum of elements in the (i-1)th row for each i where 2 ≤ i ≤ N and the sum of elements in the Nth row is less than or equal to M. Your task is to find the number of different steady tables of size N x M modulo 1 000 000 000.

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

-----Output-----
For each test case, print a single integer corresponding to the answer.

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

-----Subtasks-----
- Subtask 1 : 1 ≤ T ≤ 10 , 1 ≤ N,M ≤ 50 : ( 23 pts )
- Subtask 2 : 1 ≤ T ≤ 10 , 1 ≤ N,M ≤ 500 : ( 29 pts )
- Subtask 3 : 1 ≤ T ≤ 10 , 1 ≤ N,M ≤ 2000 : ( 48 pts )

-----Example-----
Input:
3
1 1
2 2
2 3
Output:
2
25
273

-----Explanation-----
Test case 1 : There are only 2 such grids possible 0 and 1.

# This is not my code, it's Snehasish Karmakar's.  Refer to http://www.codechef    .com/viewsolution/7153774
# for original version.
# Submitting it to try and work out if it can be sped up.

def compute_nCr(n,r) :
 C[0][0]=1
 for i in range(1,n+1) :
#       print "i",i
  C[i][0]=1
  for j in range(1,min(i,r)+1) :
   if i!=j :
    C[i][j]=(C[i-1][j-1]+C[i-1][j])%MOD
   else :
    C[i][j]=1

def solve(n,m) :
 store=[C[m+i-1][i] for i in range(m+1)]

 for i in range(1,n+1) :
  s=1
  for j in range(1,m+1) :
   s=(s+store[j])%MOD
   store[j]=(s*C[m+j-1][j])%MOD
  #   print "a[%d][%d]=%d"%(i,j,s)

 return s

MOD=1000000000
LIMIT=2000

C=[[0 for x in range(LIMIT+1)] for y in range(2*LIMIT+1)]
compute_nCr(2*LIMIT,LIMIT)
t=int(input())

while t :
 n,m=list(map(int,input().split()))
 print(solve(n,m))
 t-=1


Solve in Python:
Let's consider a rooted binary tree with the following properties:
- The number of nodes and edges in the tree is infinite
- The tree root is labeled by $1$
- A node labeled by $v$ has two children: $2 \cdot v$ (the left child of $v$), and $2 \cdot v + 1$ (the right child of $v$).
Here is an image of the first several layers of such a tree:

Let's consider four operations that you are allowed to apply during the tree traversal:
- move to the left child - move from $v$ to $2 \cdot v$
- move to the right child - move from $v$ to $2 \cdot v + 1$
- move to the parent as a left child - move from $v$ to $\frac{v}{2}$ if $v$ is an even integer
- move to the parent as a right child - move from $v$ to $\frac{v - 1}{2}$ if $v$ is an odd integer
It can be proven, that for any pair of nodes $u$ and $v$, there is only one sequence of commands that moves from $u$ to $v$ and visits each node of the tree at most once. Let's call such a sequence of commands a path configuration for a pair of nodes $(u, v)$.
You are asked to process a series of the following queries:
You are given three integers $n$, $u$ and $v$ ($1 \leq u, v \leq n$). Count the pairs of nodes $(w, t)$ ($1 \leq w, t \leq n$) such that the path configuration for $(w, t)$ is the same with the path configuration for $(u, v)$.

-----Input-----
- The first line of input contains a single integer $Q$, denoting the number of queries to process.
- Each of the next $Q$ lines contains three space-separated integers $n$, $u$ and $v$ denoting a query.

-----Output-----
For each query, print the answer on a separate line.

-----Constraints-----
- $1 \leq Q \leq 2 \cdot 10^4$
- $1 \leq u, v \leq n \leq 10^{9}$

-----Example Input-----
3
11 9 11
10 2 2
8 1 8

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

-----Explanation-----
In the first query from the example test case, you should count pairs $(5, 7)$ and $(9, 11)$.
In the second query from the example test case, you should count the following pairs: $(1, 1)$, $(2, 2)$, $(3, 3)$, $(4, 4)$, $(5, 5)$, $(6, 6)$, $(7, 7)$, $(8, 8)$, $(9,...

t = int(input())
while(t>0):
 t-=1;
 n,l,r = list(map(int,input().split()));
 a = bin(l)[2:];
 b = bin(r)[2:];
 # find matching
 z = 0;
 l = min(len(a),len(b));
 for i in range(l):
  if a[i]==b[i]:
   z+=1;
  else:
   break;

 #find base string
 a = a[z:]
 b = b[z:]
 if(len(a)==0 and len(b)==0):
  print(n);
 else :
  m = max(len(a),len(b))
  #print m;
  zz = bin(n)[2:]
  x= len(zz)
  y = zz[:x-m]

  f1 = y+a;
  f2 = y+b;
  ans = int(y,2)
  if(int(f1,2)>n or int(f2,2)>n):
   ans-=1;

  print(ans)


Solve in Python:
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.

At every moment of time, every SELL offer has higher price than every BUY offer.

In this problem no two ever existed orders will have the same price.

The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below. [Image] The presented order book says that someone wants to sell the product at price $12$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $10$.

There are two possible actions in this orderbook:  Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.

It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL $20$" if there is already an offer "BUY $20$" or "BUY $25$" — in this case you just accept the best BUY offer.

You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: "ADD $p$" denotes adding a new order with price $p$ and unknown direction. The order must not contradict with orders still not removed from the order book.  "ACCEPT $p$" denotes accepting an existing best offer with price $p$ and unknown direction.

The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore...

from heapq import heapify,heappush,heappop

n=int(input())
low=[]
high=[]
pos=0
mid=set()
for i in range(n):
    #print(high,low,mid)
    s=input().split()
    #print(s)
    x=int(s[1])
    s=s[0]
    #print(s[0],s[0]=='ADD')
    if(s=='ADD'):
        if(len(low) and x<-1*low[0]):
            heappush(low,(-x))
        elif(len(high) and x>high[0]):
            heappush(high,x)
        else:
            mid.add(x)
    else:
        if(len(low) and x==-low[0]):
            heappop(low)
        elif(len(high) and x==high[0]):
            heappop(high)
        elif(x in mid):
            pos+=1
        else:
            print(0)
            return
        for j in mid:
            if(j>x):
                heappush(high,j)
            elif(j<x):
                heappush(low,-j)
        mid=set()
mod=int(1e9+7)
print((pow(2,pos,mod)*(len(mid)+1))%mod)


Solve in Python:
Let's define `increasing` numbers as the numbers whose digits, read from left to right, are never less than the previous ones: 234559 is an example of increasing number.

Conversely, `decreasing` numbers have all the digits read from left to right so that no digits is bigger than the previous one: 97732 is an example of decreasing number.

You do not need to be the next Gauss to figure that all numbers with 1 or 2 digits are either increasing or decreasing: 00, 01, 02, ..., 98, 99 are all belonging to one of this categories (if not both, like 22 or 55): 101 is indeed the first number which does NOT fall into either of the categories. Same goes for all the numbers up to 109, while 110 is again a decreasing number.

Now your task is rather easy to declare (a bit less to perform): you have to build a function to return the total occurrences of all the increasing or decreasing numbers *below* 10 raised to the xth power (x will always be >= 0).

To give you a starting point, there are a grand total of increasing and decreasing numbers as shown in the table:

|Total  | Below
|---------------
|1      | 1
|10     | 10
|100    | 100
|475    | 1000
|1675   | 10000
|4954   | 100000
|12952  | 1000000

This means that your function will have to behave like this:
```python
total_inc_dec(0)==1
total_inc_dec(1)==10
total_inc_dec(2)==100
total_inc_dec(3)==475
total_inc_dec(4)==1675
total_inc_dec(5)==4954
total_inc_dec(6)==12952
```

**Tips:** efficiency and trying to figure out how it works are essential: with a brute force approach, some tests with larger numbers may take more than the total computing power currently on Earth to be finished in the short allotted time.

To make it even clearer, the increasing or decreasing numbers between in the range 101-200 are: [110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 122, 123, 124, 125, 126, 127, 128, 129, 133, 134, 135, 136, 137, 138, 139, 144, 145, 146, 147, 148, 149, 155, 156, 157, 158, 159, 166, 167, 168, 169, 177, 178, 179, 188, 189, 199, 200], that is 47 of them. In the...

from math import factorial

def total_inc_dec(x):
    return comb(x + 10, 10) + comb(x + 9, 9) - 1 - (10 * x)

def comb(n, k):
    f = factorial
    return f(n) // f(k) // f(n-k)


Solve in Python:
Let's define a function countUniqueChars(s) that returns the number of unique characters on s, for example if s = "LEETCODE" then "L", "T","C","O","D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.

On this problem given a string s we need to return the sum of countUniqueChars(t) where t is a substring of s. Notice that some substrings can be repeated so on this case you have to count the repeated ones too.
Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.

Example 1:
Input: s = "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Evey substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10

Example 2:
Input: s = "ABA"
Output: 8
Explanation: The same as example 1, except countUniqueChars("ABA") = 1.

Example 3:
Input: s = "LEETCODE"
Output: 92

Constraints:

0 <= s.length <= 10^4
s contain upper-case English letters only.

class Solution:
    def uniqueLetterString(self, s: str) -> int:
        ans, d = 0, defaultdict(lambda: (-1, -1))
        for i, c in enumerate(s):
            ans += (d[c][1]-d[c][0])*(i-d[c][1])
            d[c] = (d[c][1], i)
        for c, pre in d.items():
            ans += (d[c][1]-d[c][0])*(len(s)-d[c][1])
        return ans


Solve in Python:
Let's define a periodic infinite sequence S$S$ (0$0$-indexed) with period K$K$ using the formula Si=(i%K)+1$S_i = (i \% K) + 1$.
Chef has found a sequence of positive integers A$A$ with length N$N$ buried underground. He suspects that it is a contiguous subsequence of some periodic sequence. Unfortunately, some elements of A$A$ are unreadable. Can you tell Chef the longest possible period K$K$ of an infinite periodic sequence which contains A$A$ (after suitably filling in the unreadable elements) as a contiguous subsequence?

-----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 a single integer N$N$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Unreadable elements are denoted by −1$-1$.

-----Output-----
For each test case, print a single line.
- If the period can be arbitrarily large, this line should contain a single string "inf".
- Otherwise, if A$A$ cannot be a contiguous subsequence of a periodic sequence, it should contain a single string "impossible".
- Otherwise, it should contain a single integer — the maximum possible period.

-----Constraints-----
- 1≤T≤100$1 \le T \le 100$
- 2≤N≤105$2 \le N \le 10^5$
- the sum of N$N$ over all test cases does not exceed 106$10^6$
- for each valid i$i$, 1≤Ai≤106$1 \le A_i \le 10^6$ or Ai=−1$A_i = -1$

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

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

-----Example Output-----
inf
4
impossible

# cook your dish here
from math import gcd
for _ in range(int(input())):
    n,a,k,min_k,e = int(input()),[int(i) for i in input().split()],0,0,-1
    for j in range(n):
     if(a[j] != -1):break
    for i in range(j,n):
     if min_k==0:min_k,e = a[i],a[i]+1
     else:
      if min_k < a[i]:min_k = a[i]
      if(a[i] == -1):pass
      else:
       if(a[i] == e):pass
       else:
        if( k == 0):k = e-a[i]
        else:
         new_k = e-a[i]
         if(new_k < 0):k = -1
         else:k = gcd(k,new_k)
        if(k<min_k or k<0): k = -1; break
      if k != 0 and a[i]!=-1: e = a[i]%k+1
      else:e += 1
    if(k == -1):print("impossible")
    elif k == 0 :print("inf")
    else:print(k)


Solve in Python:
Let's define the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$

Here $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes.

Your task is calculate $a_{K}$ for given $a_{1}$ and $K$.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of independent test cases.

Each test case consists of a single line containing two integers $a_{1}$ and $K$ ($1 \le a_{1} \le 10^{18}$, $1 \le K \le 10^{16}$) separated by a space.

-----Output-----

For each test case print one integer $a_{K}$ on a separate line.

-----Example-----
Input
8
1 4
487 1
487 2
487 3
487 4
487 5
487 6
487 7

Output
42
487
519
528
544
564
588
628

-----Note-----

$a_{1} = 487$

 $a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$

 $a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$

 $a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$

 $a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$

 $a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$

 $a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$

import sys

input = sys.stdin.readline

for _ in range(int(input())):
	a, k = list(map(int, input().split()))
	for _ in range(k - 1):
		if '0' in str(a):
			break
		a += int(min(list(str(a)))) * int(max(list(str(a))))
	print(a)


Solve in Python:
Let's define the niceness of a sequence of positive integers X1,X2,…,XN$X_1, X_2, \dots, X_N$ as the sum of greatest common divisors of all pairs of its elements, i.e.
N∑i=1N∑j=i+1gcd(Xi,Xj).∑i=1N∑j=i+1Ngcd(Xi,Xj).\sum_{i=1}^N \sum_{j=i+1}^N \mathrm{gcd}(X_i, X_j)\;.
For example, the niceness of the sequence [1,2,2]$[1, 2, 2]$ is gcd(1,2)+gcd(1,2)+gcd(2,2)=4$gcd(1, 2) + gcd(1, 2) + gcd(2, 2) = 4$.
You are given a sequence A1,A2,…,AN$A_1, A_2, \dots, A_N$; each of its elements is either a positive integer or missing.
Consider all possible ways to replace each missing element of A$A$ by a positive integer (not necessarily the same for each element) such that the sum of all elements is equal to S$S$. Your task is to find the total niceness of all resulting sequences, i.e. compute the niceness of each possible resulting sequence and sum up all these values. Since the answer may be very large, compute it modulo 109+7$10^9 + 7$.

-----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 S$S$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$. Missing elements in this sequence are denoted by −1$-1$.

-----Output-----
For each test case, print a single line containing one integer — the total niceness modulo 109+7$10^9 + 7$.

-----Constraints-----
- 1≤T≤20$1 \le T \le 20$
- 1≤N,S≤50$1 \le N, S \le 50$
- 1≤Ai≤50$1 \le A_i \le 50$ or Ai=−1$A_i = -1$ for each valid i$i$

-----Subtasks-----
Subtask #1 (30 points):
- 1≤N,S≤18$1 \le N, S \le 18$
- 1≤Ai≤18$1 \le A_i \le 18$ or Ai=−1$A_i = -1$ for each valid i$i$
Subtask #2 (70 points): original constraints

-----Example Input-----
3
3 3
1 1 -1
4 8
1 -1 -1 3
3 10
-1 -1 -1

-----Example Output-----
3
23
150

-----Explanation-----
Example case 1: There is only one possible way to fill in the missing element; the resulting sequence is [1,1,1]$[1, 1, 1]$. Its...

mod = 10**9 + 7
from math import gcd
def fac50():
    f = [0]*51
    f[0] ,f[1] = 1,1
    for i in range(1,51):f[i] = (f[i-1]*i)%mod
    return f
def gcd110():
    gc = [[0]*111 for i in range(111)]
    for i in range(111):
        for j in range(111):gc[i][j] = gcd(i,j)
    return gc
factorials,gcds = fac50(),gcd110()
def rule_asc(n,l):
    a,k = [0 for i in range(n + 1)],1
    a[1] = n
    while k != 0:
        x,y = a[k - 1] + 1,a[k] - 1
        k -= 1
        while x <= y and k < l - 1:
            a[k],y = x,y-x
            k += 1
        a[k] = x + y
        yield a[:k + 1]
def niceness(s):
    t = 0
    for i in range(len(s)):
        for j in range(i+1,len(s)):t = (t + gcds[s[i]][s[j]])%mod
    return t
def permcount(s,c):
    f,p = [s.count(x) for x in set(s)],factorials[c]
    for e in f:p = (p*pow(factorials[e],mod-2,mod))%mod
    return p
def main():
    for i in range(int(input())):
        n,s = [int(item) for item in input().split()]
        a = [int(item) for item in input().split()]
        b = [i for i in a if i != -1]
        s , ones = s - sum(b),a.count(-1)
        if s < 0:print(0)
        elif (s == 0 and ones == 0):print(niceness(a)%mod)
        elif (s > 0 and ones == 0):print(0)
        else:
            t = 0
            for seq in rule_asc(s,ones):
                if len(seq) == ones: t = (t + (((permcount(seq,ones))%mod)*(niceness(b+seq)%mod))%mod)%mod
            print(t)
def __starting_point():main()
__starting_point()


Solve in Python:
Let's denote as $\text{popcount}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer x.

You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and $\text{popcount}(x)$ is maximum possible. If there are multiple such numbers find the smallest of them.

-----Input-----

The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).

Each of the following n lines contain two integers l_{i}, r_{i} — the arguments for the corresponding query (0 ≤ l_{i} ≤ r_{i} ≤ 10^18).

-----Output-----

For each query print the answer in a separate line.

-----Examples-----
Input
3
1 2
2 4
1 10

Output
1
3
7

-----Note-----

The binary representations of numbers from 1 to 10 are listed below:

1_10 = 1_2

2_10 = 10_2

3_10 = 11_2

4_10 = 100_2

5_10 = 101_2

6_10 = 110_2

7_10 = 111_2

8_10 = 1000_2

9_10 = 1001_2

10_10 = 1010_2

import sys
L = lambda x : x.bit_length() if x > 0 else 1
n = int(input())
while n > 0:
    n -= 1
    l, r = list(map(int, sys.stdin.readline().split()))
    a = 0
    while L(l) == L(r) and  r > 0:
        u = 1 << (L(r) - 1)
        l-= u
        r-= u
        a+= u
    u = 1 << (L(r) - 1)
    if u + u - 1 == r and r > 1:
        u<<=1
    print(a+u-1)


Solve in Python:
Let's imagine we have a popular online RPG. A player begins with a score of 0 in class E5. A1 is the highest level a player can achieve.

Now let's say the players wants to rank up to class E4. To do so the player needs to achieve at least 100 points to enter the qualifying stage.

Write a script that will check to see if the player has achieved at least 100 points in his class. If so, he enters the qualifying stage.

In that case, we return, ```"Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up."```.

Otherwise return, ```False/false``` (according to the language n use).

NOTE:  Remember, in C# you have to cast your output value to Object type!

def playerRankUp(pts):
     return "Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up." if pts >= 100 else pts >= 100


Solve in Python:
Let's just place tokens on a connect four board.

** INPUT **

Provided as input the list of columns where a token is placed, from 0 to 6 included.
The first player starting is the yellow one (marked with `Y`), then the red (marked with `R`); the other cells might be empty and marked with `-`.

** OUTPUT **

The output is the state of the board after all the tokens in input have been placed.

** ASSUMPTIONS **

- The board is the standard 7x6;
- Of course you'll need to deal with gravity;
- You don't need to hassle with wrong input, wrong column numbers, checking for full column or going off the board;
- the columns list will always include proper column numbers;
- Notice: when you read the results in tests, the highest row appears first and the lowest row appears last; debugging using `\n` after each row might help (check example);

** EXAMPLES **

1.
```
Moves = [0,1,2,5,6]

Result:
['-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-']
['Y', 'R', 'Y', '-', '-', 'R', 'Y']
```
2.
```
Moves = [0,1,2,5,6,2,0,0]

Result:
['-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', '-', '-', '-']
['R', '-', '-', '-', '-', '-', '-']
['Y', '-', 'R', '-', '-', '-', '-']
['Y', 'R', 'Y', '-', '-', 'R', 'Y']
```

See test cases for better details.

def connect_four_place(columns):
    mat = [[] for _ in range(7)]
    ply = 0
    for col in columns:
        mat[col].append('YR'[ply])
        ply ^= 1
    for col in mat:
        while len(col) < 6: col.append('-')
    return [list(row) for row in zip(*mat)][::-1]


Solve in Python:
Let's look at the following process: initially you have an empty stack and an array $s$ of the length $l$. You are trying to push array elements to the stack in the order $s_1, s_2, s_3, \dots s_{l}$. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack.

If after this process the stack remains empty, the array $s$ is considered stack exterminable.

There are samples of stack exterminable arrays:   $[1, 1]$;  $[2, 1, 1, 2]$;  $[1, 1, 2, 2]$;  $[1, 3, 3, 1, 2, 2]$;  $[3, 1, 3, 3, 1, 3]$;  $[3, 3, 3, 3, 3, 3]$;  $[5, 1, 2, 2, 1, 4, 4, 5]$;

Let's consider the changing of stack more details if $s = [5, 1, 2, 2, 1, 4, 4, 5]$ (the top of stack is highlighted).   after pushing $s_1 = 5$ the stack turn into $[\textbf{5}]$;  after pushing $s_2 = 1$ the stack turn into $[5, \textbf{1}]$;  after pushing $s_3 = 2$ the stack turn into $[5, 1, \textbf{2}]$;  after pushing $s_4 = 2$ the stack turn into $[5, \textbf{1}]$;  after pushing $s_5 = 1$ the stack turn into $[\textbf{5}]$;  after pushing $s_6 = 4$ the stack turn into $[5, \textbf{4}]$;  after pushing $s_7 = 4$ the stack turn into $[\textbf{5}]$;  after pushing $s_8 = 5$ the stack is empty.

You are given an array $a_1, a_2, \ldots, a_n$. You have to calculate the number of its subarrays which are stack exterminable.

Note, that you have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries.

The first line of each query contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the length of array $a$.

The second line of each query contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$) — the elements.

It is guaranteed that the sum of all $n$ over all queries does not exceed $3 \cdot 10^5$.

-----Output-----

For each test case print one...

# encoding: utf-8
from sys import stdin

def solve(a):
    # root node of tries denotes empty stack
    stack = [None]
    node_stack = [[1, {}]]

    counter = 0
    for i in range(len(a)):
        el = a[i]

        if len(stack) == 0 or stack[-1] != el:

            current_node = node_stack[-1]
            stack.append(el)
            if el not in current_node[1]:
                current_node[1][el] = [0, {}]

            next_node = current_node[1][el]
            next_node[0] += 1
            node_stack.append(next_node)

        else:
            # just go up in trie
            stack.pop()
            node_stack.pop()
            node_stack[-1][0] += 1

        value = node_stack[-1][0]
        counter += (value - 1)

    return counter

q = int(stdin.readline().strip())
for _ in range(q):
    n = int(stdin.readline().strip())
    a = [int(i) for i in stdin.readline().strip().split()]
    print(solve(a))