Solve in Python:
You are given K eggs, and you have access to a building with N floors from 1 to N.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break.
Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).
Your goal is to know with certainty what the value of F is.
What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?

Example 1:
Input: K = 1, N = 2
Output: 2
Explanation:
Drop the egg from floor 1.  If it breaks, we know with certainty that F = 0.
Otherwise, drop the egg from floor 2.  If it breaks, we know with certainty that F = 1.
If it didn't break, then we know with certainty F = 2.
Hence, we needed 2 moves in the worst case to know what F is with certainty.

Example 2:
Input: K = 2, N = 6
Output: 3

Example 3:
Input: K = 3, N = 14
Output: 4

Note:

1 <= K <= 100
1 <= N <= 10000

#class Solution:
#    def superEggDrop(self, K: int, N: int) -> int:
#        def solve(e,f,dp):
#            if f==0:
#                return f
#            elif e==1:
#                return f
#
#            if dp[e][f]!=-1:
#                return dp[e][f]
#            l,h=1,f
#            while l+1<h:
#                x=(l+h)//2
#                if dp[e][f-x]!=-1:
#                    f1=dp[e][f-x]
#                else:
#                    f1=solve(e,f-x,dp)
#                if dp[e-1][x-1]!=-1:
#                    f2=dp[e-1][x-1]
#                else:
#                    f2=solve(e-1,x-1,dp)
#                if f1<f2:
#                    l=x
#                elif f2>f1:
#                    h=x
#                else:
#                    l=h=x
#
#            ans=1+min(max(solve(e,f-x,dp),solve(e,x-1,dp)) for x in range(l,h+1))
#            dp[e][f]=ans
#            return dp[e][f]
#        dp=[[-1]*(N+1) for i in range(K+1)]
#        return solve(K,N,dp)
class Solution(object):
    def superEggDrop(self, K, N):
        memo = {}
        def dp(k, n):
            if (k, n) not in memo:
                if n == 0:
                    ans = 0
                elif k == 1:
                    ans = n
                else:
                    lo, hi = 1, n
                    # keep a gap of 2 X values to manually check later
                    while lo + 1 < hi:
                        x = (lo + hi) // 2
                        t1 = dp(k-1, x-1)
                        t2 = dp(k, n-x)

                        if t1 < t2:
                            lo = x
                        elif t1 > t2:
                            hi = x
                        else:
                            lo = hi = x
                    ans=1000000
                    for x in range(lo, hi+1):
                            temp=1+max(dp(k-1, x-1), dp(k, n-x))
                            if ans>temp:
                                ans=temp

               ...


Solve in Python:
You are given N integer sequences A1, A2, ..., AN. Each of these sequences contains N elements. You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1.
Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead.

-----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.
- N lines follow. For each valid i, the i-th of these lines contains N space-separated integers Ai1, Ai2, ..., AiN denoting the elements of the sequence Ai.

-----Output-----
For each test case, print a single line containing one integer — the maximum sum of picked elements.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 700
- 1 ≤ sum of N in all test-cases ≤ 3700
- 1 ≤ Aij ≤ 109 for each valid i, j

-----Subtasks-----
Subtask #1 (18 points): 1 ≤ Aij ≤ N for each valid i, j
Subtask #2 (82 points): original constraints

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

1
3
1 2 3
4 5 6
7 8 9

Output:

18

-----Explanation-----
Example case 1: To maximise the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18.

for i in range(int(input())):
 n=int(input())
 b=[]
 counter=0
 for j in range(n):
  b.append(list(map(int,input().split())))
 c=max(b[-1])
 sum=c
 for k in range(1,n):
  for x in b[-k-1]:
   if(x<c and x>counter):
    counter=x
  if(counter==0):
   print(-1)
   sum=0
   break
  else:
   sum=sum+counter
   c=counter
   counter=0
 if(sum!=0):
  print(sum)


Solve in Python:
You are given Name of chef's friend and using chef's new method of calculating value of string , chef have to find the value of all the names. Since chef is busy , he asked you to do the work from him .
The method is a function $f(x)$ as follows -
-
$f(x)$ = $1$ , if $x$ is a consonent
-
$f(x)$ = $0$ , if $x$ is a vowel
Your task is to apply the above function on all the characters in the string $S$ and convert the obtained binary string in decimal number N. Since the number N can be very large, compute it modulo $10^9+7$ .
Input:
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each test line contains one String $S$ composed of lowercase English alphabet letters.

-----Output:-----
For each case, print a single line containing one integer $N$ modulo  $10^9+7$ .

-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq |S| \leq 10^5$

-----Sample Input:-----
1
codechef

-----Sample Output:-----
173

-----EXPLANATION:-----
The string "codechef" will be converted to 10101101 ,using the chef's method function . Which is equal to 173.

test=int(input())
for _ in range(test):
 s=input()
 a=""
 for i in s:
  if i != "\r":
   if i in ["a","e","i","o","u"]:
    a+="0"
   else:
    a+="1"
 ans=int(a,2)
 print(ans%(1000000000+7))


Solve in Python:
You are given a 1×1×2$1 \times 1 \times 2$ bar (a cuboid) and a grid A$A$ with N$N$ rows (numbered 1$1$ through N$N$) and M$M$ columns (numbered 1$1$ through M$M$). Let's denote the cell in row r$r$ and column c$c$ by (r,c)$(r, c)$. Some cells of the grid are blocked, the remaining cells are free.
Each cell has dimensions 1×1$1 \times 1$, the same as two opposite faces of the cuboid. When the bar is placed on the grid in such a way that one of its two 1×1$1 \times 1$ faces fully covers a cell (r,c)$(r, c)$, we say that the bar is standing on the cell (r,c)$(r, c)$. Initially, the bar is standing on a cell (x,y)$(x, y)$.
When the bar is placed on the grid, one of its faces is touching the grid; this face is called the base. In one move, you must roll the bar over one of its base edges (sides of the base); this base edge does not move and the bar is rotated 90∘$90^\circ$ around it in such a way that it is still lying on the grid, but with a different base. In different moves, the bar may be rotated around different edges in different directions. After each move, the base of the bar must lie fully inside the grid and it must not cover any blocked cells.
An example sequence of moves is shown here.
For each cell of the grid, determine the minimum number of moves necessary to achieve the state where the bar is standing on this cell or determine that it is impossible to achieve.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- The second line contains two space-separated integers x$x$ and y$y$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains M$M$ integers Ai,1,Ai,2,…,Ai,M$A_{i, 1}, A_{i, 2}, \ldots, A_{i, M}$ (a string with length M$M$). For each valid i,j$i, j$, Ai,j=0$A_{i, j} = 0$ denotes that the cell (i,j)$(i, j)$ is blocked and Ai,j=1$A_{i, j} = 1$ denotes that it is...

def issafe(r,c,r1,c1,graph,n,m):
    if (r>-1 and r1>-1 and c>-1 and c1>-1 and r<n and r1<n and c<m and c1<m and graph[r][c] and graph[r1][c1]):
        return True
    return False

t=int(input())
for mmmmmm in range(t):
    n,m=map(int,input().split())
    x,y=map(int,input().split())

    graph=[[False]*m for _ in range(n)]

    cost_graph=[[[-1,-1,-1] for __ in range(m)] for _ in range(n)]

    for i in range(n):
        str1=input()
        for j,val in enumerate(str1):
            graph[i][j]=(val=='1')

    x=x-1
    y=y-1

    set1=set()
    set1.add((x,y,0))
    cost_graph[x][y][0]=0
    while(set1):

        set2=set()

        while(set1):
            r,c,p=set1.pop()

            new_cost=cost_graph[r][c][p]+1

            if(p==0):
                if issafe(r,c+1,r,c+2,graph,n,m):
                    if cost_graph[r][c+1][1]==-1 or cost_graph[r][c+1][1]>new_cost:
                        cost_graph[r][c+1][1]=new_cost
                        set2.add((r,c+1,1))

                if issafe(r+1,c,r+2,c,graph,n,m):
                    if cost_graph[r+1][c][2]==-1 or cost_graph[r+1][c][2]>new_cost:
                        cost_graph[r+1][c][2]=new_cost
                        set2.add((r+1,c,2))

                if issafe(r,c-2,r,c-1,graph,n,m):
                    if cost_graph[r][c-2][1]==-1 or cost_graph[r][c-2][1]>new_cost:
                        cost_graph[r][c-2][1]=new_cost
                        set2.add((r,c-2,1))

                if issafe(r-2,c,r-1,c,graph,n,m):
                    if cost_graph[r-2][c][2]==-1 or cost_graph[r-2][c][2]>new_cost:
                        cost_graph[r-2][c][2]=new_cost
                        set2.add((r-2,c,2))

            elif(p==1):
                if issafe(r,c+2,r,c+2,graph,n,m):
                    if cost_graph[r][c+2][0]==-1 or...


Solve in Python:
You are given a Young diagram.

Given diagram is a histogram with $n$ columns of lengths $a_1, a_2, \ldots, a_n$ ($a_1 \geq a_2 \geq \ldots \geq a_n \geq 1$). [Image] Young diagram for $a=[3,2,2,2,1]$.

Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a $1 \times 2$ or $2 \times 1$ rectangle.

-----Input-----

The first line of input contain one integer $n$ ($1 \leq n \leq 300\,000$): the number of columns in the given histogram.

The next line of input contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 300\,000, a_i \geq a_{i+1}$): the lengths of columns.

-----Output-----

Output one integer: the largest number of non-overlapping dominos that you can draw inside of the given Young diagram.

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

Output
4

-----Note-----

Some of the possible solutions for the example:

[Image] $\square$

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

ans = 0
black = 0
white = 0
for i in range(n):
    if i % 2 == 0:
        black += a[i] // 2
        white += a[i] - a[i] // 2
    elif i % 2 == 1:
        white += a[i] // 2
        black += a[i] - a[i] // 2

print(min(white, black))


Solve in Python:
You are given a binary string $s$ (recall that a string is binary if each character is either $0$ or $1$).

Let $f(t)$ be the decimal representation of integer $t$ written in binary form (possibly with leading zeroes). For example $f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$ and $f(000100) = 4$.

The substring $s_{l}, s_{l+1}, \dots , s_{r}$ is good if $r - l + 1 = f(s_l \dots s_r)$.

For example string $s = 1011$ has $5$ good substrings: $s_1 \dots s_1 = 1$, $s_3 \dots s_3 = 1$, $s_4 \dots s_4 = 1$, $s_1 \dots s_2 = 10$ and $s_2 \dots s_4 = 011$.

Your task is to calculate the number of good substrings of string $s$.

You have to answer $t$ independent queries.

-----Input-----

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

The only line of each query contains string $s$ ($1 \le |s| \le 2 \cdot 10^5$), consisting of only digits $0$ and $1$.

It is guaranteed that $\sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5$.

-----Output-----

For each query print one integer — the number of good substrings of string $s$.

-----Example-----
Input
4
0110
0101
00001000
0001000

Output
4
3
4
3

def main():
    from sys import stdin, stdout
    input = stdin.readline
    print = stdout.write
    for _ in range(int(input())):
        ans = 0
        i = -1
        s = input()
        for j in range(len(s) - 1):
            if s[j] == '1':
                c = 0
                for k in range(j, len(s)):
                    c = c * 2 + (s[k] == '1') + (s[k] == '\n') * k
                    if k - i < c:
                        ans += k - j
                        break
                i = j
        print(f'{ans}\n')

main()


Solve in Python:
You are given a binary string $s$ consisting of $n$ zeros and ones.

Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).

Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the test case contains $n$ characters '0' and '1' — the string $s$.

It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).

-----Output-----

For each test case, print the answer: in the first line print one integer $k$ ($1 \le k \le n$) — the minimum number of subsequences you can divide the string $s$ to. In the second line print $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the number of subsequence the $i$-th character of $s$ belongs to.

If there are several answers, you can print any.

-----Example-----
Input
4
4
0011
6
111111
5
10101
8
01010000

Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4

def solve():
    n = int(input())
    s = input()
    z, o = [], []
    c = 0
    ans = []
    def add(x):
        nonlocal z, o, c, ans
        u, v = z, o
        if x == 0:
            u, v = v, u
        if u:
            w = u.pop()
            ans.append(w)
            v.append(w)
        else:
            c += 1
            ans.append(c)
            v.append(c)
    for i in s:
        add(int(i))
    print(c)
    print(*ans)

t = int(input())
for _ in range(t):
    solve()


Solve in Python:
You are given a binary string S of N bits. The bits in the string are indexed starting from 1. S[i] denotes the ith bit of S.

Let's say that a sequence i1, i2, …, iK(1 ≤ K; 1 ≤ i1 < i2 < … < iK ≤ N) produces a palindrome when applied to S, if the string S[i1] S[i2] … S[ik] is a palindrome (that is, reads the same backward or forward).

In addition, a sequence i1, i2, …, iK(1 ≤ K; 1 ≤ i1 < i2 < … < iK ≤ N) is said to be exponential, if ij + 1 = p * ij for each integer 1 ≤ j < K and for some integer p > 1. Note, that a sequence of one element is always exponential.

Your task is to count the number of exponential sequences that produce a palindrome when applied to S.

-----Input-----
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.

The only line of description for each test case contains a binary string S of N bits.

-----Output-----

For each test case, output a single line containing the number of exponential sequences that produce a palindrome.

-----Constraints-----
- 1 ≤ T ≤ 10
- Subtask 1(20 points): 1 ≤ N ≤ 20
- Subtask 2(30 points): 1 ≤ N ≤ 1000
- Subtask 3(50 points): 1 ≤ N ≤ 5 × 105

-----Note-----

The first test of the first subtask is the example test. It's made for you to make sure that your solution produces the same verdict both on your machine and our server.

-----Time Limits-----

Time limit for the first and the second subtasks is 3s. Time limit for the third subtask is 6s.

-----Example-----
Input:
2
11010
101001011

Output:
9
18

-----Explanation of the first case in the example test-----

The following sequences are counted in the answer: {1}, {2}, {3}, {4}, {5}, {1, 2}, {1, 4}, {2, 4}, {1, 2, 4}.

def checkPalindrome(string):
    if(string==string[::-1]):
        return 1
    else:
        return 0
t=int(eval(input()))
while(t):
    ip_string=input()
    length_of_str=len(ip_string)
    p=2
    count=length_of_str
    while(p<=length_of_str):
        for i in range(1,length_of_str+1):
            temp_str=ip_string[i-1]
            j=i*p
            while(j<=length_of_str):
                temp_str+=ip_string[j-1]
                if(checkPalindrome(temp_str)==1):
                    count+=1
                j=j*p

        p+=1
    print(count)
    t-=1


Solve in Python:
You are given a binary string S. You need to transform this string into another string of equal length consisting only of zeros, with the minimum number of operations.
A single operation consists of taking some prefix of the string S and flipping all its values. That is, change all the 0s in this prefix to 1s, and all the 1s in the prefix to 0s. You can use this operation as many number of times as you want over any prefix of the string.

-----Input-----
The only line of the input contains the binary string,  S .

-----Output-----
Output a single line containing one integer, the minimum number of operations that are needed to transform the given string S into the string of equal length consisting only of zeros.

-----Constraints-----
- 1 ≤ |S| ≤ 100,000

-----Subtasks-----
- Subtask #1 (30 points): 1 ≤ |S| ≤ 2000
- Subtask #2 (70 points): Original constraints.

-----Example-----
Input:
01001001

Output:
6

-----Explanation-----
For the given sample case, let us look at the way where we achieved minimum number of operations.

Operation 1: You flip values in the prefix of length 8 and transform the string into 10110110
Operation 2: You flip values in the prefix of length 7 and transform the string into 01001000
Operation 3: You flip values in the prefix of length 5 and transform the string into 10110000
Operation 4: You flip values in the prefix of length 4 and transform the string into 01000000
Operation 5: You flip values in the prefix of length 2 and transform the string into 10000000
Operation 6: You flip values in the prefix of length 1 and finally, transform the string into 00000000

# cook your dish here
s=input()
s=list(s)
n,c=0,0

j=0
while(n!=1):
 j+=1

 p=-1
 for i in range(len(s)-2,-1,-1):
  if(j%2!=0):

   if(s[i]=='0'):
    p=i
    break
  else:

   if(s[i]=='1'):
    p=i
    break

 if(p!=-1):
  c+=1

 s=s[0:p+1]

 if(len(s)==1) or (len(s)==0):
  n=1

print(c+1)


Solve in Python:
You are given a binary tree:

```python
class Node:
    def __init__(self, L, R, n):
        self.left = L
        self.right = R
        self.value = n
```

Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.
```if:ruby
Return empty array if root is `nil`.
```
```if:haskell
Return empty list if root is `Nothing`.
```
```if:python
Return empty list if root is `None`.
```
```if:csharp
Return empty list if root is 'null'.
```
```if:java
Return empty list is root is 'null'.
```

Example 1 - following tree:

                     2
                8        9
              1  3     4   5

Should return following list:

    [2,8,9,1,3,4,5]

Example 2 - following tree:

                     1
                8        4
                  3        5
                             7
Should return following list:

    [1,8,4,3,5,7]

def tree_by_levels(node):
  return [v for v, _, _ in sorted(extract_nodes(node), key = lambda x: (x[1], x[2]))]

def extract_nodes(node, lvl=0, directions=[]):
  if node:
    return [(node.value, lvl, directions)] + extract_nodes(node.left, lvl+1, directions + [-1]) + extract_nodes(node.right, lvl+1, directions + [1])
  return []


Solve in Python:
You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\frac{n}{2}$ opening brackets '(' and $\frac{n}{2}$ closing brackets ')'.

In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $i$, remove the $i$-th character of $s$ and insert it before or after all remaining characters of $s$).

Your task is to find the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints.

Recall what the regular bracket sequence is:

  "()" is regular bracket sequence;  if $s$ is regular bracket sequence then "(" + $s$ + ")" is regular bracket sequence;  if $s$ and $t$ are regular bracket sequences then $s$ + $t$ is regular bracket sequence.

For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains one integer $n$ ($2 \le n \le 50$) — the length of $s$. It is guaranteed that $n$ is even. The second line of the test case containg the string $s$ consisting of $\frac{n}{2}$ opening and $\frac{n}{2}$ closing brackets.

-----Output-----

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $s$. It can be proved that the answer always exists under the given constraints.

-----Example-----
Input
4
2
)(
4
()()
8
())()()(
10
)))((((())

Output
1
0
1
3

-----Note-----

In the first test case of the example, it is sufficient to move the first bracket to the end of the string.

In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.

In the fourth test case of the example, we can...

import sys
input = sys.stdin.readline

t=int(input())
for tests in range(t):
    n=int(input())
    S=input().strip()

    MIN=0
    NOW=0
    for s in S:
        if s=="(":
            NOW+=1
        else:
            NOW-=1
            MIN=min(NOW,MIN)

    print(-MIN)


Solve in Python:
You are given a certain integer, ```n, n > 0```. You have to search the partition or partitions, of n, with maximum product value.

Let'see the case for ```n = 8```.
```
Partition                 Product
[8]                          8
[7, 1]                       7
[6, 2]                      12
[6, 1, 1]                    6
[5, 3]                      15
[5, 2, 1]                   10
[5, 1, 1, 1]                 5
[4, 4]                      16
[4, 3, 1]                   12
[4, 2, 2]                   16
[4, 2, 1, 1]                 8
[4, 1, 1, 1, 1]              4
[3, 3, 2]                   18   <---- partition with maximum product value
[3, 3, 1, 1]                 9
[3, 2, 2, 1]                12
[3, 2, 1, 1, 1]              6
[3, 1, 1, 1, 1, 1]           3
[2, 2, 2, 2]                16
[2, 2, 2, 1, 1]              8
[2, 2, 1, 1, 1, 1]           4
[2, 1, 1, 1, 1, 1, 1]        2
[1, 1, 1, 1, 1, 1, 1, 1]     1
```
So our needed function will work in that way for Python and Ruby:
```
find_part_max_prod(8) == [[3, 3, 2], 18]
```
For javascript
```
findPartMaxProd(8) --> [[3, 3, 2], 18]
```
If there are more than one partition with maximum product value, the function should output the patitions in a length sorted way.
Python and Ruby
```
find_part_max_prod(10) == [[4, 3, 3], [3, 3, 2, 2], 36]
```
Javascript
```
findPartMaxProd(10) --> [[4, 3, 3], [3, 3, 2, 2], 36]
```
Enjoy it!


Solve in Python:
You are given a colored permutation $p_1, p_2, \dots, p_n$. The $i$-th element of the permutation has color $c_i$.

Let's define an infinite path as infinite sequence $i, p[i], p[p[i]], p[p[p[i]]] \dots$ where all elements have same color ($c[i] = c[p[i]] = c[p[p[i]]] = \dots$).

We can also define a multiplication of permutations $a$ and $b$ as permutation $c = a \times b$ where $c[i] = b[a[i]]$. Moreover, we can define a power $k$ of permutation $p$ as $p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$.

Find the minimum $k > 0$ such that $p^k$ has at least one infinite path (i.e. there is a position $i$ in $p^k$ such that the sequence starting from $i$ is an infinite path).

It can be proved that the answer always exists.

-----Input-----

The first line contains single 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 contains single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the permutation.

The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, $p_i \neq p_j$ for $i \neq j$) — the permutation $p$.

The third line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le n$) — the colors of elements of the permutation.

It is guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$.

-----Output-----

Print $T$ integers — one per test case. For each test case print minimum $k > 0$ such that $p^k$ has at least one infinite path.

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

Output
1
5
2

-----Note-----

In the first test case, $p^1 = p = [1, 3, 4, 2]$ and the sequence starting from $1$: $1, p[1] = 1, \dots$ is an infinite path.

In the second test case, $p^5 = [1, 2, 3, 4, 5]$ and it obviously contains several infinite paths.

In the third test case, $p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$ and the sequence starting from $4$: $4, p^2[4]=8, p^2[8]=4, \dots$ is an infinite path since $c_4 = c_8 = 4$.

from sys import stdin
input = stdin.readline
q = int(input())
for rwerew in range(q):
	n = int(input())
	p = list(map(int,input().split()))
	c = list(map(int,input().split()))
	for i in range(n):
		p[i] -= 1
	przyn = [0] * n
	grupa = []
	i = 0
	while i < n:
		if przyn[i] == 1:
			i += 1
		else:
			nowa_grupa = [i]
			j = p[i]
			przyn[i] = 1
			while j != i:
				przyn[j] = 1
				nowa_grupa.append(j)
				j = p[j]
			grupa.append(nowa_grupa)
	grupacol = []
	for i in grupa:
		cyk = []
		for j in i:
			cyk.append(c[j])
		grupacol.append(cyk)
	#print(grupacol)
	mini = 234283742834
	for cykl in grupacol:
		dziel = []
		d =  1
		while d**2 <= len(cykl):
			if len(cykl)%d == 0:
				dziel.append(d)
			d += 1
		dodat = []
		for d in dziel:
			dodat.append(len(cykl)/d)
		dziel_ost = list(map(int,dziel + dodat))
		#print(dziel_ost, len(cykl))
		for dzielnik in dziel_ost:
			for i in range(dzielnik):
				indeks = i
				secik = set()
				chuj = True
				while indeks < len(cykl):
					secik.add(cykl[indeks])
					indeks += dzielnik
					if len(secik) > 1:
						chuj = False
						break
				if chuj:
					mini = min(mini, dzielnik)
	print(mini)


Solve in Python:
You are given a convex polygon $P$ with vertices $P_0, P_1, \ldots, P_{n-1}$, each having integer coordinates. On each edge $P_{i} P_{(i+1) \% n}$ of the polygon, choose a point $R_i$ uniformly at random. What is the expected area of the convex hull of these $n$ chosen points $R_0, R_1, \ldots R_{n-1}$ ?

-----Note-----
- Consider the area of the convex hull as zero if it contains less than 3 vertices.
- All the points $R_i$ are chosen independently of each other.
- Your answer is considered correct if and only if its absolute or relative error doesn't exceed $10^{-6}$.

-----Input-----
- The first line contains $n$, the number of vertices in the convex polygon.
- The next $n$ lines contain the coordinates of the vertices of the polygon in anti-clockwise order.

-----Output-----
For each testcase, print the expected area of the convex hull of the $n$ randomly chosen points.

-----Constraints-----
- $3 \leq n \leq 10^5$
- The absolute values of all the coordinates $\leq 10^7$.
- All the points in the input are distinct.
- The described polygon $P$ is convex and the vertices of the polygon are given in anti-clockwise order. Also, no three vertices of the polygon are collinear.

-----Example Input-----
3
0 0
1 0
0 1

-----Example Output-----
0.1250000000

# cook your dish here
def polygonArea(X, Y, n):
 area = 0.0
 j = n - 1
 for i in range(0, n):
  area += (X[j]*Y[i] - Y[j]*X[i])
  j = i
 return (abs(area / 2.0))
X=[]
Y=[]
xy=[]
n=int(input())
for i in range(n):
 xy.append(list(map(int,input().split())))
for i in range((n-1)):
 X.append((xy[i][0]+xy[i+1][0])/2)
 Y.append((xy[i][1]+xy[i+1][1])/2)
X.append((xy[0][0]+xy[n-1][0])/2)
Y.append((xy[0][1]+xy[n-1][1])/2)
print(polygonArea(X, Y, n))


Solve in Python:
You are given a dataset consisting of $N$ items. Each item is a pair of a word and a boolean denoting whether the given word is a spam word or not.
We want to use this dataset for training our latest machine learning model. Thus we want to choose some subset of this dataset as training dataset. We want to make sure that there are no contradictions in our training set, i.e. there shouldn't be a word included in the training set that's marked both as spam and not-spam. For example item {"fck", 1}, and item {"fck, 0"} can't be present in the training set, because first item says the word "fck" is a spam, whereas the second item says it is not, which is a contradiction.
Your task is to select the maximum number of items in the training set.
Note that same pair of {word, bool} can appear multiple times in input. The training set can also contain the same pair multiple times.

-----Input-----
- First line will contain $T$, number of test cases. Then the test cases follow.
- The first line of each test case contains a single integer $N$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains a string $w_i$, followed by a space and an integer(boolean) $s_i$, denoting the $i$-th item.

-----Output-----
For each test case, output an integer corresponding to the maximum number of items that can be included in the training set in a single line.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 25,000$
- $1 \le |w_i| \le 5$ for each valid $i$
- $0 \le s_i \le 1$ for each valid $i$
- $w_1, w_2, \ldots, w_N$ contain only lowercase English letters

-----Example Input-----
3
3
abc 0
abc 1
efg 1
7
fck 1
fck 0
fck 1
body 0
body 0
body 0
ram 0
5
vv 1
vv 0
vv 0
vv 1
vv 1

-----Example Output-----
2
6
3

-----Explanation-----
Example case 1: You can include either of the first and the second item, but not both. The third item can also be taken. This way the training set can contain at the very max 2 items.
Example case 2: You can include all the items except the second item in the training set.

t=int(input())
ans=[]
for i in range(t):
    count=0
    d=dict()
    n=int(input())
    count=0
    for j in range(n):
        x,y=input().split()
        y=int(y)
        if(x not in d):
            d[x]=[0,0]
        d[x][y]+=1
    for i in d:
        count+=max(d[i])
    ans.append(count)
for i in ans:
    print(i)


Solve in Python:
You are given a directed graph of $n$ vertices and $m$ edges. Vertices are numbered from $1$ to $n$. There is a token in vertex $1$.

The following actions are allowed:   Token movement. To move the token from vertex $u$ to vertex $v$ if there is an edge $u \to v$ in the graph. This action takes $1$ second.  Graph transposition. To transpose all the edges in the graph: replace each edge $u \to v$ by an edge $v \to u$. This action takes increasingly more time: $k$-th transposition takes $2^{k-1}$ seconds, i.e. the first transposition takes $1$ second, the second one takes $2$ seconds, the third one takes $4$ seconds, and so on.

The goal is to move the token from vertex $1$ to vertex $n$ in the shortest possible time. Print this time modulo $998\,244\,353$.

-----Input-----

The first line of input contains two integers $n, m$ ($1 \le n, m \le 200\,000$).

The next $m$ lines contain two integers each: $u, v$ ($1 \le u, v \le n; u \ne v$), which represent the edges of the graph. It is guaranteed that all ordered pairs $(u, v)$ are distinct.

It is guaranteed that it is possible to move the token from vertex $1$ to vertex $n$ using the actions above.

-----Output-----

Print one integer: the minimum required time modulo $998\,244\,353$.

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

Output
2

Input
4 3
2 1
2 3
4 3

Output
10

-----Note-----

The first example can be solved by transposing the graph and moving the token to vertex $4$, taking $2$ seconds.

The best way to solve the second example is the following: transpose the graph, move the token to vertex $2$, transpose the graph again, move the token to vertex $3$, transpose the graph once more and move the token to vertex $4$.

import sys
input = sys.stdin.readline
import heapq

mod=998244353

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

E=[[] for i in range(n+1)]
E2=[[] for i in range(n+1)]

for i in range(m):
    x,y=list(map(int,input().split()))
    E[x].append(y)
    E2[y].append(x)

TIME=[1<<29]*(n+1)
TIME[1]=0

def shuku(x,y):
    return (x<<20)+y

Q=[]
ANS=[]

for k in range(n+1):
    NQ=[]

    if k<=1:
        heapq.heappush(Q,shuku(0,1))

    if k%2==0:
        while Q:
            #print(Q)
            x=heapq.heappop(Q)
            time=x>>20
            town=x-(time<<20)

            #print(x,time,town)

            if TIME[town]<time:
                continue

            for to in E[town]:
                if TIME[to]>time+1:
                    TIME[to]=time+1
                    heapq.heappush(Q,shuku(TIME[to],to))
                    heapq.heappush(NQ,shuku(TIME[to],to))

    else:
        while Q:
            x=heapq.heappop(Q)
            time=x>>20
            town=x-(time<<20)

            #print(x,time,town)

            if TIME[town]<time:
                continue

            for to in E2[town]:
                if TIME[to]>time+1:
                    TIME[to]=time+1
                    heapq.heappush(Q,shuku(TIME[to],to))
                    heapq.heappush(NQ,shuku(TIME[to],to))

    #print(k,TIME)

    Q=NQ
    ANS.append(TIME[n])

    if k>=100 and TIME[n]!=1<<29:
        break

A=ANS[0]
for k in range(1,len(ANS)):
    if ANS[k]==1<<29:
        continue

    if ANS[k-1]==1<<29:
        A=(ANS[k]+pow(2,k,mod)-1)%mod

    if k<60 and ANS[k-1]-ANS[k]>pow(2,k-1):
        A=(ANS[k]+pow(2,k,mod)-1)%mod

print(A)


Solve in Python:
You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$.

In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).

The garland is called $k$-periodic if the distance between each pair of adjacent turned on lamps is exactly $k$. Consider the case $k=3$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.

Your task is to find the minimum number of moves you need to make to obtain $k$-periodic garland from the given one.

You have to answer $t$ independent test cases.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 25~ 000$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 10^6; 1 \le k \le n$) — the length of $s$ and the required period. The second line of the test case contains the string $s$ consisting of $n$ characters '0' and '1'.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^6$ ($\sum n \le 10^6$).

-----Output-----

For each test case, print the answer — the minimum number of moves you need to make to obtain $k$-periodic garland from the given one.

-----Example-----
Input
6
9 2
010001010
9 3
111100000
7 4
1111111
10 3
1001110101
1 1
1
1 1
0

Output
1
2
5
4
0
0

import sys

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n, k = nm()
    s = list(map(int, list(ns())))
    w = sum(s)
    sc = n
    for i in range(k):
        t = s[i::k]
        m = len(t)
        dp = [[0]*3 for j in range(m+1)]
        for j in range(m):
            dp[j+1][0] = dp[j][0] + t[j]
            dp[j+1][1] = min(dp[j][0], dp[j][1]) + 1 - t[j]
            dp[j+1][2] = min(dp[j][1], dp[j][2]) + t[j]
        sc = min(sc, min(dp[m]) + w - sum(t))
    print(sc)
    return

# solve()

T = ni()
for _ in range(T):
    solve()


Solve in Python:
You are given a graph consisting of $n$ vertices and $m$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.

You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains two integers $n$ and $m$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$) — the number of vertices and the number of edges in the graph, respectively.

The next $m$ lines describe edges of the graph. The $i$-th edge is described with three integers $t_i$, $x_i$ and $y_i$ ($t_i \in [0; 1]$, $1 \le x_i, y_i \le n$) — the type of the edge ($t_i = 0$ if the edge is undirected and $t_i = 1$ if the edge is directed) and vertices this edge connects (the undirected edge connects vertices $x_i$ and $y_i$ and directed edge is going from the vertex $x_i$ to the vertex $y_i$). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair ($x_i, y_i$) there are no other pairs ($x_i, y_i$) or ($y_i, x_i$)).

It is guaranteed that both sum $n$ and sum $m$ do not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$; $\sum m \le 2 \cdot 10^5$).

-----Output-----

For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and $m$ lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already...

from sys import stdin
from collections import deque
tt = int(stdin.readline())

for loop in range(tt):

    Query = []
    ans = []

    n,m = list(map(int,stdin.readline().split()))
    lis = [ [] for i in range(n) ]
    inum = [0] * n
    ilis = inum
    index = [None] * n

    for i in range(m):

        st,x,y = list(map(int,stdin.readline().split()))
        x -= 1
        y -= 1
        if st == 1:
            ilis[y] += 1
            lis[x].append(y)
            ans.append((x,y))
        else:
            Query.append( (x,y) )

    endnum = 0
    q = deque([])
    for i in range(n):
        if ilis[i] == 0:
            q.append(i)
    while len(q) > 0:
        v = q.popleft()
        index[v] = endnum
        endnum += 1

        for nex in lis[v]:
            inum[nex] -= 1
            if inum[nex] == 0:
                q.append(nex)

    if endnum != n:
        print ("NO")
    else:
        print ("YES")
        for x,y in Query:
            if index[x] < index[y]:
                print(x+1,y+1)
            else:
                print(y+1,x+1)
        for x,y in ans:
            print(x+1,y+1)


Solve in Python:
You are given a graph with $3 \cdot n$ vertices and $m$ edges. You are to find a matching of $n$ edges, or an independent set of $n$ vertices.

A set of edges is called a matching if no two edges share an endpoint.

A set of vertices is called an independent set if no two vertices are connected with an edge.

-----Input-----

The first line contains a single integer $T \ge 1$ — the number of graphs you need to process. The description of $T$ graphs follows.

The first line of description of a single graph contains two integers $n$ and $m$, where $3 \cdot n$ is the number of vertices, and $m$ is the number of edges in the graph ($1 \leq n \leq 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$).

Each of the next $m$ lines contains two integers $v_i$ and $u_i$ ($1 \leq v_i, u_i \leq 3 \cdot n$), meaning that there is an edge between vertices $v_i$ and $u_i$.

It is guaranteed that there are no self-loops and no multiple edges in the graph.

It is guaranteed that the sum of all $n$ over all graphs in a single test does not exceed $10^{5}$, and the sum of all $m$ over all graphs in a single test does not exceed $5 \cdot 10^{5}$.

-----Output-----

Print your answer for each of the $T$ graphs. Output your answer for a single graph in the following format.

If you found a matching of size $n$, on the first line print "Matching" (without quotes), and on the second line print $n$ integers — the indices of the edges in the matching. The edges are numbered from $1$ to $m$ in the input order.

If you found an independent set of size $n$, on the first line print "IndSet" (without quotes), and on the second line print $n$ integers — the indices of the vertices in the independent set.

If there is no matching and no independent set of the specified size, print "Impossible" (without quotes).

You can print edges and vertices in any order.

If there are several solutions, print any. In particular, if there are both a matching of size $n$, and an independent set of size $n$, then you should print exactly one of such matchings or...

import sys
input=sys.stdin.readline
T=int(input())
for _ in range(T):
    n,m=map(int,input().split())
    edges=[0]*m
    for i in range(m):
        edges[i]=tuple(map(int,input().split()))
    used=[0]*(3*n)
    edgess=[]
    check=0
    for i in range(m):
        if used[edges[i][0]-1]==used[edges[i][1]-1]==0:
            edgess.append(i+1)
            used[edges[i][0]-1]=1
            used[edges[i][1]-1]=1
            check+=1
    if check>=n:
        useful=edgess[:n]
        edgess=[str(guy) for guy in useful]
        print("Matching")
        print(" ".join(edgess))
    else:
        indep=[]
        for i in range(1,3*n+1):
            if used[i-1]==0:
                indep.append(i)
        useful=indep[:n]
        verts=[str(guy) for guy in useful]
        print("IndSet")
        print(" ".join(verts))


Solve in Python:
You are given a grid of size M x N, where each square is colored with some random color among K colors with each having equal probability.

A Good Rectangle is defined as one where all squares lying on the inner border are of the same color.

What is the expected number of Good Rectangles in the given grid.

-----Input-----

-
First Line contains M, N, K

-----Output-----
A single value rounded off to the nearest Integer corresponding to the required answer.

-----Constraints-----
-  1 <= N <= 105
-  1 <= M <= 105
-  1 <= K <= 105

-----Example-----
Input:
1 3 1
Output:
6

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

if k == 1:
 x, y = 0, 0
 for p in range(2, n + 1):
  x += (n - p + 1)
 for p in range(2, m + 1):
  y += (m - p + 1)
 ans = x * y
 x = 0
 for p in range(1, n + 1):
  x += (n - p + 1)
 y = 0
 for p in range(1, m + 1):
  y += (m - p + 1)
 ans += m * x
 ans += n * y
 ans -= n * m
 print(ans)
else:
 x, y = 0.0, 0.0
 q = 1.0
 for p in range(2, n + 1):
  q /= k * k
  x += (n - p + 1) * q
 for p in range(2, m + 1):
  q /= k * k
  y += (m - p + 1) * q
 ans = k * x * y
 x = 0.0
 q = 1.0
 for p in range(1, n + 1):
  x += (n - p + 1) * q
  q /= k
 y = 0.0
 q = 1.0
 for p in range(1, m + 1):
  y += (m - p + 1) * q
  q /= k
 ans += m * x
 ans += n * y
 ans -= n * m
 ans += 1e-9
 # print ans
 print("%.0f" % ans)


Solve in Python:
You are given a grid of size N x M consisting of '.' (empty), 'W' (white) or 'B' (black) cells. We follow the convention that the top left corner is the position (1,1) and bottom right corner is (N,M).
From every '.' cell (i, j), a ray is shot towards the right. If the ray reaches a 'B' cell, it loses it's strength fully and stops there. When a ray
reaches a 'W' cell, it's strength drops drastically so that the  ray stops when it reaches a second 'W' cell. That is, if there is no 'B'
cell in between, a ray can cross at most one 'W' cell, and it will stop when it reaches the second 'W' cell. It passes unchanged through  any '.' cell. If it reaches a boundary cell (ie. (i,M), for some i), it stops there.
Let L(i, j) be length travelled by the ray starting from the cell (i, j). If (i,j) is 'W' or 'B', no ray starts from here, and hence L(i,j) is defined to be 0. If a ray starts from (i,j) and stops at (i,k), then the distance travelled by this ray is k-j+1. i.e, inclusive of both starting and ending cells.
For the given grid your task is to find the sum of L(i, j) over all 1 <= i <= N and 1 <= j <= M.
The description of the grid is given as follows: In addition to N and M, you are given the number of 'W' cells (w) and the number of 'B' cells (b)
and you are given the locations of these w + b cells.  (The other cells contain '.')

-----Constraints:-----
For all testcases,
- 1 <= N, M <= 10^6.
- 0 <= w,b <= 10^5
Subtask 1: 15%
It is guaranteed that 1 <= N,M <= 500
Subtask 2: 25%
It is guaranteed that 1 <= N,M <= 2000
Subtask 3: 60%
No additional guarantees.

-----Input format:-----
- There is only one line of input which contains 4 + 2w + 2b space separated integers. The first four integers are N, M, w and b.
- The next 2*w integers denote the cells which contains a 'W': x1 y1 x2 y2 .. xw yw. These denote that (xi,yi) contains 'W'.
- The next 2*b integers denote the cells which contains a 'B': x1 y1 x2 y2 .. xb yb. These denote that (xi,yi) contains 'B'.
- The cells which are not in the input have to be...

# cook your dish here
it=list(map(int,input().split()))
n,m=it[:2]
w,b=it[2:4]
aa=it[4:4+2*w]

aa=[[aa[i*2],aa[i*2+1]] for i in range(w)]
bb=it[4+2*w:]
bb=[[bb[i*2],bb[i*2+1]] for i in range(b)]
ss=[[] for i in range(n)]
for i in aa:
 ss[i[0]-1].append([i[1]-1,1])
for i in bb:
 ss[i[0]-1].append([i[1]-1,0])
ss=[sorted(i) for i in ss]
tot=0
for j in range(n):
 ind=0
 co=0
 st=[]
 # print("j is",j)
 for i in ss[j]:
  if i[1]==1:
   co+=1
   if co<=1:
    st.append(i)
    continue
   a=i[0]-ind+1
   b=1+1
   #  su=((a+b)*(a-b+1))//2

   # st=[]
  #    tot+=su
   #print(a,b,tot)
   for ii in st:
    a=ind
    b=ii[0]-1
    a=i[0]-a+1
    b=i[0]-b+1

    su=((a+b)*(a-b+1))//2
    tot+=su
    #  print(a,b,tot)
    ind=ii[0]+1
   st=[i[:]]
   #   print(tot)
   # ind=i[0]+1
  else:
   co=0
   a=i[0]-ind+1
   b=1+1
   su=((a+b)*(a-b+1))//2

   tot+=su
   #  print(a,b,tot)
   ind=i[0]+1
   for ii in st:
    tot-=(i[0]-ii[0]+1)
   st=[]
   #  print(tot)
 a=ind
 b=m-1
 #   print(a,b)
 # print(tot)
 if a<=b:
  a=m-a
  b=m-b

  # print(a,b)
  su=((a+b)*(a-b+1))//2
  tot+=su
 #  print(tot)
 for ii in st:
  tot-=(m-ii[0])

 #print(tot)
 # print()
print(tot)


Solve in Python:
You are given a grid with $R$ rows (numbered $1$ through $R$) and $C$ columns (numbered $1$ through $C$). A cell in row $r$ and column $c$ is denoted by $(r, c)$. Two cells in the grid are adjacent if they have a common side. For each valid $i$ and $j$, there is a value $a_{i, j}$ written in cell $a_{i, j}$.
A cell in the grid is stable if the number of cells in the grid which are adjacent to this cell is strictly greater than the value written in this cell. The whole grid is stable if all cells in the grid are stable.
Can you determine whether the grid is stable?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $R$ and $C$.
- $R$ lines follow. For each $i$ ($1 \le i \le R$), the $i$-th of these lines contains $C$ space-separated integers $a_{i, 1}, a_{i, 2}, \ldots, a_{i, C}$.

-----Output-----
For each test case, print a single line containing the string "Stable" if the grid is stable or "Unstable" if it is unstable (without quotes).

-----Constraints-----
- $1 \le T \le 3,000$
- $3 \le R, C \le 10$
- $0 \le a_{i, j} \le 4$ for each valid $i, j$

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

-----Example Output-----
Stable
Unstable

-----Explanation-----
Example case 1: Each cell of the grid is stable, so the grid is stable.
Example case 2: The cell in row $3$ and column $3$ is unstable since the number of cells adjacent to this cell is $3$.

t = int(input())

def numOfCordinates(arr, raw_arr, r, c):
 num = 0
 possibleCords = [[r-1, c], [r+1,c], [r, c+1], [r, c-1]]

 for cords in possibleCords:
  if cords in raw_arr:
   num+=1

 return num

for _ in range(1,t + 1):

 (r,c) = map(int, input().split(" "))

 arr = []
 for i in range(r):
  ri = list(map(int, input().split(" ")))[:c]
  arr.append(ri)

 raw_arr = []
 for ri in range(r):

  for ci in range(c):
   raw_arr.append([ri,ci])

 for r in range(len(arr)):

  for c in range(len(arr[r])):
   no_cords = numOfCordinates(arr, raw_arr, r, c)

   if no_cords == -1:
    arr[r][c] = -1

   elif arr[r][c] < no_cords:
    arr[r][c] = 0

   else:
    arr[r][c] = -1

 s = 0
 for ls in arr:
  s += sum(ls)

 if s==0:
  print("Stable")
 else:
  print("Unstable")


Solve in Python:
You are given a grid with $R$ rows (numbered $1$ through $R$) and $C$ columns (numbered $1$ through $C$). Initially, each cell of this grid is either empty, contains an ant or an anteater. Each ant is moving in a fixed direction: up, down, left or right. The anteaters do not move.
The movement of ants happens in discrete steps. For example, when an ant is in the cell in the $i$-th row and $j$-th column at some point in time (in some step) and it is moving down, then in the next step, it enters the cell in the $(i+1)$-th row and $j$-th column. Two ants meet each other when they enter the same cell at the same point in time (in the same step). When ants meet, they do not interact in any way and keep moving in their fixed directions.
If an ant reaches an anteater, that anteater eats the ant, so the ant completely disappears. If an ant attempts to leave the grid, it also disappears. When two ants enter a cell containing an anteater at the same time, they are eaten before they could meet.
Calculate the total number of pairs of ants that meet each other.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $R$ and $C$.
- Each of the following $R$ lines contains a single string with length $C$. For each valid $i, j$, the $j$-th character in the $i$-th string is:
- '#' if the cell in the $i$-th row and $j$-th column of the grid contains an anteater
- 'U', 'D', 'L' or 'R' if this cell contains an ant moving up, down, left or right respectively
- '-' if this cell is empty

-----Output-----
For each test case, print a single line containing one integer — the number of pairs of ants that meet.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le R, C \le 50$
- each string contains only characters 'U', 'D', 'L', 'R', '#' and '-'

-----Example Input-----
10
3 3
R--
---
--U
1 4
R--R
2 2
--
--
1 4
R--L
1 4
-R-L
1 4
-R#L
3 3
R-D
-#-
R-U
3 3
R-D
---
R#U
3...

def find_next(arr):
    ans=[[set() for i in range(len(arr[0]))] for j in range(len(arr))]
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            if j>0:
                if 'R' in arr[i][j-1] and '#' not in arr[i][j]:
                    ans[i][j].add('R')
            if j<len(arr[0])-1:
                if 'L' in arr[i][j+1] and '#' not in arr[i][j]:
                    ans[i][j].add('L')
            if i>0:
                if 'D' in arr[i-1][j] and '#' not in arr[i][j]:
                    ans[i][j].add('D')
            if i<len(arr)-1:
                if 'U' in arr[i+1][j] and '#' not in arr[i][j]:
                    ans[i][j].add('U')
            if '#' in arr[i][j]:
                ans[i][j].add("#")
    return ans

def cal(arr):
    ans=0
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            n=len(arr[i][j])
            ans+=n*(n-1)//2
    return ans
t=int(input())
for _ in range(t):
    r,c=list(map(int,input().split()))
    arr=[]
    for i in range(r):
        toadd=list(map(set,list(input())))
        arr+=[toadd]
    ans=0
    for i in range(max(r,c)):
        arr=find_next(arr)
        ans+=cal(arr)
    print(ans)


Solve in Python:
You are given a grid with dimension $n$ x $m$ and two points with coordinates $X(x1,y1)$ and $Y(x2,y2)$ . Your task is to find the number of ways in which one can go from point $A(0, 0)$ to point $B (n, m)$ using the $shortest$ possible path such that the shortest path neither passes through $X$ nor through $Y$.

Consider the above 4 x 4 grid . Our shortest path can't pass through points (1,3) and (3,3) (marked by yellow dots). One of the possible shortest path is from $A$ to $C$ and then from $C$ to $B$.

-----Input:-----
- First line contains $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, six space separated integers $n, m, x1, y1, x2, y2$.

-----Output:-----
- For each testcase, output in a single line number of ways modulo $998244353$.

-----Constraints-----
- $1 \leq T \leq 10^5$
- $3 \leq n,m \leq 10^5$
- $1 \leq x1, x2 \leq n - 1$
- $1 \leq y1, y2 \leq m - 1$
- $x1 \leq x2$
- $y1 \leq y2$
- $X$ and $Y$ never coincide.

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

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

#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

N = 100001
p = 998244353
factorialNumInverse = [0]*(N+1)
naturalNumInverse = [0]*(N+1)
fact = [0]*(N+1)

def InverseofNumber(p):
    naturalNumInverse[0] = naturalNumInverse[1] = 1
    for i in range(2,N+1):
        naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - (p // i)) % p)

def InverseofFactorial(p):
    factorialNumInverse[0] = factorialNumInverse[1] = 1
    for i in range(2,N+1):
        factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p

def factorial(p):
    fact[0] = 1
    for i in range(1, N + 1):
        fact[i] = (fact[i - 1] * i) % p

def f(num,den1,den2):
    # n C r = n!*inverse(r!)*inverse((n-r)!)
    #ans = ((fact[N] * factorialNumInverse[R])% p * factorialNumInverse[N-R])% p
    ans = ((fact[num]*factorialNumInverse[den1])%p*factorialNumInverse[den2])%p
    return ans

InverseofNumber(p)
InverseofFactorial(p)
factorial(p)

for _ in range(inp()):
    n,m,x1,y1,x2,y2 = ip()
    tot = f(m+n,m,n)
    a = f(m-y1+n-x1,m-y1,n-x1)
    aa = f(x1+y1,x1,y1)
    b = f(m-y2+n-x2,m-y2,n-x2)
    bb = f(x2+y2,x2,y2)
    c = f(y2-y1+x2-x1,y2-y1,x2-x1)
    ans = (tot - a*aa - b*bb + c*aa*b)%p
    print(ans)


Solve in Python:
You are given a integer $n$ ($n > 0$). Find any integer $s$ which satisfies these conditions, or report that there are no such numbers:

In the decimal representation of $s$:   $s > 0$,  $s$ consists of $n$ digits,  no digit in $s$ equals $0$,  $s$ is not divisible by any of it's digits.

-----Input-----

The input consists of multiple test cases. The first line of the input contains a single integer $t$ ($1 \leq t \leq 400$), the number of test cases. The next $t$ lines each describe a test case.

Each test case contains one positive integer $n$ ($1 \leq n \leq 10^5$).

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

-----Output-----

For each test case, print an integer $s$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $s$, print any solution.

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

Output
-1
57
239
6789

-----Note-----

In the first test case, there are no possible solutions for $s$ consisting of one digit, because any such solution is divisible by itself.

For the second test case, the possible solutions are: $23$, $27$, $29$, $34$, $37$, $38$, $43$, $46$, $47$, $49$, $53$, $54$, $56$, $57$, $58$, $59$, $67$, $68$, $69$, $73$, $74$, $76$, $78$, $79$, $83$, $86$, $87$, $89$, $94$, $97$, and $98$.

For the third test case, one possible solution is $239$ because $239$ is not divisible by $2$, $3$ or $9$ and has three digits (none of which equals zero).

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

    for _ in range(int(input())):
        N = int(input())
        if N == 1:
            print(-1)
        else:
            ans = ['3'] * N
            ans[0] = '2'
            print(''.join(ans))

def __starting_point():
    main()

__starting_point()


Solve in Python:
You are given a length of string and two thumbtacks. On thumbtack goes into the focus point *F₀* with coordinates *x₀* and *y₀*, and the other does into point *F₁* with points *x₁* and *y₁*. The string is then tied at the ends to the thumbtacks and has length *l* excluding the knots at the ends. If you pull the string taught with a pencil and draw around the plane you'll have an ellipse with focuses at *F₀* and *F₁*. Given a new point *P*, determine if it falls inside of the ellipse.

You must write a function that takes arguments `f0`, `f1`, `l`, and `p` and returns `true` or `false` depending on whether or not `p` falls inside the ellipse.

Each of `f0`, `f1`, and `p` has has properties `x` and `y` for its coordinates.

You will never be given the case where the string is too short to reach between the points.

import math

def ellipse_contains_point(f0, f1, l, p):
    calc_len = lambda f: math.hypot(*(f[a] - p[a] for a in 'xy'))
    return calc_len(f0) + calc_len(f1) <= l


Solve in Python:
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.

Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.

Given a non-empty string S and a number K, format the string according to the rules described above.

Example 1:

Input: S = "5F3Z-2e-9-w", K = 4

Output: "5F3Z-2E9W"

Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.

Example 2:

Input: S = "2-5g-3-J", K = 2

Output: "2-5G-3J"

Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.

Note:

The length of string S will not exceed 12,000, and K is a positive integer.
String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
String S is non-empty.

class Solution:
     def licenseKeyFormatting(self, S, K):
         """
         :type S: str
         :type K: int
         :rtype: str
         """

         if(len(S)<=1):
             return S.upper().strip('-')
         S = S.upper()
         n_dash = S.count('-')
         n = len(S)-n_dash
         form_S = ""
         if(n%K == 0):
             begin_at = K-1
         else:
             left = n%K
             begin_at = left-1
         steps = 0
         abs_ind = 0
         norm_ind = 0

         while(abs_ind <=begin_at and norm_ind < len(S)):
             if(S[norm_ind]=='-'):
                 norm_ind +=1
                 continue
             form_S += S[norm_ind]
             abs_ind +=1
             norm_ind +=1
         form_S += '-'
         for char_ind in range(norm_ind, len(S)):
             if(S[char_ind] =="-"):
                 continue

             elif(steps == K-1 and abs_ind > begin_at):
                 form_S += S[char_ind]+'-'
                 steps =0
             else:
                 form_S += S[char_ind]
                 steps += 1

             abs_ind += 1

         return form_S.strip('-')


Solve in Python:
You are given a list of directions in the form of a list:

goal = ["N", "S", "E", "W"]

Pretend that each direction counts for 1 step in that particular direction.

Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W.

If you get back to beginning, return an empty array.

from collections import Counter

def directions(goal):
    c = Counter(goal)
    c["N"], c["W"] = c["N"] - c["S"], c["W"] - c["E"]
    c["S"], c["E"] = -c["N"], -c["W"]
    return sorted(c.elements(), key="NSEW".index)


Solve in Python:
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.

class Solution:
     def findTargetSumWays(self, nums, S):
         sum_ = sum(nums)
         if S > sum_: return 0
         target = sum_ - S
         if target % 2: return 0
         target = target // 2

         dp = [1] + [0] * target
         for n in nums:
             i = target
             while(i>=n):
                 dp[i] += dp[i-n]
                 i -= 1
         return dp[target]


Solve in Python:
You are given a list of preferences for n friends, where n is always even.
For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.
All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.
However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:

x prefers u over y, and
u prefers x over v.

Return the number of unhappy friends.

Example 1:
Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output: 2
Explanation:
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.

Example 2:
Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output: 0
Explanation: Both friends 0 and 1 are happy.

Example 3:
Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output: 4

Constraints:

2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair.

class Solution:
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        idx_table = collections.defaultdict(lambda: collections.defaultdict(int))
        for i in range(n):
            for idx, person in enumerate(preferences[i]): idx_table[i][person] = idx

        unhappy = [0] * n
        for i in range(n//2):
            a, b = pairs[i]
            b_a_idx, a_b_idx = idx_table[b][a], idx_table[a][b]
            for j in range(i+1, n//2):
                c, d = pairs[j]

                c_a_idx = idx_table[c][a]
                c_b_idx = idx_table[c][b]
                c_d_idx = idx_table[c][d]

                d_a_idx = idx_table[d][a]
                d_b_idx = idx_table[d][b]
                d_c_idx = idx_table[d][c]

                a_c_idx = idx_table[a][c]
                a_d_idx = idx_table[a][d]

                b_c_idx = idx_table[b][c]
                b_d_idx = idx_table[b][d]

                if c_a_idx < c_d_idx and a_c_idx < a_b_idx: unhappy[a] = unhappy[c] = 1 # a & c prefer each other
                if d_a_idx < d_c_idx and a_d_idx < a_b_idx: unhappy[a] = unhappy[d] = 1 # a & d prefer each other
                if c_b_idx < c_d_idx and b_c_idx < b_a_idx: unhappy[b] = unhappy[c] = 1 # b & c prefer each other
                if d_b_idx < d_c_idx and b_d_idx < b_a_idx: unhappy[b] = unhappy[d] = 1 # b & d prefer each other
        return sum(unhappy)


Solve in Python:
You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list.

Extra credit if you solve it in one line. You can assume there is never an empty list/array and there will always be an integer.

Same meaning: 1 == 1

1 != -1

#Examples:

```
[1,4,4,4,0,4,3,3,1] # should return [1,12,0,4,6,1]

"""So as you can see sum of consecutives 1 is 1
sum of 3 consecutives 4 is 12
sum of 0... and sum of 2
consecutives 3 is 6 ..."""

[1,1,7,7,3] # should return [2,14,3]
[-5,-5,7,7,12,0] # should return [-10,14,12,0]
```

from itertools import groupby

def sum_consecutives(lst):
    return [sum(g) for _, g in groupby(lst)]


Solve in Python:
You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.

Return the number of servers that communicate with any other server.

Example 1:

Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.
Example 2:

Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.

Example 3:

Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.

Constraints:

m == grid.length
n == grid[i].length
1 <= m <= 250
1 <= n <= 250
grid[i][j] == 0 or 1

class Solution:
    def countServers(self, grid: List[List[int]]) -> int:
        rows = []
        cols = []
        servers = []
        conn = 0
        i = 0
        while i < len(grid):
            j = 0
            while j < len(grid[i]):
                if grid[i][j] == 1:
                    rows.append(i)
                    cols.append(j)
                    servers.append((i,j))
                j += 1
            i += 1
        for server in servers:
            if rows.count(server[0]) > 1 or cols.count(server[1]) > 1:
                conn += 1
        return conn


Solve in Python:
You are given a matrix of integers $A$ with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). Each element of this matrix is either $0$ or $1$.
A move consists of the following steps:
- Choose two different rows $r_1$ and $r_2$ or two different columns $c_1$ and $c_2$.
- Apply the bitwise OR operation with the second row/column on the first row/column. Formally, if you chose two rows, this means you should change $A_{r_1, k}$ to $A_{r_1, k} \lor A_{r_2, k}$ for each $1 \le k \le M$; if you chose two columns, then you should change $A_{k, c_1}$ to $A_{k, c_1} \lor A_{k, c_2}$ for each $1 \le k \le N$.
For each element of the matrix, compute the minimum number of moves required to make it equal to $1$ or determine that it is impossible. Note that these answers are independent, i.e. we are starting with the initial matrix for each of them.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $M$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $M$ integers $A_{i, 1}, A_{i, 2}, \dots, A_{i, M}$ NOT separated by spaces.

-----Output-----
For each test case, print $N$ lines. For each valid $i$, the $i$-th of these lines should contain $M$ space-separated integers; for each valid $j$, the $j$-th of these integers should be the minimum number of moves required to make $A_{i, j}$ equal to $1$, or $-1$ if it is impossible.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N, M \le 1,000$
- $A_{i, j} \in \{0, 1\}$ for each valid $i, j$
- the sum of $N \cdot M$ for all test cases does not exceed $1,000,000$

-----Example Input-----
1
3 3
010
000
001

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

t=int(input())
for _ in range(t):
 n,m=map(int,input().split())
 d={}
 e={}
 l=[]
 for i in range(n):
  d[i]=0
 for i in range(m):
  e[i]=0
 for i in range(n):
  l.append(input())
 for i in range(n):
  for j in range(m):
   if l[i][j]=='1':
    d[i]=1
    e[j]=1
 #ans=[]
 if sum(d.values())+sum(e.values())==0:
  k=[-1]*m
  for i in range(n):
   print(*k)
 else:
  ans=[]
  for i in range(n):
   ans.append([0]*m)
  for i in range(n):
   for j in range(m):
    if l[i][j]=='1':
     ans[i][j]=0
    else:
     if (d[i] or e[j]):
      ans[i][j]=1
     else:
      ans[i][j]=2
  for i in range(n):
   for j in range(m):
    print(ans[i][j],end=" ")
   print()


Solve in Python:
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' $\rightarrow$ 'y' $\rightarrow$ 'x' $\rightarrow \ldots \rightarrow$ 'b' $\rightarrow$ 'a' $\rightarrow$ 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.

What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once?

-----Input-----

The only line of the input contains the string s (1 ≤ |s| ≤ 100 000) consisting of lowercase English letters.

-----Output-----

Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring.

-----Examples-----
Input
codeforces

Output
bncdenqbdr

Input
abacaba

Output
aaacaba

-----Note-----

String s is lexicographically smaller than some other string t of the same length if there exists some 1 ≤ i ≤ |s|, such that s_1 = t_1, s_2 = t_2, ..., s_{i} - 1 = t_{i} - 1, and s_{i} < t_{i}.

# -*- coding: utf-8 -*-
"""
Created on Wed Aug 24 13:19:53 2016

@author: Felicia
"""

s = input()
n = len(s)
hea = -1
tai = -1
new = list(s)

for i in range(n):
    if new[i]!='a':
        hea = i
        for j in range(i+1,n):
            if new[j]=='a':
                tai = j-1
                break
        else:
            tai = n-1
        for k in range(hea,tai+1):
            temp = ord(new[k])-1
            new[k] = chr(temp)
        break

if hea ==-1:
    new[n-1] = 'z'

news = ''.join(new)
print(news)


Solve in Python:
You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$.

For example, let $p = [4, 5, 1, 3, 2, 6]$. In this case, the numbers $1, 3, 5, 6$ are beautiful and $2, 4$ are not. It is because:  if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$;  if $l = 3$ and $r = 5$ we will have a permutation $[1, 3, 2]$ for $m = 3$;  if $l = 1$ and $r = 5$ we will have a permutation $[4, 5, 1, 3, 2]$ for $m = 5$;  if $l = 1$ and $r = 6$ we will have a permutation $[4, 5, 1, 3, 2, 6]$ for $m = 6$;  it is impossible to take some $l$ and $r$, such that $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$ for $m = 2$ and for $m = 4$.

You are given a permutation $p=[p_1, p_2, \ldots, p_n]$. For all $m$ ($1 \le m \le n$) determine if it is a beautiful number or not.

-----Input-----

The first line contains the only integer $t$ ($1 \le t \le 1000$)  — the number of test cases in the input. The next lines contain the description of test cases.

The first line of a test case contains a number $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the given permutation $p$. The next line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$, all $p_i$ are different) — the given permutation $p$.

It is guaranteed, that the sum of $n$ from all test cases in the input doesn't exceed $2 \cdot 10^5$.

-----Output-----

Print $t$ lines — the answers to test cases in the order they are given in the input.

The answer to a test case is the string of length $n$, there the $i$-th character is equal to $1$ if $i$ is a beautiful number and is equal to $0$ if $i$ is not a beautiful number.

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

Output
101011
11111
1001

-----Note-----

The first test case is described in the problem statement.

In...

q=int(input())
for t in range(q):
    n=int(input())
    a=list(map(int,input().split()))
    ma=1
    ans='1'
    uk1=a.index(1)
    uk2=uk1
    while uk2-uk1+1!=n:
        if uk2==n-1:
            uk1-=1
            ma=max(ma,a[uk1])
            if ma==uk2-uk1+1:
                ans=ans+'1'
            else:
                ans=ans+'0'
        else:
            if uk1==0:
                uk2+=1
                ma=max(ma,a[uk2])
                if ma == uk2 - uk1 + 1:
                    ans = ans + '1'
                else:
                    ans=ans+'0'
            else:
                if a[uk1-1]<a[uk2+1]:
                    uk1 -= 1
                    ma = max(ma, a[uk1])
                    if ma == uk2 - uk1 + 1:
                        ans = ans + '1'
                    else:
                        ans = ans + '0'
                else:
                    uk2 += 1
                    ma = max(ma, a[uk2])
                    if ma == uk2 - uk1 + 1:
                        ans = ans + '1'
                    else:
                        ans = ans + '0'
    print(ans)


Solve in Python:
You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.

Find three indices $i$, $j$ and $k$ such that:   $1 \le i < j < k \le n$;  $p_i < p_j$ and $p_j > p_k$.  Or say that there are no such indices.

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases.

Next $2T$ lines contain test cases — two lines per test case. The first line of each test case contains the single integer $n$ ($3 \le n \le 1000$) — the length of the permutation $p$.

The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$; $p_i \neq p_j$ if $i \neq j$) — the permutation $p$.

-----Output-----

For each test case:   if there are such indices $i$, $j$ and $k$, print YES (case insensitive) and the indices themselves;  if there are no such indices, print NO (case insensitive).

If there are multiple valid triples of indices, print any of them.

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

Output
YES
2 3 4
YES
3 5 6
NO

t = int(input())

for _ in range(t):
    n = int(input())
    A = [int(x) for x in input().split()]
    for i in range(1,n-1):
        if A[i-1] < A[i] and A[i] > A[i+1]:
            print('YES')
            print(i, i+1, i+2)
            break
    else:
        print('NO')


Solve in Python:
You are given a permutation $p_1, p_2, \ldots, p_n$.

In one move you can swap two adjacent values.

You want to perform a minimum number of moves, such that in the end there will exist a subsegment $1,2,\ldots, k$, in other words in the end there should be an integer $i$, $1 \leq i \leq n-k+1$ such that $p_i = 1, p_{i+1} = 2, \ldots, p_{i+k-1}=k$.

Let $f(k)$ be the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation.

You need to find $f(1), f(2), \ldots, f(n)$.

-----Input-----

The first line of input contains one integer $n$ ($1 \leq n \leq 200\,000$): the number of elements in the permutation.

The next line of input contains $n$ integers $p_1, p_2, \ldots, p_n$: given permutation ($1 \leq p_i \leq n$).

-----Output-----

Print $n$ integers, the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation, for $k=1, 2, \ldots, n$.

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

Output
0 1 3 6 10

Input
3
1 2 3

Output
0 0 0

import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

class Binary_Indexed_Tree():
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)

    def add(self, i, x):
        while i <= self.n:
            self.data[i] += x
            i += i & -i

    def get(self, i):
        return self.sum_range(i, i)

    def sum(self, i):
        ret = 0
        while i:
            ret += self.data[i]
            i &= i-1
        return ret

    def sum_range(self, l, r):
        return self.sum(r)-self.sum(l-1)

    def lower_bound(self, w):
        if w<=0:
            return 0
        i = 0
        k = 1<<(self.n.bit_length())
        while k:
            if i+k <= self.n and self.data[i+k] < w:
                w -= self.data[i+k]
                i += k
            k >>= 1
        return i+1

n = int(input())
a = list(map(int, input().split()))
d = {j:i for i,j in enumerate(a)}
BIT1 = Binary_Indexed_Tree(n)
BIT2 = Binary_Indexed_Tree(n)
BIT3 = Binary_Indexed_Tree(n)

tentou = 0
ans = []
for i in range(n):
    tmp = 0
    p = d[i+1]
    inv_p = n-p
    tentou += BIT1.sum(inv_p)
    BIT1.add(inv_p, 1)

    BIT2.add(p+1, 1)
    BIT3.add(p+1, p+1)
    m = i//2+1
    mean = BIT2.lower_bound(i//2+1)
    tmp = 0
    if i%2 == 0:
        tmp -= m*(m-1)
    else:
        tmp -= m*m
    tmp += tentou
    left = BIT3.sum_range(1, mean)
    right = BIT3.sum_range(mean, n)
    if i%2 == 0:
        left = mean*m - left
        right = right - mean*m
    else:
        left = mean*m - left
        right = right - mean*(m+1)
    tmp += left + right
    ans.append(tmp)
print(*ans)


Solve in Python:
You are given a permutation of 1,2,...,N: p_1,p_2,...,p_N. Determine if the state where p_i=i for every i can be reached by performing the following operation any number of times:
 - Choose three elements p_{i-1},p_{i},p_{i+1} (2\leq i\leq N-1) such that p_{i-1}>p_{i}>p_{i+1} and reverse the order of these three.

-----Constraints-----
 - 3 \leq N \leq 3 × 10^5
 - p_1,p_2,...,p_N is a permutation of 1,2,...,N.

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

-----Output-----
If the state where p_i=i for every i can be reached by performing the operation, print Yes; otherwise, print No.

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

-----Sample Output-----
Yes

The state where p_i=i for every i can be reached as follows:
 - Reverse the order of p_1,p_2,p_3. The sequence p becomes 1,2,5,4,3.
 - Reverse the order of p_3,p_4,p_5. The sequence p becomes 1,2,3,4,5.

def Split(a):
    no = []
    for i, x in a:
        if no and (i == x) == (no[-1][0] == no[-1][1]):
            yield no
            no = []
        no.append((i, x))
    yield no

for sq in Split((i + 1, int(input())) for i in range(int(input()))):
    tb = [0, 0]
    for np, goal in sq:
        if goal != np:
            if goal < tb[np < goal] or goal > sq[-1][0] or goal < sq[0][0]:
                print("No")
                return
            tb[np < goal] = goal
print("Yes")


Solve in Python:
You are given a permutation of natural integers from 1 to N, inclusive. Initially, the permutation is 1, 2, 3, ..., N.
You are also given M pairs of integers, where the i-th is (Li Ri). In a single turn you can choose any of these pairs (let's say with the index j) and arbitrarily shuffle the elements of our permutation on the positions from Lj to Rj, inclusive (the positions are 1-based). You are not limited in the number of turns and you can pick any pair more than once.

The goal is to obtain the permutation P, that is given to you. If it's possible, output "Possible", otherwise output "Impossible" (without quotes).

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two space separated integers N and M denoting the size of the permutation P and the number of pairs described above.
The next line contains N integers - the permutation P.
Each of the following M lines contain pair of integers Li and Ri.

-----Output-----
For each test case, output a single line containing the answer to the corresponding test case.

-----Constraints-----
- 1 ≤ T ≤ 35
- 1 ≤ N, M ≤ 100000
- 1 ≤ Li ≤ Ri ≤ N

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

Output:
Possible
Impossible

t=int(input())
for _ in range(t):
 n,m=list(map(int,input().split()))
 l=list(map(int,input().split()))
 k=[]
 for i in range(m):
  a,b=list(map(int,input().split()))
  k.append([a,b])
 k.sort()
 c=[]
 flag=1
 x=k[0][0]
 y=k[0][1]

 for i in k[1:]:
  if i[0]<=y:
   y=max(y,i[1])
  else:
   c.append([x-1,y-1])
   x=i[0]
   y=i[1]
 c.append([x-1,y-1])
 m=[]
 j=0

 for i in c:
  while j<i[0]:
   m.append(l[j])
   j+=1
  x=l[i[0]:i[1]+1]
  m+=sorted(x)
  j=i[1]+1

 while j<n:
  m.append(l[j])
  j+=1

 if m==sorted(l):
  print('Possible')
 else:
  print('Impossible')


Solve in Python:
You are given a picture consisting of $n$ rows and $m$ columns. Rows are numbered from $1$ to $n$ from the top to the bottom, columns are numbered from $1$ to $m$ from the left to the right. Each cell is painted either black or white.

You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $x$ and $y$, where $1 \le x \le n$ and $1 \le y \le m$, such that all cells in row $x$ and all cells in column $y$ are painted black.

For examples, each of these pictures contain crosses:

 [Image]

The fourth picture contains 4 crosses: at $(1, 3)$, $(1, 5)$, $(3, 3)$ and $(3, 5)$.

Following images don't contain crosses:

 [Image]

You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.

What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?

You are also asked to answer multiple independent queries.

-----Input-----

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

The first line of each query contains two integers $n$ and $m$ ($1 \le n, m \le 5 \cdot 10^4$, $n \cdot m \le 4 \cdot 10^5$) — the number of rows and the number of columns in the picture.

Each of the next $n$ lines contains $m$ characters — '.' if the cell is painted white and '*' if the cell is painted black.

It is guaranteed that $\sum n \le 5 \cdot 10^4$ and $\sum n \cdot m \le 4 \cdot 10^5$.

-----Output-----

Print $q$ lines, the $i$-th line should contain a single integer — the answer to the $i$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.

-----Example-----
Input
9
5 5
..*..
..*..
*****
..*..
..*..
3 4
****
.*..
.*..
4 3
***
*..
*..
*..
5 5
*****
*.*.*
*****
..*.*
..***
1 4
****
5 5
.....
..*..
.***.
..*..
.....
5 3
...
.*.
.*.
***
.*.
3 3
.*.
*.*
.*.
4...

import sys
Q = int(input())
for _ in range(Q):
    N, M = map(int, sys.stdin.readline().split())
    G = [[1 if s == '*' else 0 for s in sys.stdin.readline().strip()] for _ in range(N)]
    ans = 10**9+7
    G1 = [sum(g) for g in G]
    G = list(map(list, zip(*G)))
    G2 = [sum(g) for g in G]
    G = list(map(list, zip(*G)))
    K = N + M - 1
    for i in range(N):
        for j in range(M):
            if G[i][j]:
                ans = min(ans, K - (G1[i] + G2[j] - 1))
            else:
                ans = min(ans, K - (G1[i] + G2[j]))
    sys.stdout.write('{}\n'.format(ans))


Solve in Python:
You are given a positive integer $N$. Consider the sequence $S = (1, 2, \ldots, N)$. You should choose two elements of this sequence and swap them.
A swap is nice if there is an integer $M$ ($1 \le M < N$) such that the sum of the first $M$ elements of the resulting sequence is equal to the sum of its last $N-M$ elements. Find the number of nice swaps.

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

-----Output-----
For each test case, print a single line containing one integer ― the number of nice swaps.

-----Constraints-----
- $1 \le T \le 10^6$
- $1 \le N \le 10^9$

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

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

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

# cook your dish here
from math import sqrt
for _ in range(int(input())):
 n=int(input())
 sum=(n*(n+1))//2
 #print(sum)
 if(sum%2!=0):
  print(0)
  continue
 m=(int((sqrt(1+4*(sum)))-1)//2)
 if(m*(m+1)//2==sum//2):
  print((((m-1)*m)//2)+n-m+((n-m-1)*(n-m))//2)
 else:
  print(n-m)


Solve in Python:
You are given a prime number $p$, $n$ integers $a_1, a_2, \ldots, a_n$, and an integer $k$.

Find the number of pairs of indexes $(i, j)$ ($1 \le i < j \le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$.

-----Input-----

The first line contains integers $n, p, k$ ($2 \le n \le 3 \cdot 10^5$, $2 \le p \le 10^9$, $0 \le k \le p-1$). $p$ is guaranteed to be prime.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le p-1$). It is guaranteed that all elements are different.

-----Output-----

Output a single integer — answer to the problem.

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

Output
1
Input
6 7 2
1 2 3 4 5 6

Output
3

-----Note-----

In the first example:

$(0+1)(0^2 + 1^2) = 1 \equiv 1 \bmod 3$.

$(0+2)(0^2 + 2^2) = 8 \equiv 2 \bmod 3$.

$(1+2)(1^2 + 2^2) = 15 \equiv 0 \bmod 3$.

So only $1$ pair satisfies the condition.

In the second example, there are $3$ such pairs: $(1, 5)$, $(2, 3)$, $(4, 6)$.

n,p,k=list(map(int,input().split()));
pairs = {}
count =0
for i in map(int,input().split()):
    t=(i**4-k*i)%p
    if t in pairs:
        count = count + pairs[t]
        pairs[t] += 1

    else:
        pairs[t] = 1

print(count)


Solve in Python:
You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$.

Find the number of different groups of three integers ($a$, $b$, $c$) such that $1\leq a\leq b\leq c$ and parallelepiped $A\times B\times C$ can be paved with parallelepipeds $a\times b\times c$. Note, that all small parallelepipeds have to be rotated in the same direction.

For example, parallelepiped $1\times 5\times 6$ can be divided into parallelepipeds $1\times 3\times 5$, but can not be divided into parallelepipeds $1\times 2\times 3$.

-----Input-----

The first line contains a single integer $t$ ($1 \leq t \leq 10^5$) — the number of test cases.

Each of the next $t$ lines contains three integers $A$, $B$ and $C$ ($1 \leq A, B, C \leq 10^5$) — the sizes of the parallelepiped.

-----Output-----

For each test case, print the number of different groups of three points that satisfy all given conditions.

-----Example-----
Input
4
1 1 1
1 6 1
2 2 2
100 100 100

Output
1
4
4
165

-----Note-----

In the first test case, rectangular parallelepiped $(1, 1, 1)$ can be only divided into rectangular parallelepiped with sizes $(1, 1, 1)$.

In the second test case, rectangular parallelepiped $(1, 6, 1)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 1, 3)$ and $(1, 1, 6)$.

In the third test case, rectangular parallelepiped $(2, 2, 2)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 2, 2)$ and $(2, 2, 2)$.

N=100001
fac=[0 for i in range(N)]
for i in range(1,N):
    for j in range(i,N,i):
        fac[j]+=1
def gcd(a,b):
        if a<b:
            a,b=b,a
        while b>0:
            a,b=b,a%b
        return a
def ctt(A,B,C):
    la=fac[A]
    lb=fac[B]
    lc=fac[C]
    ab=gcd(A,B)
    ac=gcd(A,C)
    bc=gcd(B,C)
    abc=gcd(ab,C)
    dupabc=fac[abc]
    dupac=fac[ac]-dupabc
    dupbc=fac[bc]-dupabc
    dupab=fac[ab]-dupabc
    lax=la-dupabc-dupab-dupac
    lbx=lb-dupabc-dupab-dupbc
    lcx=lc-dupabc-dupac-dupbc
    ctx=lax*lbx*lcx
    ctx+=lax*lbx*(lc-lcx)
    ctx+=lax*lcx*(lb-lbx)
    ctx+=lcx*lbx*(la-lax)
    ctx+=lax*((lb-lbx)*(lc-lcx)-(dupabc+dupbc)*(dupabc+dupbc-1)/2)
    ctx+=lbx*((la-lax)*(lc-lcx)-(dupabc+dupac)*(dupabc+dupac-1)/2)
    ctx+=lcx*((la-lax)*(lb-lbx)-(dupabc+dupab)*(dupabc+dupab-1)/2)
    ctx+=dupab*dupac*dupbc
    ctx+=dupab*dupac*(dupab+dupac+2)/2
    ctx+=dupab*dupbc*(dupab+dupbc+2)/2
    ctx+=dupbc*dupac*(dupbc+dupac+2)/2
    ctx+=dupabc*(dupab*dupac+dupab*dupbc+dupbc*dupac)
    ctx+=dupabc*(dupab*(dupab+1)+(dupbc+1)*dupbc+(dupac+1)*dupac)/2
    ctx+=(dupabc+1)*dupabc*(dupab+dupac+dupbc)/2
    ctx+=(dupabc*dupabc+dupabc*(dupabc-1)*(dupabc-2)/6)
    return int(ctx)
n=int(input())
for _ in range(n):
    a,b,c = map(int,input().split())
    print(ctt(a,b,c))
return


Solve in Python:
You are given a rooted tree on N vertices. The nodes are numbered from 1 to N, and Node 1 is the root. Each node u has an associated value attached to it: Au.
For each vertex v, we consider the path going upwards from v to the root. Suppose that path is v1, v2, .., vk, where v1 = v and vk = 1. The cost of any node on this path is equal to the minimum value among all the nodes to its left in the path sequence, including itself. That is, cost(vi) = min1 <= j <= i{Avj}. And the cost of the path is the sum of costs of all the nodes in it.
For every node in the tree, find the cost of the path from that node to the root.

-----Input-----
- The first line of the input contains a single integer, N, denoting the number of nodes in the tree.
- The next line contains N-1 integers, the i-th of which denotes the parent of node i+1.
- The next line contains N integers, the i-th of which denotes Ai.

-----Output-----
Output a single line containing N integers, the i-th of which should be the cost of the path from node i to the root.

-----Constraints-----
- 1 ≤ N ≤ 100,000
- -1,000,000,000 ≤ Av ≤ 1,000,000,000

-----Subtasks-----
- Subtask #1 (30 points): 1 ≤ N ≤ 2000
- Subtask #2 (70 points): Original constraints.

-----Example-----
Input:
8
1 1 1 1 5 8 6
1 2 3 4 5 15 70 10

Output:
1 3 4 5 6 21 96 26

-----Explanation-----
For example, take a look at the path from vertex 7: The path is 7 -> 8 -> 6 -> 5 -> 1.
Cost(7) has no choice but to be A7. So Cost(7) = 70.
Cost(8) will be minimum of A7 and A8, which turns out to be A8. So Cost(8) = 10.
Cost(6) = minimum {A7, A8, A6} = minimum {70, 10, 15} = 10.
Cost(5) = minimum {70, 10, 15, 5} = 5.
Cost(1) = minimum {70, 10, 15, 5, 1} = 1.
So, the cost of the path from 7 to the root is 70 + 10 + 10 + 5 + 1 = 96.

import sys
n = eval(input())
parents = [int(x)-1 for x in input().split(' ')]
values = list(map(int , input().split(' ')))
parents = [0]+parents
# print(parents)
# print(values)
def single_node_cost(i):
 cost = 0
 # print('started with ',i)
 min_value = sys.maxsize
 while i != 0:
  min_value = min(min_value,values[i])
  cost += min_value
  # print(i,min_value)
  i = parents[i]
 cost += min(values[0],min_value)
 return cost
for i in range(n):
 print(single_node_cost(i), end=' ')


Solve in Python:
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:

For each word:
- the second and the last letter is switched (e.g. `Hello` becomes `Holle`)
- the first letter is replaced by its character code (e.g. `H` becomes `72`)

Note: there are no special characters used, only letters and spaces

Examples
```
decipherThis('72olle 103doo 100ya'); // 'Hello good day'
decipherThis('82yade 115te 103o'); // 'Ready set go'
```

def decipher_this(string):
    translated = []
    for word in string.split():
        digits = ''
        for c in word:
            if c.isdigit():
                digits += c
        word = word.replace(digits, chr(int(digits)))
        if len(word) > 2:
            translated.append(''.join([word[0], word[-1], word[2:-1], word[1]]))
        else:
            translated.append(word)
    return ' '.join(translated)


Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. Calculate the number of ways to remove a non-empty contiguous subsequence from it such that the resulting sequence is non-empty and strictly increasing.

-----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 one integer ― the number of ways.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^5$
- $|A_i| \le 10^9$ for each valid $i$

-----Subtasks-----
Subtask #1 (40 points): $N \le 1,000$
Subtask #2 (60 points): original constraints

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

-----Example Output-----
4
7

# cook your dish here
def bin(arr,l,r,val,n):
 ans=n
 while(l<=r):
  mid=(l+r)//2
  if(arr[mid]<=val):
   l=mid+1
  else:
   ans=mid
   r=mid-1
 return ans

t=int(input())
while(t):
 n=int(input())
 arr=list(map(int,input().strip().split(' ')))
 pre=[]
 suff=[0]*n
 pre.append(1)
 for i in range(1,n):
  if(arr[i]>arr[i-1] and pre[i-1]==1):
   pre.append(1)
  else:
   pre.append(0)
 flag=0
 temp=0
 for i in range(n-1,-1,-1):
  if(i==n-1):
   suff[i]=1
  elif(arr[i]<arr[i+1] and suff[i+1]==1):
   suff[i]=1
  else:
   if(flag==0):
    temp=i+1
    #print(temp)
    suff[i]=0
    flag=1
   else:
    suff[i]=0
    #flah=1

 #print(pre,end=' ')
 #print()
 #print(suff,end='')
 #print(temp)
 count=0
 y=n
 for i in range(n):
  y=n
  if(pre[i]==1):
   count+=1
   if(temp>i+1):
    y=bin(arr,temp,n-1,arr[i],n)
   elif(i+2<n):
    y=bin(arr,i+2,n-1,arr[i],n)
   #print(y)
   count+=(n-y)
     #print(n-j)
     #break
 count+=(n-temp)
 if(pre[temp]==1):
  count-=2
 print(count)
 t-=1


Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. For each $k$ ($1 \le k \le N$), let's define a function $f(k)$ in the following way:
- Consider a sequence $B_1, B_2, \ldots, B_N$, which is created by setting $A_k = 0$. Formally, $B_k = 0$ and $B_i = A_i$ for each valid $i \neq k$.
- $f(k)$ is the number of ways to split the sequence $B$ into two non-empty contiguous subsequences with equal sums.
Find the sum $S = f(1) + f(2) + \ldots + f(N)$.

-----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 one integer — the sum $S$.

-----Constraints-----
- $1 \le T \le 10$
- $2 \le N \le 2 \cdot 10^5$
- $1 \le |A_i| \le 10^9$ for each valid $i$

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

-----Example Output-----
6
2

from sys import stdin
def gt(num):
 if num:
  return num
 return 0
for __ in range(int(stdin.readline().split()[0])):
 n = int(stdin.readline().split()[0])
 a = list(map(int, stdin.readline().split()))
 cnta = dict()
 cnta.setdefault(0)
 cntb = dict()
 cntb.setdefault(0)
 for i in a:
  cnta[i] = gt(cnta.get(i)) + 1
 asum = 0
 bsum = sum(a)
 ans = 0
 for i in range(n-1):
  asum += a[i]
  bsum -= a[i]
  cnta[a[i]] = gt(cnta.get(a[i])) - 1
  cntb[a[i]] = gt(cntb.get(a[i])) + 1
  ans += gt(cnta.get(bsum-asum))
  ans += gt(cntb.get(asum-bsum))
 print(ans)


Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. For each valid $i$, the star value of the element $A_i$ is the number of valid indices $j < i$ such that $A_j$ is divisible by $A_i$.
Chef is a curious person, so he wants to know the maximum star value in the given sequence. Help him find it.

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

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

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^6$ for each valid $i$
- Sum of $N$ over all test cases does not exceed $100,000$.

-----Subtasks-----
Subtask #1 (20 points): sum  of $N$ over all test cases does not exceed $5,000$
Subtask #2 (80 points): original constraints

-----Example Input-----
1
7
8 1 28 4 2 6 7

-----Example Output-----
3

-----Explanation-----
$A_5 = 2$ divides $4$, $28$ and $8$, so its star value is $3$. There is no element with a higher star value.

T = int(input())
for _ in range(T):
 n = int(input())
 arr = list(map(int, input().split()))
 a = [0 for _ in range(max(arr)+1)]
 star_val = []
 for i in range(len(arr)):
  j = 1
  val = 0
  while j*arr[i] <= len(a):
   val += a[j*arr[i]-1]
   j += 1
  star_val.append(val)
  a[arr[i]-1] += 1
 print(max(star_val))