Solve in Python:
You are given a string s containing lowercase letters and an integer k. You need to :

First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is palindrome.

Return the minimal number of characters that you need to change to divide the string.

Example 1:
Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.

Example 2:
Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
Example 3:
Input: s = "leetcode", k = 8
Output: 0

Constraints:

1 <= k <= s.length <= 100.
s only contains lowercase English letters.

class Solution:
    def palindromePartition(self, s: str, k: int) -> int:
        self.memo = {}
        return self.dfs(s, k)

    def dfs(self, s, k):
        if (s, k) not in self.memo:
            res = float('inf')
            if len(s) == k:
                res = 0
            elif k == 1:
                res = sum(s[i] != s[-1-i] for i in range(len(s)//2))
            else:
                for i in range(1, len(s) - k + 2):
                    res = min(self.dfs(s[:i], 1) + self.dfs(s[i:], k - 1), res)
            self.memo[s, k] = res
        return self.memo[s, k]


Solve in Python:
You are given a system of pipes. It consists of two rows, each row consists of $n$ pipes. The top left pipe has the coordinates $(1, 1)$ and the bottom right — $(2, n)$.

There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:

 [Image] Types of pipes

You can turn each of the given pipes $90$ degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types $1$ and $2$ can become each other and types $3, 4, 5, 6$ can become each other).

You want to turn some pipes in a way that the water flow can start at $(1, 0)$ (to the left of the top left pipe), move to the pipe at $(1, 1)$, flow somehow by connected pipes to the pipe at $(2, n)$ and flow right to $(2, n + 1)$.

Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes:

 [Image] Examples of connected pipes

Let's describe the problem using some example:

 [Image] The first example input

And its solution is below:  [Image] The first example answer

As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $(1, 2)$ $90$ degrees clockwise, the pipe at $(2, 3)$ $90$ degrees, the pipe at $(1, 6)$ $90$ degrees, the pipe at $(1, 7)$ $180$ degrees and the pipe at $(2, 7)$ $180$ degrees. Then the flow of water can reach $(2, n + 1)$ from $(1, 0)$.

You have to answer $q$ independent queries.

-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 10^4$) — the number of queries. Then $q$ queries follow.

Each query consists of exactly three lines. The first line of the query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of $n$ digits from $1$ to $6$ without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding...

def main():
    Q = int(input())
    data = []
    for _ in range(Q):
        N = int(input())
        S1 = [int(a) for a in list(input())]
        S2 = [int(a) for a in list(input())]
        data.append((N, [S1, S2]))

    A = [3, 4, 5, 6]
    B = [1, 2]
    for N, S in data:
        dp = [[0, 0] for _ in range(N+1)]
        dp[0][0] = 1
        for n in range(N):
            if S[0][n] in A and S[1][n] in A:
                dp[n+1][0] = dp[n][1]
                dp[n+1][1] = dp[n][0]
            elif S[0][n] in B and S[1][n] in A:
                dp[n+1][0] = dp[n][0]
                dp[n+1][1] = 0
            elif S[0][n] in A and S[1][n] in B:
                dp[n+1][0] = 0
                dp[n+1][1] = dp[n][1]
            else:
                dp[n+1][0] = dp[n][0]
                dp[n+1][1] = dp[n][1]
        if dp[N][1] == 1:
            print("YES")
        else:
            print("NO")

def __starting_point():
    main()
__starting_point()


Solve in Python:
You are given a table $a$ of size $2 \times n$ (i.e. two rows and $n$ columns) consisting of integers from $1$ to $n$.

In one move, you can choose some column $j$ ($1 \le j \le n$) and swap values $a_{1, j}$ and $a_{2, j}$ in it. Each column can be chosen no more than once.

Your task is to find the minimum number of moves required to obtain permutations of size $n$ in both first and second rows of the table or determine if it is impossible to do that.

You have to answer $t$ independent test cases.

Recall that the permutation of size $n$ is such an array of size $n$ that contains each integer from $1$ to $n$ exactly once (the order of elements doesn't matter).

-----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 number of columns in the table. The second line of the test case contains $n$ integers $a_{1, 1}, a_{1, 2}, \dots, a_{1, n}$ ($1 \le a_{1, i} \le n$), where $a_{1, i}$ is the $i$-th element of the first row of the table. The third line of the test case contains $n$ integers $a_{2, 1}, a_{2, 2}, \dots, a_{2, n}$ ($1 \le a_{2, i} \le n$), where $a_{2, i}$ is the $i$-th element of the second row of the table.

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: -1 if it is impossible to obtain permutation of size $n$ in both first and the second rows of the table, or one integer $k$ in the first line, where $k$ is the minimum number of moves required to obtain permutations in both rows, and $k$ distinct integers $pos_1, pos_2, \dots, pos_k$ in the second line ($1 \le pos_i \le n$) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any.

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

import sys
from collections import deque

input=sys.stdin.readline
#sys.setrecursionlimit(2*10**5)

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    b=list(map(int,input().split()))
    data=[[] for i in range(n)]
    for i in range(n):
        data[a[i]-1].append(i)
        data[b[i]-1].append(i)
    for i in range(n):
        if len(data[i])!=2:
            print(-1)
            break
    else:
        edge=[[] for i in range(n)]
        for i in range(n):
            u,v=data[i][0],data[i][1]
            edge[u].append((v,i))
            edge[v].append((u,i))

        seen=[False]*n
        temp=[]
        res=0
        def dfs(v,cond):
            nonlocal temp,res
            res.append(v)
            if cond==1:
                up,down=a[v],b[v]
            else:
                up,down=b[v],a[v]

            for nv,val in edge[v]:
                if not seen[nv]:
                    seen[nv]=True
                    if a[nv]==up or b[nv]==down:
                        temp.append(nv)
                        dfs(nv,-1)
                    else:
                        dfs(nv,1)

        def bfs(i):
            nonlocal temp,res
            deq=deque([(i,1)])
            while deq:
                v,cond=deq.popleft()
                res.append(v)
                if cond==1:
                    up,down=a[v],b[v]
                else:
                    up,down=b[v],a[v]

                for nv,val in edge[v]:
                    if not seen[nv]:
                        seen[nv]=True
                        if a[nv]==up or b[nv]==down:
                            temp.append(nv)
                            deq.append((nv,-1))
                        else:
                            deq.append((nv,1))

        ans=[]
        for i in range(0,n):
            if not seen[i]:
                res=[]
                temp=[]
                seen[i]=True
                bfs(i)
                if len(res)-len(temp)>=len(temp):
                    ans+=temp
               ...


Solve in Python:
You are given a tree (connected graph without cycles) consisting of $n$ vertices. The tree is unrooted — it is just a connected undirected graph without cycles.

In one move, you can choose exactly $k$ leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them with edges incident to them. I.e. you choose such leaves $u_1, u_2, \dots, u_k$ that there are edges $(u_1, v)$, $(u_2, v)$, $\dots$, $(u_k, v)$ and remove these leaves and these edges.

Your task is to find the maximum number of moves you can perform if you remove leaves optimally.

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 $k$ ($2 \le n \le 2 \cdot 10^5$; $1 \le k < n$) — the number of vertices in the tree and the number of leaves you remove in one move, respectively. The next $n-1$ lines describe edges. The $i$-th edge is represented as two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$), where $x_i$ and $y_i$ are vertices the $i$-th edge connects. It is guaranteed that the given set of edges forms a tree.

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 — the maximum number of moves you can perform if you remove leaves optimally.

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

Output
2
3
3
4

-----Note-----

The picture corresponding to the first test case of the example:

[Image]

There you can remove vertices $2$, $5$ and $3$ during the first move and vertices $1$, $7$ and $4$ during the second move.

The picture corresponding to the second test case of the example:

[Image]

There you can remove vertices $7$, $8$ and $9$ during the first move, then...

from sys import stdin, stdout
import functools
import sys,os,math

#sys.setrecursionlimit(10**6)

T = int(input())

for _ in range(T):
    N, K = list(map(int, input().split()))
    DS = [0] * (N + 1)
    LeafNum = [0] * (N + 1)
    g = [[] for _ in range(N+1)]
    for _ in range(N-1):
        u, v = list(map(int, input().split()))
        DS[u] += 1
        DS[v] += 1
        g[u].append(v)
        g[v].append(u)

    for u in range(1, N+1):
        if DS[u] == 1:
            for v in g[u]:
                LeafNum[v] += 1

    if K == 1:
        print(N - 1)
        continue

    q = set()
    for u in range(1, N+1):
        if LeafNum[u] >= K:
            q.add(u)

    ans = 0
    while len(q) > 0:
        u = q.pop()
        nl = LeafNum[u]
        ans += int(nl / K)
        LeafNum[u] = nl % K
        dn = int(nl / K) * K
        DS[u] -= int(nl / K) * K
        if DS[u] == 1:
            for v in g[u]:
                if DS[v] == 1 and dn > 0:
                    dn -= 1
                    continue

                LeafNum[v] += 1
                if LeafNum[v] >= K and v not in q:
                    q.add(v)
    print(ans)


Solve in Python:
You are given a tree consisting of n nodes numbered from 1 to n. The weights of edges of the tree can be any binary integer satisfying following Q conditions.

-
		Each condition is of form u, v, x where u, v are nodes of the tree and x is a binary number.

		For satisfying this condition,  sum of the weight of all the edges present in the path from node u to v of the tree, should have even if x = 0, odd otherwise.

Now, you have to find out number of ways of assigning 0/1 (binary) weights to the edges of the tree satisfying the above conditions.
As the answer could be quite large, print your answer modulo 109 + 7.

-----Input-----
- The first line of input contains a single integer T denoting number of test cases.
- For each test case:

- First line contains two space separated integers n, Q.
- Each of the next n - 1 lines will contain two space separated integer  u, v denoting that there is an edge between vertex u and v in the tree.
- Each of the next Q lines will contain three space separated integer  u, v, x denoting a condition as stated in the probelm.

-----Output-----
- For each test case, output a single integer corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ u, v ≤ n
- 0 ≤ x ≤ 1

-----Subtasks-----
Subtask #1 : (10 points)
- Sum of each of variables n and Q over all the test cases ≤ 20

Subtask #2 : (20 points)
- Sum of each of variables n and Q over all the test cases ≤ 100

Subtask #3 : (30 points)
- Sum of each of variables n and Q over all the test cases ≤ 5000

Subtask #4 : (40 points)
- Sum of each of variables n and Q over all the test cases ≤ 100000

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

Output:
1
4
2

-----Explanation-----
In the first example,
You can only set the weight of each edge equal to 0 for satisfying the given condition. So, there is exactly one way of doing this. Hence answer is 1.

In the second example,
There are two edges and there is no condition on the edges. So, you can assign them in 4 ways.

In...

import sys

def powc(x,n,m):
  res = 1
  xx=x
  while n:
    if n&1:
      res = (res*xx)%m
    xx=xx*xx%m
    n >>= 1
  return res

def circles(u):
  r = 0
  S = [(u,-1,0)]
  Visited[u] = 0
  for s in S:
    for e in V[s[0]]:
      if e[0] != s[1]:
        if Visited[e[0]]==-1:
          Visited[e[0]] = s[2]^e[1]
          S.append((e[0], s[0], s[2]^e[1]))
        elif Visited[e[0]] != s[2]^e[1]:
          return -1
        else:
          r += s[0]<e[0]
  return r

T = int(sys.stdin.readline())
for _ in range(T):
  is_bad = False
  empty = 0
  n,Q = list(map(int, sys.stdin.readline().split()))
  for _ in range(n-1):
    sys.stdin.readline()
  paths = []
  V=list(map(list,[[]]*n))
  for q in range(Q):
    u,v,x = list(map(int, sys.stdin.readline().split()))
    u-=1
    v-=1
    if (v,x^1) in V[u]:
      is_bad = True
    elif (v,x) in V[u]:
      empty += 1
    elif u!=v:
      V[u].append((v,x))
      V[v].append((u,x))
    elif x==1:
      is_bad = True
    else:
      empty += 1
    paths.append((u,v,x))
  if is_bad:
    print(0)
  elif n<=1:
    print(1)
  else:
    Visited = [-1]*n
    components = 0
    for i in range(n):
      if Visited[i]==-1:
        components += 1
        c = circles(i)
        if c==-1:
          is_bad = True
          break
        empty += c
    if is_bad:
      print(0)
    else:
      print(powc(2,n-1-(Q-empty),10**9+7))


Solve in Python:
You are given a tree rooted at node $1$ with $N$ vertices. The $i$$th$ vertex initially has value $A_i (1 \leq i \leq N)$. You are also given $Q$ queries.
In each query you are given a vertex $V$.  Let $S = \{ S_1 , S_2 , ... S_x \} $ denote the set of vertices such that $S_i$ is in the subtree of $V$, distance between $S_i$ and $V$ is even and $S_i \neq V$ for all $i$. For all $S_i$ , add $A$$S_i$ to $A_V$ and change the value of $A$$S_i$ to zero.
Find the values of all the vertices after all queries are performed.
Note-The distance between two vertices is defined as the number of edges
traversed on the shortest path from one vertex to the other.

-----Input:-----
- The first line contains an integer $T$ denoting the number of test cases.
- The first line of each test case contain two integers $N$ and $Q$.
- The second line contains $N$ space separated integers, $A_1, A_2, ..., A_n$ denoting the initial values of the vertices.
- The next $N-1$ lines contain two integers $u$ and $v$ denoting an edge between $u$and $v$.
- The next $Q$ lines contain a single integer which is the query.

-----Output:-----
- Print a single line containing $N$ integers for each test case which is the final values of the vertices.

-----Constraints:-----
- $1\leq T \leq 10$
- $1 \leq N \leq 200000$
- $1 \leq Q \leq 200000$
- $0 \leq A_i \leq 10^9$
- The sum of $N$ over all test cases does not exceed $200000$.
- The sum of $Q$ over all test cases does not exceed $200000$.

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

-----Sample Output-----
13 5 0 0

-----Explanation-----
Node $3$ has no child in its subtree which is at  an even distance so there is no change in the values. Values of nodes after $1st$ query: $6, 2, 7, 3$.
Node $4$ is at an even distance in the subtree of node $2$ so $A_4$ gets added to $A_2$ and $A_4$ becomes 0. Values of nodes after $2nd$ query: $6, 5, 7, 0$.
Node $3$ is at an even distance in the subtree of node $1$ so $A_3$ gets added to $A_1$ and $A_3$ becomes 0. Values of nodes after $3rd$ query:...

from collections import defaultdict as dd,deque as dq
def opbfs(u,vis,ll,parr):
 q=dq([(u,0)])
 uu=u
 su=0
 while q:

  u,lol=q.pop()
  par=parr[u]
  if(lol%2==0):
   vis[u]=1
   su+=ll[u-1]
   ll[u-1]=0
  for j in d[u]:
   if(j!=par):
    q.appendleft((j,lol+1))
 ll[uu-1]=su
def bfs(height,d,parr):
 q=dq([1])
 while q:
  u=q.pop()
  height[u]=height[parr[u]]+1
  for i in d[u]:
   if(i!=parr[u]):
    q.appendleft(i)
    parr[i]=u
t=int(input())
while t:
 n,q=map(int,input().split())
 ll=list(map(int,input().split()))
 d=dd(list)
 for i in range(n-1):
  u,v=map(int,input().split())
  d[u].append(v)
  d[v].append(u)
 vis=[0]*(n+1)
 l=[]
 height=[0]*(n+1)
 parr=[0]*(n+1)
 bfs(height,d,parr)
 for i in range(q):
  u=int(input())
  l.append((height[u],u,i))
 l.sort()
 vis=[0]*(n+1)
 #print(l)
 for i in l:
  he,u,ind=i
  if(vis[u]==0):
   #print(u)
   opbfs(u,vis,ll,parr)
 print(*ll)
 t-=1


Solve in Python:
You are given a tree with $N$ vertices (numbered $1$ through $N$) and a bag with $N$ markers. There is an integer written on each marker; each of these integers is $0$, $1$ or $2$. You must assign exactly one marker to each vertex.
Let's define the unattractiveness of the resulting tree as the maximum absolute difference of integers written on the markers in any two vertices which are connected by an edge.
Find the minimum possible unattractiveness of the resulting tree.

-----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 denoting the numbers on markers in the bag.
- Each of the next $N-1$ lines contains two space-separated integers $u$ and $v$ denoting an edge between vertices $u$ and $v$.

-----Output-----
For each test case, print a single line containing one integer — the minimum unattractiveness.

-----Constraints-----
- $1 \le T \le 30$
- $1 \le N \le 100$
- $1 \le u, v \le N$
- the graph described on the input is a tree

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

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

-----Explanation-----
Example case 1:

# cook your dish here
import numpy as np
tests = int(input())
for _ in range(tests):
   n = int(input())
   weights = [int(j) for j in input().split()]
   edges = [[0] for _ in range(n-1)]
   for i in range(n-1):
      edges[i] = [int(j)-1 for j in input().split()]
   vertex_set = [[] for _ in range(n)]
   for i in range(n-1):
      vertex_set[edges[i][0]].append(edges[i][1])
      vertex_set[edges[i][1]].append(edges[i][0])
   counts = [0 for _ in range(3)]
   for i in range(n):
      counts[weights[i]] += 1
   if counts[1] == 0:
      print(2 * (counts[0] != 0 and counts[2] != 0))
   elif counts[1] == n:
      print(0)
   else:
      visited = [0]
      for i in range(n):
         vertex = visited[i]
         for v in vertex_set[vertex]:
            if v not in visited:
               visited.append(v)
      vertex_nums = [[0] for _ in range(n)]
      for i in range(n-1,-1,-1):
         vertex = visited[i]
         for v in vertex_set[vertex]:
            if v in visited[i:]:
               vertex_nums[vertex].append(sum(vertex_nums[v])+1)
      for i in range(n):
         vertex_nums[i].append(n-1-sum(vertex_nums[i]))
      sums = np.zeros(n,dtype=bool)
      sums[0] = True
      for i in range(n):
         new_sums = np.zeros(n,dtype=bool)
         new_sums[0] = True
         for num in vertex_nums[i]:
            new_sums[num:n] = np.logical_or(new_sums[num:n],new_sums[:n-num])
         sums = np.logical_or(sums,new_sums)
      solved = False
      for i in range(n):
         if sums[i] and counts[0] <= i and counts[2] <= n - 1 - i:
            solved = True
            break
      if solved or counts[1] > 1:
         print(1)
      else:
         print(2)


Solve in Python:
You are given a tree with $N$ vertices (numbered $1$ through $N$) and a sequence of integers $A_1, A_2, \ldots, A_N$. You may choose an arbitrary permutation $p_1, p_2, \ldots, p_N$ of the integers $1$ through $N$. Then, for each vertex $i$, you should assign the value $A_{p_i}$ to this vertex.
The profit of a path between two vertices $u$ and $v$ is the sum of the values assigned to the vertices on that path (including $u$ and $v$).
Let's consider only (undirected) paths that start at a leaf and end at a different leaf. Calculate the maximum possible value of the sum of profits of all such paths. Since this value could be very large, compute it modulo $10^9 + 7$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
- Each of the following $N−1$ lines contains two space-separated integers $u$ and $v$ denoting that vertices $u$ and $v$ are connected by an edge.

-----Output-----
For each test case, print a single line containing one integer — the maximum sum of profits, modulo $10^9 + 7$.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 300,000$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$

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

-----Example Output-----
24
15

-----Explanation-----
Example case 1: $(1, 4, 2, 3)$ is one of the possible permutations that give the optimal answer. Then, the profits of paths between pairs of vertices $(1, 3)$, $(1, 4)$ and $(3, 4)$ are $7$, $8$ and $9$ respectively.
Example case 2: Here, any permutation could be chosen.

T = int(input())

M = 10 ** 9 + 7

for _ in range(T):
 N = int(input())

 A = list(map(int, input().split()))

 if N == 1:
  print(0)
  continue

 B = {}
 C = {}

 for i in range(N - 1):
  u, v = input().split()
  u = int(u) - 1
  v = int(v) - 1

  if u not in B:
   B[u] = []

  if v not in B:
   B[v] = []

  B[u].append(v)
  B[v].append(u)

 total_leaves = 0

 for i in B:
  if len(B[i]) == 1:
   total_leaves += 1

 S = [0]

 visited = [False] * N

 parent = [-1] * N

 total_visits = [0] * N

 while len(S) > 0:
  current = S.pop(len(S) - 1)

  if visited[current]:
   p = parent[current]
   if p != -1:
    total_visits[p] += total_visits[current]
    if p not in C:
     C[p] = {}
    C[p][current] = total_visits[current]
    if current not in C:
     C[current] = {}
    C[current][p] = total_leaves - C[p][current]
  else:
   S.append(current)
   visited[current] = True
   for i, j in enumerate(B[current]):
    if not visited[j]:
     parent[j] = current
     S.append(j)
   if len(B[current]) == 1:
    total_visits[current] = 1
    p = parent[current]
    if p != -1:
     if p not in C:
      C[p] = {}
     C[p][current] = 1

 D = {}
 for i in C:
  sum1 = 0
  for j in C[i]:
   sum1 += C[i][j]
  D[i] = sum1

 E = [0] * N
 for i in C:
  sum1 = 0
  for j in C[i]:
   D[i] -= C[i][j]
   sum1 += C[i][j] * D[i]
  E[i] = sum1

 for i, j in enumerate(E):
  if j == 0:
   for k in C[i]:
    E[i] = C[i][k]

 E.sort()
 E.reverse()
 A.sort()
 A.reverse()

 E = [x % M for x in E]
 A = [x % M for x in A]

 ans = 0
 for i, j in zip(E, A):
  a = i * j
  a %= M
  ans += a
  ans %= M

 print(ans)


Solve in Python:
You are given a weighted graph with $N$ nodes and $M$ edges. Some of the nodes are marked as special nodes. Your task is to find the shortest pairwise distance between any two different special nodes.

-----Input-----
- The first line of the input contains three space-separated integers $N$, $M$ and $K$ denoting the number of nodes, the number of edges, and the number of special nodes.
- The next line contains $K$ space-separated distinct integers $A_{1}$, $A_{2}$, $\ldots$, $A_{K}$, denoting the special nodes.
- The next $M$ lines each contain three space-separated integers - $X$, $Y$, $Z$, denoting an edge connecting the nodes $X$ and $Y$, with weight $Z$.

-----Output-----
Output the shortest pairwise distance between any two different special nodes.

-----Constraints-----
- The given graph is connected.
- The given graph doesn't contain self loops and multiple edges.
- $1 \leq A_{i} \leq N$
- $1 \leq Z_{j} \leq 10^{4}$
- $1 \leq X_{j}, Y_{j} \leq N$

-----Subtasks-----
Subtask #1 (20 points):
- $2 \leq N \leq 300$
- $N-1 \leq M \leq \frac{N \cdot (N-1)}{2}$
- $2 \leq K \leq N$
Subtask #2 (25 points):
- $2 \leq N \leq 10^5$
- $N-1 \leq M \leq 10^5$
- $2 \leq K \leq 10$
Subtask #3 (55 points):
- $2 \leq N \leq 10^5$
- $N-1 \leq M \leq 3 \cdot 10^5$
- $2 \leq K \leq 10^4$

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

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

-----Explanation-----
Nodes $1$, $3$, and $5$ are special nodes. Shortest distance between nodes $1$ and $3$ is $7$, and that between nodes $3$ and $5$ is $9$. Shortest distance between nodes $1$ and $5$ is $16$. Minimum of these distances is $7$. Hence answer is $7$.

n,m,lk = list(map(int,input().split()))
sp = [int(i)-1 for i in input().split()]
dp = []
for i in range(n):
 dp += [[0]*n]
for i in range(n):
 for j in range(n):
  if(i!=j):
   dp[i][j]=10**18
for _ in range(m):
 x,y,z = list(map(int,input().split()))
 dp[x-1][y-1]=z
 dp[y-1][x-1]=z
for k in range(n):
 for i in range(n):
  for j in range(n):
   if(dp[i][j]>dp[i][k]+dp[k][j]):
    dp[i][j]=dp[i][k]+dp[k][j]
dist = 10**18
for i in range(lk):
 for j in range(i+1,lk):
  dist = min(dist,dp[sp[i]][sp[j]])
print(dist)


Solve in Python:
You are given a weighted undirected graph consisting of n$n$ nodes and m$m$ edges. The nodes are numbered from 1$1$ to n$n$. The graph does not contain any multiple edges or self loops.
A walk W$W$ on the graph is a sequence of vertices (with repetitions of vertices and edges allowed) such that every adjacent pair of vertices in the sequence is an edge of the graph. We define the cost of a walk W$W$, Cost(W)$Cost(W)$, as the maximum over the weights of the edges along the walk.
You will be given q$q$ queries. In each query, you will be given an integer X$X$.

You have to count the number of different walks W$W$ of length 4$4$ such that Cost(W)$Cost(W)$ = X$X$.

Two walks are considered different if they do not represent the same edge sequence.

-----Input:-----
- First line contains 2 integers : the number of nodes n$n$ and number of edges m$m$.
- Next m$m$ lines each describe u$u$, v$v$ and w$w$, describing an edge between u$u$ and v$v$ with weight w$w$.
- Next line contains q$q$, the number of queries.
- Next q$q$ lines each describe an integer X$X$ - the cost of the walk in the query.

-----Output:-----
For each query, output in a single line the number of different possible walks.

-----Constraints-----
- 1≤n≤100$1 \leq n \leq 100$
- 1≤m≤n(n−1)2$1 \leq m \leq \frac{n (n-1)}{2}$
- 1≤u,v≤n$1 \leq u, v \leq n$
- 1≤w≤100$1 \leq w \leq 100$
- 1≤q≤100$1 \leq q \leq 100$
- 1≤X≤100$1 \leq X \leq 100$

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

-----Sample Output:-----
2
10
36

-----EXPLANATION:-----
For X=2$X = 2$, all possible 10$10$ walks are listed below :
- 1 -> 2 -> 1 -> 2 -> 3
- 1 -> 2 -> 3 -> 2 -> 1
- 1 -> 2 -> 3 -> 2 -> 3
- 2 -> 1 -> 2 -> 3 -> 2
- 2 -> 3 -> 2 -> 1 -> 2
- 2 -> 3 -> 2 -> 3 -> 2
- 3 -> 2 -> 1 -> 2 -> 1
- 3 -> 2 -> 1 -> 2 -> 3
- 3 -> 2 -> 3 -> 2 -> 1
- 3 -> 2 -> 3 -> 2 -> 3

# cook your dish here
from collections import defaultdict

class sol():
    def __init__(self,n,edges):
        self.n = n
        self.edges = edges
        self.graph = self.create_graph()
        self.precompute()

    def create_graph(self):
        graph = defaultdict(list)
        for e in self.edges:
            u = e[0]
            v = e[1]
            w = e[2]
            graph[u].append([v,w])
            graph[v].append([u,w])
        return graph

    def precompute(self):
        self.maxiedges = [0]*6
        self.B = [[0 for i in range(101)] for i in range(101)]
        def func(u,v,l):
            if l==2:
                self.B[u][self.maxiedges[l]] += 1
            else:
                for j in self.graph[v]:
                    self.maxiedges[l+1] = max(self.maxiedges[l],j[1])
                    func(u,j[0],l+1)
        for i in range(1,self.n+1):
            func(i,i,0)

    def paths(self,X):
        freq = 0
        for u in range(1,self.n+1):
            for x in range(X+1):
                freq += 2*self.B[u][X]*self.B[u][x]
            freq -= self.B[u][X]*self.B[u][X]
        return freq

n, m = map(int, input().split())
edges = []
while m:
    uvw = list(map(int, input().split()))
    edges.append(uvw)
    m -= 1
q = int(input())
Graph = sol(n,edges)
while q:
    query = int(input())
    print(Graph.paths(query))
    q -= 1


Solve in Python:
You are given an $array$ of size $N$ and an integer $K$ ( $N > 1 , K > 0$ ).
Each element in the array can be incremented by $K$ or decremented by $K$ $at$ $most$ $once$.
So there will be  $3^n$ possible combinations of final array. (As there are 3 options for every element).

Out of these combinations, you have to select a combination, in which the $absolute$ difference between the largest and the smallest element is $maximum$.
You have to print the $maximum$ $absolute$ $difference$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a two lines of input
- First line contains two integers $N, K$.
- Second line contains $N$ space separated integers.

-----Output:-----
For each testcase, output the maximum absolute difference that can be achieved on a new line.

-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq N \leq 1000$
- $1 \leq K , arr[i]  \leq 10000$
$NOTE$:  Large  input files, Use of fastio is recommended.

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

4 3

4 2 5 1

3 5

2 5 3

-----Sample Output:-----
10

13

for i in range(int(input())):
    n,k=list(map(int,input().split()))
    l=list(map(int,input().split()))
    ma=max(l)+k
    mi=min(l)-k
    print(abs(ma-mi))


Solve in Python:
You are given an N × N grid initially filled by zeros. Let the rows and columns of the grid be numbered from 1 to N, inclusive. There are two types of operations can be applied to the grid:

- RowAdd R X: all numbers in the row R should be increased by X.
- ColAdd C X: all numbers in the column C should be increased by X.

Now after performing the sequence of such operations you need to find the maximum element in the grid.

-----Input-----
The first line of the input contains two space separated integers N and Q denoting the size of the grid and the number of performed operations respectively. Each of the following Q lines describe an operation in the format described above.

-----Output-----
Output a single line containing the maximum number at the grid after performing all the operations.

-----Constraints-----
- 1 ≤ N ≤ 314159
- 1 ≤ Q ≤ 314159
- 1 ≤ X ≤ 3141
- 1 ≤ R, C ≤ N

-----Example-----
Input:
2 4
RowAdd 1 3
ColAdd 2 1
ColAdd 1 4
RowAdd 2 1

Output:
7

-----Explanation-----
The grid changes as follows:
00  33  34  74  74
00  00  01  41  52

The maximum number in the final grid is 7.

check_digit = lambda x: int(x) if x.isdigit() else x
n, q = map(int, input().split())
rows = {i : 0 for i in range(n)}
columns = {i : 0 for i in range(n)}

for _ in range(q):
 op, num, x = map(check_digit, input().split())
 if op == "RowAdd":
  rows[num-1] += x
 else:
  columns[num-1] += x
print(max(rows.values()) + max(columns.values()))


Solve in Python:
You are given an array $A$ of $N$ positive and pairwise distinct integers.
You can permute the elements in any way you want.
The cost of an ordering $(A_1, A_2, \ldots, A_N)$ is defined as $ (((A_1 \bmod A_2) \bmod A_3)......) \bmod A_N$ where $X \bmod Y$ means the remainder when $X$ is divided by $Y$.
You need to find the maximum cost which can be attained through any possible ordering of the elements.

-----Input:-----
- The first line contains $T$ denoting the number of test cases.
- The first line of each testcase contains a single integer $N$.
- The second line of each testcase contains $N$ space-separated integers, the elements of $A$.

-----Output:-----
- For each testcase, output the maximum possible cost in a new line.

-----Constraints-----
- $1 \leq T \leq 5*10^5$
- $2 \leq N \leq 5*10^5$
- $1 \leq A_i  \leq 10^9$
- Sum of $N$ over all testcases is less than or equal to $10^6$
- All elements in a single testcase are distinct.

-----Subtasks-----
- 100 points : Original constraints.

-----Sample Input:-----
1
2
7 12

-----Sample Output:-----
7

-----Explanation:-----
The two possible ways to order the elements are [7, 12] and [12, 7]. In the first case, the cost is $7 \bmod 12 = 7$ and in the second case the cost is $12 \bmod 7 = 5$. Clearly the answer is 7.

# cook your dish here
t = int(input())
for i in range(t):
 n = int(input())
 a = list(map(int,input().split()))
 j = 1
 r = []
 b = a[0]
 while j<len(a):
  b = b%a[j]
  r.append(b)
  j += 1
 print(min(r))


Solve in Python:
You are given an array $a$ consisting of $n$ integers (it is guaranteed that $n$ is even, i.e. divisible by $2$). All $a_i$ does not exceed some integer $k$.

Your task is to replace the minimum number of elements (replacement is the following operation: choose some index $i$ from $1$ to $n$ and replace $a_i$ with some integer in range $[1; k]$) to satisfy the following conditions:  after all replacements, all $a_i$ are positive integers not greater than $k$;  for all $i$ from $1$ to $\frac{n}{2}$ the following equation is true: $a_i + a_{n - i + 1} = x$, where $x$ should be the same for all $\frac{n}{2}$ pairs of elements.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains two integers $n$ and $k$ ($2 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5$) — the length of $a$ and the maximum possible value of some $a_i$ correspondingly. It is guratanteed that $n$ is even (i.e. divisible by $2$). The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the $i$-th element of $a$.

It is guaranteed that the sum of $n$ (as well as the sum of $k$) over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$, $\sum k \le 2 \cdot 10^5$).

-----Output-----

For each test case, print the answer — the minimum number of elements you have to replace in $a$ to satisfy the conditions from the problem statement.

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

Output
0
1
4
2

import sys
def input():
	return sys.stdin.readline()[:-1]

t = int(input())
for _ in range(t):
	n, k = map(int, input().split())
	a = list(map(int, input().split()))
	cum = [0 for _ in range(2*k+2)]
	for i in range(n//2):
		x, y = a[i], a[n-i-1]
		cum[2] += 2
		cum[min(x, y)+1] -= 1
		cum[x+y] -= 1
		cum[x+y+1] += 1
		cum[max(x, y)+k+1] += 1
		cum[2*k+1] -= 2
	ans = n
	for i in range(2, 2*k+1):
		cum[i] += cum[i-1]
		ans = min(ans, cum[i])
	print(ans)


Solve in Python:
You are given an array $a$ consisting of $n$ integers numbered from $1$ to $n$.

Let's define the $k$-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length $k$ (recall that a subsegment of $a$ of length $k$ is a contiguous part of $a$ containing exactly $k$ elements). If there is no integer occuring in all subsegments of length $k$ for some value of $k$, then the $k$-amazing number is $-1$.

For each $k$ from $1$ to $n$ calculate the $k$-amazing number of the array $a$.

-----Input-----

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

The first line of each test case contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements in the array. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) — the elements of the array.

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

-----Output-----

For each test case print $n$ integers, where the $i$-th integer is equal to the $i$-amazing number of the array.

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

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

for anynumber in range(int(input())):
    n = int(input())
    l = list(map(int,input().split()))
    d = {}
    for (index, i) in enumerate(l):
        if i not in d.keys():
            d[i] = [index+1,index]
        else:
            d[i] = [max(index-d[i][1], d[i][0]),index]
    for i in d.keys():
        d[i] = max(d[i][0], n-d[i][1])
    ans = [-1 for i in range(n)]
    for i in sorted(d.keys(), reverse=True):
        ans[d[i]-1] = i
    for i in range(1,n):
        if ans[i] == -1:
            ans[i] = ans[i-1]
        elif ans[i-1] != -1:
            if ans[i-1]<ans[i]:
                ans[i] = ans[i-1]
    for i in range(n-1):
        print(ans[i],end=" ")
    print(ans[n-1])


Solve in Python:
You are given an array $a$ consisting of $n$ integers.

In one move, you can choose some index $i$ ($1 \le i \le n - 2$) and shift the segment $[a_i, a_{i + 1}, a_{i + 2}]$ cyclically to the right (i.e. replace the segment $[a_i, a_{i + 1}, a_{i + 2}]$ with $[a_{i + 2}, a_i, a_{i + 1}]$).

Your task is to sort the initial array by no more than $n^2$ such operations or say that it is impossible to do that.

You have to answer $t$ independent test cases.

-----Input-----

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

The first line of the test case contains one integer $n$ ($3 \le n \le 500$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 500$), where $a_i$ is the $i$-th element $a$.

It is guaranteed that the sum of $n$ does not exceed $500$.

-----Output-----

For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations $ans$ on the first line and $ans$ integers $idx_1, idx_2, \dots, idx_{ans}$ ($1 \le idx_i \le n - 2$), where $idx_i$ is the index of left border of the segment for the $i$-th operation. You should print indices in order of performing operations.

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

Output
0

6
3 1 3 2 2 3
13
2 1 1 6 4 2 4 3 3 4 4 6 6
-1
4
3 3 4 4

t = int(input())
for _ in range(t):
    n = int(input())
    l = list([int(x)- 1 for x in input().split()])
    out = []

    ll = [(l[i], i) for i in range(n)]
    ll.sort()

    swap = (-1,-1)
    for i in range(n - 1):
        if ll[i][0] == ll[i + 1][0]:
            swap = (ll[i][1],ll[i+1][1])

    newl = [0]*n
    for i in range(n):
        newl[ll[i][1]] = i

    l = newl

    swapN = 0
    for i in range(n):
        for j in range(i + 1, n):
            if l[i] > l[j]:
                swapN += 1

    #print(l)
    if swapN & 1:
        l[swap[0]],l[swap[1]] = l[swap[1]],l[swap[0]]
    #print(l)

    def shift(i):
        out.append(i + 1)
        l[i],l[i+1],l[i+2] = l[i+2],l[i],l[i+1]

    works = True
    done = False

    while not done:

        for i in range(n):
            if l[i] != i:
                break
        else:
            done = True

        if done:
            break

        for find in range(i + 1, n):
            if l[find] == i:
                break

        while find - i >= 2:
            find -= 2
            shift(find)

        if find - i == 1:
            if find <= n - 2:
                shift(find - 1)
                shift(find - 1)
            else:
                works = False
                break

    #print(l)
    if works:
        print(len(out))
        print(' '.join(map(str,out)))
    else:
        print(-1)
    #print('---')


Solve in Python:
You are given an array $a$ consisting of $n$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $a$ to make it a good array. Recall that the prefix of the array $a=[a_1, a_2, \dots, a_n]$ is a subarray consisting several first elements: the prefix of the array $a$ of length $k$ is the array $[a_1, a_2, \dots, a_k]$ ($0 \le k \le n$).

The array $b$ of length $m$ is called good, if you can obtain a non-decreasing array $c$ ($c_1 \le c_2 \le \dots \le c_{m}$) from it, repeating the following operation $m$ times (initially, $c$ is empty):  select either the first or the last element of $b$, remove it from $b$, and append it to the end of the array $c$.

For example, if we do $4$ operations: take $b_1$, then $b_{m}$, then $b_{m-1}$ and at last $b_2$, then $b$ becomes $[b_3, b_4, \dots, b_{m-3}]$ and $c =[b_1, b_{m}, b_{m-1}, b_2]$.

Consider the following example: $b = [1, 2, 3, 4, 4, 2, 1]$. This array is good because we can obtain non-decreasing array $c$ from it by the following sequence of operations:  take the first element of $b$, so $b = [2, 3, 4, 4, 2, 1]$, $c = [1]$;  take the last element of $b$, so $b = [2, 3, 4, 4, 2]$, $c = [1, 1]$;  take the last element of $b$, so $b = [2, 3, 4, 4]$, $c = [1, 1, 2]$;  take the first element of $b$, so $b = [3, 4, 4]$, $c = [1, 1, 2, 2]$;  take the first element of $b$, so $b = [4, 4]$, $c = [1, 1, 2, 2, 3]$;  take the last element of $b$, so $b = [4]$, $c = [1, 1, 2, 2, 3, 4]$;  take the only element of $b$, so $b = []$, $c = [1, 1, 2, 2, 3, 4, 4]$ — $c$ is non-decreasing.

Note that the array consisting of one element is good.

Print the length of the shortest prefix of $a$ to delete (erase), to make $a$ to be a good array. Note that the required length can be $0$.

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...

from sys import stdin

tt = int(stdin.readline())

for loop in range(tt):

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

    flag = 0
    for i in range(n-1,0,-1):
        if flag == 0 and a[i-1] < a[i]:
            flag = 1
        elif flag == 1 and a[i-1] > a[i]:
            print (i)
            break
    else:
        print(0)


Solve in Python:
You are given an array $a$ consisting of $n$ non-negative integers. You have to choose a non-negative integer $x$ and form a new array $b$ of size $n$ according to the following rule: for all $i$ from $1$ to $n$, $b_i = a_i \oplus x$ ($\oplus$ denotes the operation bitwise XOR).

An inversion in the $b$ array is a pair of integers $i$ and $j$ such that $1 \le i < j \le n$ and $b_i > b_j$.

You should choose $x$ in such a way that the number of inversions in $b$ is minimized. If there are several options for $x$ — output the smallest one.

-----Input-----

First line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements in $a$.

Second line contains $n$ space-separated integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$.

-----Output-----

Output two integers: the minimum possible number of inversions in $b$, and the minimum possible value of $x$, which achieves those number of inversions.

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

Output
1 0

Input
9
10 7 9 10 7 5 5 3 5

Output
4 14

Input
3
8 10 3

Output
0 8

-----Note-----

In the first sample it is optimal to leave the array as it is by choosing $x = 0$.

In the second sample the selection of $x = 14$ results in $b$: $[4, 9, 7, 4, 9, 11, 11, 13, 11]$. It has $4$ inversions:

  $i = 2$, $j = 3$;  $i = 2$, $j = 4$;  $i = 3$, $j = 4$;  $i = 8$, $j = 9$.

In the third sample the selection of $x = 8$ results in $b$: $[0, 2, 11]$. It has no inversions.

import sys
readline = sys.stdin.readline
from collections import Counter

N = int(readline())
A = list(map(int, readline().split()))
B = 31

table = [0]*N

ans = 0
rev = 0
for b in range(B-1, -1, -1):
    one = Counter()
    zero = Counter()
    cnt = 0
    cntr = 0
    for i in range(N):
        a = (A[i]>>b)&1
        if a:
            one[table[i]] += 1
            cntr += zero[table[i]]
            table[i] += 1<<b
        else:
            zero[table[i]] += 1
            cnt += one[table[i]]

    if cntr < cnt:
        rev += cntr
        ans |= 1<<b
    else:
        rev += cnt

print(rev, ans)


Solve in Python:
You are given an array $a$ of $n$ integers and an integer $s$. It is guaranteed that $n$ is odd.

In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $s$.

The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $6, 5, 8$ is equal to $6$, since if we sort this array we will get $5, 6, 8$, and $6$ is located on the middle position.

-----Input-----

The first line contains two integers $n$ and $s$ ($1\le n\le 2\cdot 10^5-1$, $1\le s\le 10^9$) — the length of the array and the required value of median.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1\le a_i \le 10^9$) — the elements of the array $a$.

It is guaranteed that $n$ is odd.

-----Output-----

In a single line output the minimum number of operations to make the median being equal to $s$.

-----Examples-----
Input
3 8
6 5 8

Output
2
Input
7 20
21 15 12 11 20 19 12

Output
6

-----Note-----

In the first sample, $6$ can be increased twice. The array will transform to $8, 5, 8$, which becomes $5, 8, 8$ after sorting, hence the median is equal to $8$.

In the second sample, $19$ can be increased once and $15$ can be increased five times. The array will become equal to $21, 20, 12, 11, 20, 20, 12$. If we sort this array we get $11, 12, 12, 20, 20, 20, 21$, this way the median is $20$.

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

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

a.sort()
if(s>a[n//2]):
    fir=n
    for i in range(n//2,n):
        if(a[i]>=s):
            fir=i
            break
    sum1=sum(a[n//2:fir])
    fin=s*(fir-n//2)
    print(fin-sum1)
elif(s<a[n//2]):
    fir=n//2
    for i in range(n//2):
        if(a[i]>=s):
            fir=i
            break
    sum1=sum(a[fir:n//2+1])
    fin=s*(n//2-fir+1)
    print(sum1-fin)
else:
    print(0)


Solve in Python:
You are given an array $a$ of $n$ integers.

You want to make all elements of $a$ equal to zero by doing the following operation exactly three times:  Select a segment, for each number in this segment we can add a multiple of $len$ to it, where $len$ is the length of this segment (added integers can be different).

It can be proven that it is always possible to make all elements of $a$ equal to zero.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 100\,000$): the number of elements of the array.

The second line contains $n$ elements of an array $a$ separated by spaces: $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$).

-----Output-----

The output should contain six lines representing three operations.

For each operation, print two lines:

  The first line contains two integers $l$, $r$ ($1 \le l \le r \le n$): the bounds of the selected segment.

  The second line contains $r-l+1$ integers $b_l, b_{l+1}, \dots, b_r$ ($-10^{18} \le b_i \le 10^{18}$): the numbers to add to $a_l, a_{l+1}, \ldots, a_r$, respectively; $b_i$ should be divisible by $r - l + 1$.

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

Output
1 1
-1
3 4
4 2
2 4
-3 -6 -6

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

if n!=1:
    print(n,n)
    print(-a[-1])

    print(1,n-1)
    res_2 = [a[i]*(n-1) for i in range(n-1)]
    print(*res_2)

    print(1,n)
    res_3 = [-a[i]*n for i in range(n)]
    res_3[-1] = 0

    print(*res_3)
else:
    print(1,1)
    print(-a[0])
    print(1,1)
    print(0)
    print(1,1)
    print(0)


Solve in Python:
You are given an array $a$ of $n$ positive integers.

You can use the following operation as many times as you like: select any integer $1 \le k \le n$ and do one of two things:   decrement by one $k$ of the first elements of the array.  decrement by one $k$ of the last elements of the array.

For example, if $n=5$ and $a=[3,2,2,1,4]$, then you can apply one of the following operations to it (not all possible options are listed below):   decrement from the first two elements of the array. After this operation $a=[2, 1, 2, 1, 4]$;  decrement from the last three elements of the array. After this operation $a=[3, 2, 1, 0, 3]$;  decrement from the first five elements of the array. After this operation $a=[2, 1, 1, 0, 3]$;

Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.

-----Input-----

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

Each test case begins with a line containing one integer $n$ ($1 \le n \le 30000$) — the number of elements in the array.

The second line of each test case contains $n$ integers $a_1 \ldots a_n$ ($1 \le a_i \le 10^6$).

The sum of $n$ over all test cases does not exceed $30000$.

-----Output-----

For each test case, output on a separate line:   YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations.  NO, otherwise.

The letters in the words YES and NO can be outputed in any case.

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

Output
YES
YES
NO
YES

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    b = [0] * (n - 1)
    for i in range(n - 1):
        b[i] = a[i + 1] - a[i]
    mi = 10000000
    c = [0] * (n + 1)
    for i in range(n - 1):
        if b[i] < 0:
            c[i + 1] += b[i]
            c[0] -= b[i]
        else:
            c[i + 1] += b[i]
            c[-1] -= b[i]
    for i in range(n):
        c[i + 1] += c[i]
    for i in range(n):
        if c[i] > a[i]:
            print('NO')
            break
    else:
        print('YES')


Solve in Python:
You are given an array $a$ of length $2n$. Consider a partition of array $a$ into two subsequences $p$ and $q$ of length $n$ each (each element of array $a$ should be in exactly one subsequence: either in $p$ or in $q$).

Let's sort $p$ in non-decreasing order, and $q$ in non-increasing order, we can denote the sorted versions by $x$ and $y$, respectively. Then the cost of a partition is defined as $f(p, q) = \sum_{i = 1}^n |x_i - y_i|$.

Find the sum of $f(p, q)$ over all correct partitions of array $a$. Since the answer might be too big, print its remainder modulo $998244353$.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 150\,000$).

The second line contains $2n$ integers $a_1, a_2, \ldots, a_{2n}$ ($1 \leq a_i \leq 10^9$) — elements of array $a$.

-----Output-----

Print one integer — the answer to the problem, modulo $998244353$.

-----Examples-----
Input
1
1 4

Output
6
Input
2
2 1 2 1

Output
12
Input
3
2 2 2 2 2 2

Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846

Output
2588544

-----Note-----

Two partitions of an array are considered different if the sets of indices of elements included in the subsequence $p$ are different.

In the first example, there are two correct partitions of the array $a$:  $p = [1]$, $q = [4]$, then $x = [1]$, $y = [4]$, $f(p, q) = |1 - 4| = 3$;  $p = [4]$, $q = [1]$, then $x = [4]$, $y = [1]$, $f(p, q) = |4 - 1| = 3$.

In the second example, there are six valid partitions of the array $a$:   $p = [2, 1]$, $q = [2, 1]$ (elements with indices $1$ and $2$ in the original array are selected in the subsequence $p$);  $p = [2, 2]$, $q = [1, 1]$;  $p = [2, 1]$, $q = [1, 2]$ (elements with indices $1$ and $4$ are selected in the subsequence $p$);  $p = [1, 2]$, $q = [2, 1]$;  $p = [1, 1]$, $q = [2, 2]$;  $p = [2, 1]$, $q = [2, 1]$ (elements with indices $3$ and $4$ are selected in the subsequence $p$).

import sys
from sys import stdin

def modfac(n, MOD):

    f = 1
    factorials = [1]
    for m in range(1, n + 1):
        f *= m
        f %= MOD
        factorials.append(f)
    inv = pow(f, MOD - 2, MOD)
    invs = [1] * (n + 1)
    invs[n] = inv
    for m in range(n, 1, -1):
        inv *= m
        inv %= MOD
        invs[m - 1] = inv
    return factorials, invs

def modnCr(n,r,mod,fac,inv):
    return fac[n] * inv[n-r] * inv[r] % mod

mod = 998244353

n = int(stdin.readline())
a = list(map(int,stdin.readline().split()))
a.sort()
fac,inv = modfac(2*n+10,mod)

print( (modnCr(2*n,n,mod,fac,inv) * (sum(a[n:]) - sum(a[:n]))) % mod )


Solve in Python:
You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears:  Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;  Let this segment be $[l; r]$. If $r-l+1$ is odd (not divisible by $2$) then assign (set) $a[\frac{l+r}{2}] := i$ (where $i$ is the number of the current action), otherwise (if $r-l+1$ is even) assign (set) $a[\frac{l+r-1}{2}] := i$.

Consider the array $a$ of length $5$ (initially $a=[0, 0, 0, 0, 0]$). Then it changes as follows:  Firstly, we choose the segment $[1; 5]$ and assign $a[3] := 1$, so $a$ becomes $[0, 0, 1, 0, 0]$;  then we choose the segment $[1; 2]$ and assign $a[1] := 2$, so $a$ becomes $[2, 0, 1, 0, 0]$;  then we choose the segment $[4; 5]$ and assign $a[4] := 3$, so $a$ becomes $[2, 0, 1, 3, 0]$;  then we choose the segment $[2; 2]$ and assign $a[2] := 4$, so $a$ becomes $[2, 4, 1, 3, 0]$;  and at last we choose the segment $[5; 5]$ and assign $a[5] := 5$, so $a$ becomes $[2, 4, 1, 3, 5]$.

Your task is to find the array $a$ of length $n$ after performing all $n$ actions. Note that the answer exists and unique.

You have to answer $t$ independent test cases.

-----Input-----

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

The only line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $a$.

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

-----Output-----

For each test case, print the answer — the array $a$ of length $n$ after performing $n$ actions described in the problem statement. Note that the answer exists and unique.

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

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

import sys
input = sys.stdin.readline

def construct(A,count,MAX):
    #print(ANS,A,count,MAX)
    B=[]
    NMAX=0
    for l,r in A:
        if r-l+1==MAX:
            ANS[(r+l)//2]=count
            count+=1

            if l<=(r+l)//2-1:
                NMAX=max(NMAX,(r+l)//2-l)
                B.append((l,(r+l)//2-1))
            if r>=(r+l)//2+1:
                NMAX=max(NMAX,r-(r+l)//2)
                B.append(((r+l)//2+1,r))
        else:
            NMAX=max(NMAX,r-l+1)
            B.append((l,r))
    if NMAX!=0:
        construct(B,count,NMAX)

t=int(input())
for tests in range(t):
    n=int(input())
    ANS=[0]*n
    construct([(0,n-1)],1,n)
    print(*ANS)


Solve in Python:
You are given an array $a$ of length $n$, which initially is a permutation of numbers from $1$ to $n$. In one operation, you can choose an index $i$ ($1 \leq i < n$) such that $a_i < a_{i + 1}$, and remove either $a_i$ or $a_{i + 1}$ from the array (after the removal, the remaining parts are concatenated).

For example, if you have the array $[1, 3, 2]$, you can choose $i = 1$ (since $a_1 = 1 < a_2 = 3$), then either remove $a_1$ which gives the new array $[3, 2]$, or remove $a_2$ which gives the new array $[1, 2]$.

Is it possible to make the length of this array equal to $1$ with these operations?

-----Input-----

The first line contains a single integer $t$ ($1 \leq t \leq 2 \cdot 10^4$)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \leq n \leq 3 \cdot 10^5$)  — the length of the array.

The second line of each test case contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \leq a_i \leq n$, $a_i$ are pairwise distinct) — elements of the array.

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

-----Output-----

For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.

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

Output
YES
YES
NO
YES

-----Note-----

For the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):

$[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$

$[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$

$[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3},...

def main():
    n = int(input())
    a = list(map(int, input().split()))
    if a[0] < a[-1]:
        print("YES")
    else:
        print("NO")

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

__starting_point()


Solve in Python:
You are given an array $a$ of length $n$. A subsequence of this array is valid, if it satisfies these two conditions:
- There shouldn't be any two even numbers within a distance of $K$, both which have been chosen in the subsequence. i.e. there shouldn't be two indices $i, j$ such that $a_i$ and $a_j$ are even, $|i - j| \leq K$ and $a_i$ and $a_j$ are in the subsequence.
- Similarly, there shouldn't be any two odd numbers within a distance of $K$, both which have been chosen in the subsequence
The sum of a subsequence is the sum of all the numbers in it. Your task is find the maximum sum possible in a valid subsequence of the given array. Print this maximum sum.

-----Input-----
- The first line of the input contains an integer $T$ denoting the number of test cases. The description of the test cases follows.
- The first line of each test case contains two space-separated integers $n, k$.
- The second line of each test case contains $n$ space-separated integers denoting the array $a$.

-----Output-----
For each test case, output an integer corresponding to the answer of the problem.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le n \leq 10^5$
- $1 \le k \leq  n$
- $1 \le a_i \leq 10^9$
- Sum of $n$ over all the test cases doesn't exceed $10^6$

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

-----Example Output-----
3
2
11

-----Explanation:-----
Testcase 2: Only one of the two 2s can be chosen. Hence the answer is 2.
Testcase 3: The subsequence containing the second, third and fifth numbers is a valid subsequence, and its sum is 2+3+6 = 11. You can check that this is the maximum possible, and hence is the answer.

def solve(array,k,n):

 even=[]
 odd=[]
 for i in range(n):
  if array[i]%2==0:
   even.append(array[i])
   odd.append(0)
  else:
   odd.append(array[i])
   even.append(0)
 dpEven=[0]*n
 dpOdd=[0]*n
 dpEven[0]=even[0]
 dpOdd[0]=odd[0]
 i=1
 while i<=k and i<n:
  dpEven[i]=max(dpEven[i-1],even[i])
  dpOdd[i]=max(dpOdd[i-1],odd[i])
  i+=1
 for i in range(k+1,n):
  dpEven[i]=max(dpEven[i-1],dpEven[i-k-1]+even[i])
 for i in range(k+1,n):
  dpOdd[i]=max(dpOdd[i-1],dpOdd[i-k-1]+odd[i])
 return dpOdd[-1]+dpEven[-1]
queries=[]
for _ in range(int(input())):
 n,k=map(int,input().split( ))
 queries.append((list(map(int,input().split( ))),k))

for query in queries:
 print(solve(query[0],query[1],len(query[0])))


Solve in Python:
You are given an array $a$, consisting of $n$ integers.

Each position $i$ ($1 \le i \le n$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.

For example, let $a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$, the underlined positions are locked. You can obtain the following arrays:   $[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$;  $[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$;  $[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$;  $[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$;  and some others.

Let $p$ be a sequence of prefix sums of the array $a$ after the rearrangement. So $p_1 = a_1$, $p_2 = a_1 + a_2$, $p_3 = a_1 + a_2 + a_3$, $\dots$, $p_n = a_1 + a_2 + \dots + a_n$.

Let $k$ be the maximum $j$ ($1 \le j \le n$) such that $p_j < 0$. If there are no $j$ such that $p_j < 0$, then $k = 0$.

Your goal is to rearrange the values in such a way that $k$ is minimum possible.

Output the array $a$ after the rearrangement such that the value $k$ for it is minimum possible. If there are multiple answers then print any of them.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of testcases.

Then $t$ testcases follow.

The first line of each testcase contains a single integer $n$ ($1 \le n \le 100$) — the number of elements in the array $a$.

The second line of each testcase contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^5 \le a_i \le 10^5$) — the initial array $a$.

The third line of each testcase contains $n$ integers $l_1, l_2, \dots, l_n$ ($0 \le l_i \le 1$), where $l_i = 0$ means that the position $i$ is unlocked and $l_i = 1$ means that the position $i$ is...

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    l = list(map(int, input().split()))
    b = []
    for i in range(n):
        if l[i] == 0:
            b.append(a[i])
    b.sort()
    b.reverse()
    j = 0
    for i in range(n):
        if l[i] == 0:
            a[i] = b[j]
            j += 1
    print(*a)


Solve in Python:
You are given an array $a_1, a_2 \dots a_n$. Calculate the number of tuples $(i, j, k, l)$ such that:   $1 \le i < j < k < l \le n$;  $a_i = a_k$ and $a_j = a_l$;

-----Input-----

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

The first line of each test case contains a single integer $n$ ($4 \le n \le 3000$) — the size of the array $a$.

The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) — the array $a$.

It's guaranteed that the sum of $n$ in one test doesn't exceed $3000$.

-----Output-----

For each test case, print the number of described tuples.

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

Output
5
2

-----Note-----

In the first test case, for any four indices $i < j < k < l$ are valid, so the answer is the number of tuples.

In the second test case, there are $2$ valid tuples:   $(1, 2, 4, 6)$: $a_1 = a_4$ and $a_2 = a_6$;  $(1, 3, 4, 6)$: $a_1 = a_4$ and $a_3 = a_6$.

def calcCntAtPrefix(a):
    cntAtPrefix = [[0] * (len(a) + 1)]
    for i, x in enumerate(a):
        cntAtPrefix.append(cntAtPrefix[-1][:])
        cntAtPrefix[-1][x] += 1
    return cntAtPrefix

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

    cntAtPrefix = calcCntAtPrefix(a)
    cntAtSuffix = calcCntAtPrefix(a[::-1])

    ans = 0
    for j in range(n):
        for k in range(j + 1, n):
            ans += cntAtPrefix[j][a[k]] * cntAtSuffix[n - 1 - k][a[j]]
    print(ans)

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


Solve in Python:
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer `N`. Write a method that takes the array as an argument and returns this "outlier" `N`.

## Examples

```python
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)
```

def find_outlier(integers):
    parity = [n % 2 for n in integers]
    return integers[parity.index(1)] if sum(parity) == 1 else integers[parity.index(0)]


Solve in Python:
You are given an array A consisting of N integers. A group of disjoint subarrays in it will be a collection of subarrays of the array. Formally a group of subarrays consisting of K subarrays can be denoted by 2 * K indices, [i1, j1], [i2, j2] , ..., [iK, jK], such that i1 ≤ j1 < i2 ≤ j2 < ... < iK ≤ jK.

For example, in array A = {5, 6, 7}. A group of subarrays could be the subarrays denoted by indices [1, 1], [2, 3]. The subarray corresponding to indices [1, 1] will be {5}. The subarray corresponding to indices [2, 3] will be {6, 7}. So, we have i1 = 1, j1 = 1, i2 = 2, j2 = 3 and K = 2. You can check that the indices satisfy the property i1 ≤ j1 < i2 ≤ j2.

Note that the group of subarrays [1, 2] and [2, 3] won't be disjoint, as it does not satisfy the property j1 < i2. In other words, the index 2 is common in two subarrays, which should not happen.

Let M denote the maximum value of K in a group of K disjoint subarrays of array A, such that there are not two elements (not indices) common in those subarrays. This means, that if the group contained subarrays [A[i1], A[j1], [A[i2], A[j2]] , ..., A[[iK, jK]], then there should not be an element which is present in more than one subarrays.

You have to find maximum number of group of disjoint subarrays that number of subarrays in those groups are equal to M. As the answer could be large, output it modulo 109 + 7.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of the each test case contains a single integer N denoting number of elements in array A.
Second line of each test case contains N space separated integers denoting the elements of the array A

-----Output-----
For each test case, output a single line corresponding to maximum number of group of disjoint subarrays of array A.

-----Constraints-----
- 1 ≤ T, N ≤ 105
- 1 ≤ Ai ≤ n
- Sum of N over all the test cases in a single file won't exceed 105

-----Subtasks-----
Subtask #1 (30 points)

- 1 ≤ T, N ≤...

t=int(input())
for k in range(t):
    n=int(input())
    l=[int(i) for i in input().split()]
    m={}
    count=1
    for i in range(1,n):
        if l[i]==l[i-1]:
            count+=1
        else:

            if l[i-1] not in m:
                m[l[i-1]]=(count*(count+1))/2
            else:

                m[l[i-1]]+=(count*(count+1))/2
            count=1
    if(l[n-1]) not in m:
        m[l[n-1]]=(count*(count+1))/2
    else:

        m[l[n-1]]+=(count*(count+1))/2
    s=1

    for x in m:

         s=(s*m[x])%(1000000007)
    print(s)


Solve in Python:
You are given an array A of size N. Let us list down all the subarrays of the given array. There will be a total of N * (N + 1) / 2 subarrays of the given array. Let us sort each of the subarrays in descending order of the numbers in it.

Now you want to sort these subarrays in descending order. You can compare two subarrays B, C, as follows.

compare(B, C):
Append N - |B| zeros at the end of the array B.
Append N - |C| zeros at the end of the array C.
for i = 1 to N:
if B[i] < C[i]:
return B is less than C
if B[i] > C[i]:
return B is greater than C
return B and C are equal.

You are given M queries asking for the maximum element in the pth subarray (1-based indexing).

-----Input-----
The first line of input contains T, the number of test cases.
The first line of each test case contains two space separated integers N and M, denoting the array size and the number of queries respectively.
The next line contains N space-separated integers denoting the array elements.

Each of the next M lines contains a single integer - p.

-----Output-----
Output a single integer corresponding to the maximum element in the pth subarray.

-----Constraints-----
- 1 ≤ Ai ≤ 109
- 1 ≤ p ≤ N+1C2

-----Subtasks-----Subtask #1 (20 points):
- 1 ≤ T ≤ 20
- 1 ≤ N ≤ 200
- 1 ≤ M ≤ 104
Subtask #2 (30 points):
- 1 ≤ T ≤ 20
- 1 ≤ N ≤ 3000
- 1 ≤ M ≤ 104
Subtask #3 (50 points):
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105
- 1 ≤ M ≤ 105

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

Output:4
3

for _ in range(int(input())):
 n,q=map(int,input().split())
 l=[int(i) for i in input().split()]
 qry=[int(input()) for i in range(q)]
 def cmp(sub1,sub2):
  for i in range(len(sub1)):
   if sub1[i]>sub2[i]:
    return 1
   if sub1[i]<sub2[i]:
    return 2
  return 1
 maxl=[]
 for i in range(n):
  for j in range(i,n):
   maxl.append(max(l[i:j+1]))
 maxl.sort(reverse=True)
 for i in qry:
  print(maxl[i-1])


Solve in Python:
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].
Now, a group of special-equivalent strings from A is a non-empty subset of A such that:

Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)

Return the number of groups of special-equivalent strings from A.

Example 1:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.

The other two groups are ["xyzz", "zzxy"] and ["zzyx"].  Note that in particular, "zzxy" is not special equivalent to "zzyx".

Example 2:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3

Note:

1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters.

class Solution:
    def numSpecialEquivGroups(self, A: List[str]) -> int:
        d = set()
        for w in A:
            even = ''.join(sorted(w[0::2]))
            odd = ''.join(sorted(w[1::2]))
            d.add((even, odd))
        return len(d)


Solve in Python:
You are given an array A with size N (indexed from 0) and an integer K. Let's define another array B with size N · K as the array that's formed by concatenating K copies of array A.
For example, if A = {1, 2} and K = 3, then B = {1, 2, 1, 2, 1, 2}.
You have to find the maximum subarray sum of the array B. Fomally, you should compute the maximum value of Bi + Bi+1 + Bi+2 + ... + Bj, where 0 ≤ i ≤ j < N · K.

-----Input-----

- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains two space-separated integers N and K.
- The second line contains N space-separated integers A0, A1, ..., AN-1.

-----Output-----
For each test case, print a single line containing the maximum subarray sum of B.

-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ K ≤ 105
- -106 ≤ Ai ≤ 106 for each valid i

-----Subtasks-----
Subtask #1 (18 points): N · K ≤ 105
Subtask #2 (82 points): original constraints

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

2
2 3
1 2
3 2
1 -2 1

Output:

9
2

-----Explanation-----
Example case 1: B = {1, 2, 1, 2, 1, 2} and the subarray with maximum sum is the whole {1, 2, 1, 2, 1, 2}. Hence, the answer is 9.
Example case 2: B = {1, -2, 1, 1, -2, 1} and the subarray with maximum sum is {1, 1}. Hence, the answer is 2.

# cook your dish here
x = int(input())
for i in range(x):
    n, k = map(int, input().split())
    arr = list(map(int, input().split()))
    ar = [i for i in arr]*k
    l = [0 for i in range(n*k)]
    l[0] = ar[0]
    for i in range(n*k):
        l[i] = max([l[i-1]+ar[i], ar[i]])
    print(max(l))


Solve in Python:
You are given an array A, consisting of N integers and an array B, consisting of M integers.
The subsequence of A is the array that can be obtained by picking the elements at the arbitrary sorted set of positions from A.
Your task is to count the number of such subsequences C of A that:

- C contains exactly M elements.
- The array (C+B) is non-decreasing. Here by + operation, we mean element-wise sum.

For example, the array (4, 8, 5) plus the array (10, 20, 30) is (14, 28, 35).

Formally, (C+B) is an array of size M such that (C+B)i = Ci + Bi.

In case some subsequence appears more that once, you should counts it as many times as it appears.

Formally, two subarrays of an array a, (ai_1, ai_2, ... ,ai_n) and (aj_1, aj_2, ... ,aj_m) will be considered different if either their lengths are different i.e. n != m or there exists an index k such that such that i_k  != j_k.

Since the answer can be very large, we ask you to calculate it, modulo 109+7.

-----Input-----
The first line of input contains a pair of space separated integers N and M, denoting the number of elements in the array A and the number of elements in the array B.
The second line contains N space-separated integers Ai, denoting the array A.
The third line contains M space-separated integers Bj, denoting the array B.

-----Output-----
Output a single line containing the number of subsequences C as asked in the problem, modulo 109+7.

-----Constraints-----
- 1 ≤ Ai, Bi ≤ 109
- 1 ≤ M ≤ N

-----Subtasks-----
- Subtask #1 (33 points): 1 ≤ N ≤ 50, 1 ≤ M ≤ 5
- Subtask #2 (33 points): 1 ≤ N ≤ 500, 1 ≤ M ≤ 50
- Subtask #3 (34 points): 1 ≤ N ≤ 2000, 1 ≤ M ≤ 1000

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

Output #1:
4

Input #2:
4 2
7 7 7 7
3 4

Output #2:
6

-----Explanation-----
Example case 1. The suitable subsequences are (1, 2, 7), (1, 4, 7), (5, 4, 7), (2, 4, 7).
Example case 2. The suitable subsequence is (7, 7), and it appears 6 times:

- at indices (1, 2)
- at indices (1, 3)
- at indices (1, 4)
- at indices (2, 3)
- at indices (2, 4)
- at...

n,m = list(map(int,input().split()))
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
dp = []
for i in range(n):
    dp += [[0]*m]
dp[-1][-1]=1
for i in range(n-2,-1,-1):
    dp[i][-1]=1
    for j in range(m-1):
        x = (a[i]+b[j])-(b[j+1])
        temp = 0
        for k in range(i+1,n):
            if(a[k]>=x):
                temp += dp[k][j+1]
        dp[i][j]=temp
ans = 0
for i in range(n):
    ans += dp[i][0]
print(ans)


Solve in Python:
You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x_1, x_2, ..., x_{k}} (1 ≤ x_{i} ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. $\sum_{i = 1}^{k} a_{x_{i}} \neq \sum_{i = 1}^{k} b_{x_{i}}$

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array.

The second line contains n space-separated distinct integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the elements of the array.

-----Output-----

If there is no such array b, print -1.

Otherwise in the only line print n space-separated integers b_1, b_2, ..., b_{n}. Note that b must be a permutation of a.

If there are multiple answers, print any of them.

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

Output
2 1

Input
4
1000 100 10 1

Output
100 1 1000 10

-----Note-----

An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x.

Note that the empty subset and the subset containing all indices are not counted.

n=int(input())

a=list(map(int,input().split()))
b=a.copy()
a.sort()
c=[]
for i in range(n):
    c.append(a[(a.index(b[i])+1)%n])
print(*c)


Solve in Python:
You are given an array consisting of n non-negative integers a_1, a_2, ..., a_{n}.

You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.

After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.

The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9).

The third line contains a permutation of integers from 1 to n — the order used to destroy elements.

-----Output-----

Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.

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

Output
5
4
3
0

Input
5
1 2 3 4 5
4 2 3 5 1

Output
6
5
5
1
0

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

Output
18
16
11
8
8
6
6
0

-----Note-----

Consider the first sample:   Third element is destroyed. Array is now 1 3  *  5. Segment with maximum sum 5 consists of one integer 5.  Fourth element is destroyed. Array is now 1 3  *   * . Segment with maximum sum 4 consists of two integers 1 3.  First element is destroyed. Array is now  *  3  *   * . Segment with maximum sum 3 consists of one integer 3.  Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.

3
size = int(input())
num = list(map(int, input().split()))
rem = reversed(list(map(lambda x: int(x) - 1, input().split())))
chunks = [None] * size
res = [-1] * size
ans = [0] * size
ms = -1

def addChunk(n):
    chunks[n] = [n, num[n]]
    return n

def getRoot(n):
    while chunks[n][0] != n:
        n = chunks[n][0]
    return n

def mergeChunks(parent, child):
    proot = getRoot(parent)
    croot = getRoot(child)
    chunks[croot][0] = proot
    chunks[proot][1] += chunks[croot][1]
    return proot

for i in rem:
    res[i] = num[i]
    root = addChunk(i)
    if i > 0 and chunks[i - 1] != None:
        root = mergeChunks(i - 1, i)
    if i + 1 < size and chunks[i + 1] != None:
        root = mergeChunks(i, i + 1)
    ms = max(ms, chunks[root][1])
    ans.append(ms)

for i in range(1, size):
    print (ans[-i-1])

print(0)


Solve in Python:
You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.
Notice that x does not have to be an element in nums.
Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

Example 1:
Input: nums = [3,5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.

Example 2:
Input: nums = [0,0]
Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.

Example 3:
Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater than or equal to 3.

Example 4:
Input: nums = [3,6,7,7,0]
Output: -1

Constraints:

1 <= nums.length <= 100
0 <= nums[i] <= 1000

class Solution:
    def specialArray(self, nums: List[int]) -> int:
        # n --> length of given array
        n = len(nums)

        # temporary array with all elements 0
        temp = [0 for i in range(n)]

        # if all elements are 0 then given array is not special
        if nums==temp:
            return -1

        # check for each number from 0 to 1000 that for ith number there are exactly i numbers greater than or equal to i.
        for x in range(1001):
            cnt = 0
            for i in nums:
                if i>=x:
                    cnt+=1
            if cnt==x:
                return x
        return -1


Solve in Python:
You are given an array of N integers a1, a2, ..., aN and an integer K. Find the number of such unordered pairs {i, j} that

- i ≠ j
- |ai + aj - K| is minimal possible

Output  the minimal possible value of |ai + aj - K| (where i ≠ j) and the number of such pairs for the given array and the integer K.

-----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 consists of two space separated integers - N and K respectively.

The second line contains N single space separated integers - a1, a2, ..., aN respectively.

-----Output-----
For each test case, output a single line containing two single space separated integers - the minimal possible value of |ai + aj - K| and the number of unordered pairs {i, j} for which this minimal difference is reached.

-----Constraints-----

- 1 ≤ T ≤ 50
- 1 ≤ ai, K ≤ 109
- N = 2 - 31 point.
- 2 ≤ N ≤ 1000 - 69 points.

-----Example-----
Input:
1
4 9
4 4 2 6

Output:
1 4

-----Explanation:-----
The minimal possible absolute difference of 1 can be obtained by taking the pairs of a1 and a2, a1 and a4, a2 and a4, a3 and a4.

for _ in range(int(input())):
 N, K = map(int, input().split())
 array = list(map(int, input().split()))
 count = 0
 mn = float('inf')
 for i in range(N):
  for j in range(i+1,N):
   if abs(array[i] + array[j] - K) < mn:
    mn = abs(array[i] + array[j] - K)
    count = 1
   elif abs(array[i] + array[j] - K) == mn:
    count+=1
 print(mn, count)


Solve in Python:
You are given an array of `n+1` integers `1` through `n`. In addition there is a single duplicate integer.

The array is unsorted.

An example valid array would be `[3, 2, 5, 1, 3, 4]`. It has the integers `1` through `5` and `3` is duplicated. `[1, 2, 4, 5, 5]` would not be valid as it is missing `3`.

You should return the duplicate value as a single integer.

find_dup = lambda l: [v for i, v in enumerate(l) if l.index(v) != i][0]


Solve in Python:
You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.
Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).
Return the count of all possible routes from start to finish.
Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
Output: 4
Explanation: The following are all possible routes, each uses 5 units of fuel:
1 -> 3
1 -> 2 -> 3
1 -> 4 -> 3
1 -> 4 -> 2 -> 3

Example 2:
Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
Output: 5
Explanation: The following are all possible routes:
1 -> 0, used fuel = 1
1 -> 2 -> 0, used fuel = 5
1 -> 2 -> 1 -> 0, used fuel = 5
1 -> 0 -> 1 -> 0, used fuel = 3
1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5

Example 3:
Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
Output: 0
Explanation: It's impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
Example 4:
Input: locations = [2,1,5], start = 0, finish = 0, fuel = 3
Output: 2
Explanation: There are two possible routes, 0 and 0 -> 1 -> 0.
Example 5:
Input: locations = [1,2,3], start = 0, finish = 2, fuel = 40
Output: 615088286
Explanation: The total number of possible routes is 2615088300. Taking this number modulo 10^9 + 7 gives us 615088286.

Constraints:

2 <= locations.length <= 100
1 <= locations[i] <= 10^9
All integers in locations are distinct.
0 <= start, finish < locations.length
1 <= fuel <= 200

class Solution:
    def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:

        @lru_cache(None)
        def dp(i, f):
            if f<0: return 0
            return (sum(dp(j, f-abs(locations[i]-locations[j]))
                      for j in range(len(locations)) if i!=j) + (i==finish))%(10**9+7);

        return dp(start, fuel);


Solve in Python:
You are given an array of integers [A1,A2,…,AN]$[A_1, A_2, \ldots, A_N]$. Let's call adding an element to this array at any position (including the beginning and the end) or removing an arbitrary element from it a modification. It is not allowed to remove an element from the array if it is empty.
Find the minimum number of modifications which must be performed so that the resulting array can be partitioned into permutations. Formally, it must be possible to partition elements of the resulting array into zero or more groups (multisets; not necessarily identical) in such a way that each element belongs to exactly one group and for each group, if it contains L$L$ elements, then it must contain only integers 1$1$ through L$L$, each of them exactly once.

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

-----Output-----
For each test case, print a single line containing one integer ― the minimum required number of modifications.

-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N≤106$1 \le N \le 10^6$
- 1≤Ai≤109$1 \le A_i \le 10^9$ for each valid i$i$
- the sum of N$N$ over all test cases does not exceed 106$10^6$

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

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

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

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

    dp = [[] for val in range(2*n+1)]
    cnt = [0]*(n*2+1)
    dp[0].extend( [ 0 for val in range(n*2+1) ])

    for val in a:
     if val<=2*n: cnt[val]+=1
     else: cost+=1

    for i in range(1, n*2+1):
     rn = n*2//i
     dp[i].extend([ 0 for val in range(rn+1) ])
     for j in range(0, rn+1):
      dp[i][j] = dp[i-1][j] + abs(cnt[i]-j)
     for j in range(rn-1, -1, -1):
      dp[i][j] = min(dp[i][j], dp[i][j+1])

    print( cost+min( dp[2*n][0], dp[2*n][1]) )


Solve in Python:
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.

For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.

Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array.

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

-----Output-----

Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.

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

Output
4

Input
5
1 1 1 1 1

Output
0

-----Note-----

In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.

In the second sample, there is no way to increase any element with a permutation, so the answer is 0.

def solution(n, num_array):

	# If there is only one element in the list, return 0.
	# import pdb; pdb.set_trace
	if (len(num_array) == 1):
		return 0

	# sort the array first
	num_array.sort()
	idx1 = 0
	idx2 = 1
	res = 0
	while (idx2 < len(num_array)):
		num1 = num_array[idx1]
		num2 = num_array[idx2]

		if (num1 < num2):
			# swap the numbers
			res += 1
			idx1 += 1
			idx2 += 1

		else:
			idx2 += 1

	# print(sorted_arr)
	return res

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

print(solution(n, num_array))


Solve in Python:
You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order.

Note that zero is an even number. If you have an empty array, you need to return it.

For example:
```
[5, 3, 2, 8, 1, 4]  -->  [1, 3, 8, 4, 5, 2]

odd numbers ascending:   [1, 3,       5   ]
even numbers descending: [      8, 4,    2]
```

def sort_array(a):
    odds = iter(sorted(n for n in a if n % 2))
    evens = iter(sorted((n for n in a if not n % 2), reverse=True))
    return [next(odds) if n % 2 else next(evens) for n in a]


Solve in Python:
You are given an array of non-negative integers, your task is to complete the series from 0 to the highest number in the array.

If the numbers in the sequence provided are not in order you should order them, but if a value repeats, then you must return a sequence with only one item, and the value of that item must be 0. like this:
```
inputs        outputs
[2,1]     ->  [0,1,2]
[1,4,4,6] ->  [0]
```
Notes: all numbers are positive integers.

This is set of example outputs based on the input sequence.
```
inputs        outputs
[0,1]   ->    [0,1]
[1,4,6] ->    [0,1,2,3,4,5,6]
[3,4,5] ->    [0,1,2,3,4,5]
[0,1,0] ->    [0]
```

def complete_series(a):
    return list(range(max(a) + 1)) if len(a) == len(set(a)) else [0]


Solve in Python:
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once.
Find all the combinations of n elements of the array that their sum are 0.
```python
arr = [1, -1, 2, 3, -2]
n = 3
find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0
```
The function should ouput every combination or group in increasing order.

We may have more than one group:
```python
arr = [1, -1, 2, 3, -2, 4, 5, -3 ]
n = 3
find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]]
```
In the case above the function should output a sorted 2D array.

The function will not give a group twice, or more, only once.

```python
arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ]
n = 3
find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]]
```
If there are no combinations with sum equals to 0, the function will output an alerting message.

```python
arr = [1, 1, 2, 3]
n = 2
find_zero_sum_groups(arr, n) == "No combinations"
```
If the function receives an empty array will output an specific alert:
```python
arr = []
n = 2
find_zero_sum_groups(arr, n) == "No elements to combine"
```
As you have seen the solutions may have a value occurring only once.
Enjoy it!

from itertools import combinations as c
def find_zero_sum_groups(arr, n):
    a=sorted(set(arr))
    ans=[]
    for i in c(a,n):
        if sum(i)==0:
            ans.append(list(i))
    if not arr: return 'No elements to combine'
    if not ans: return 'No combinations'
    if len(ans)==1: return ans[0]
    return ans


Solve in Python:
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.

Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Note:

1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only.

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:

        words = [collections.Counter(word) for word in words]

        c = collections.Counter(chars)

        print(words)
        print(c)

        return sum([sum(list(w.values())) for w in words if all([c[i] >= w[i] for i in w])])


Solve in Python:
You are given an array of unique numbers. The numbers represent points. The higher the number the higher the points.
In the array [1,3,2] 3 is the highest point value so it gets 1st place. 2 is the second highest so it gets second place. 1 is the 3rd highest so it gets 3rd place.

Your task is to return an array giving each number its rank in the array.
input // [1,3,2]
output // [3,1,2]

```rankings([1,2,3,4,5]) // [5,4,3,2,1]```
```rankings([3,4,1,2,5])//  [3,2,5,4,1]```
```rankings([10,20,40,50,30]) //  [5, 4, 2, 1, 3]```
```rankings([1, 10]) //   [2, 1]```
```rankings([22, 33, 18, 9, 110, 4, 1, 88, 6, 50]) //```
```[5, 4, 6, 7, 1, 9, 10, 2, 8, 3]```

def rankings(arr):
    ranks = {x: i for i, x in enumerate(sorted(arr, reverse=True), 1)}
    return [ranks[x] for x in arr]


Solve in Python:
You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to the closest person.

Example 1:

Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

Example 2:
Input: seats = [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

Example 3:
Input: seats = [0,1]
Output: 1

Constraints:

2 <= seats.length <= 2 * 104
seats[i] is 0 or 1.
At least one seat is empty.
At least one seat is occupied.

class Solution:
    def maxDistToClosest(self, seats: List[int]) -> int:
        ans = 0
        for seat, group in itertools.groupby(seats):
            if not seat:
                k = len(list(group))
                ans = max(ans, (k+1)//2)
        return max(ans, seats.index(1),seats[::-1].index(1))


Solve in Python:
You are given an array that of arbitrary depth that needs to be nearly flattened into a 2 dimensional array. The given array's depth is also non-uniform, so some parts may be deeper than others.

All of lowest level arrays (most deeply nested) will contain only integers and none of the higher level arrays will contain anything but other arrays. All arrays given will be at least 2 dimensional. All lowest level arrays will contain at least one element.

Your solution should be an array containing all of the lowest level arrays and only these. The sub-arrays should be ordered by the smallest element within each, so `[1,2]` should preceed `[3,4,5]`. Note: integers will not be repeated.

For example:

If you receive `[[[1,2,3],[4,5]],[6,7]]`, your answer should be `[[1,2,3],[4,5],[6,7]]`.

def near_flatten(xs):
    def f(xs):
        if all(not isinstance(x, list) for x in xs):
            yield xs
            return
        for x in xs:
            yield from f(x)
    return sorted(f(xs))


Solve in Python:
You are given an array with $N$ integers: $A[1], A[2], \ldots, A[N]$ (where $N$ is even). You are allowed to permute the elements however you want. Say, after permuting the elements, you end up with the array $A'[1], A'[2], \ldots, A'[N]$. Your goal is to maximize the following sum:
|A′[1]−A′[2]| + |A′[3]−A′[4]| + ... + |A′[N−1]−A′[N]||A′[1]−A′[2]| + |A′[3]−A′[4]| + ... + |A′[N−1]−A′[N]|
|A'[1] - A'[2]| \ + \ |A'[3] - A'[4]| \ + \ ... \ + \ |A'[N - 1] - A'[N]|

Here, $|x|$ denotes the absolute value of $x$.
You have to print the maximum sum achievable.

-----Input-----
- The first line contains $T$, the number of test cases.
- Each test case starts with an integer $N$ in the first line.
- The second line of each test case contains $N$ space separated integers, denoting the values of array $A$.

-----Output-----
For each test case, output the maximum sum achievable in a new line.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le N \le 10^5$
- $N$ is even
- $|A[i]| \le 10^9$
- Sum of $N$ over all test cases $\le 2 * 10^5$

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

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

-----Explanation 1-----
The original array is {$1, -3, 2, -3$}. Suppose you permute it and get the array {$2, 1, -3, -3$}. Then the corresponding sum would be $|2 - 1| \ + \ |-3 - (-3)| = 1 + 0 = 1$.
But suppose you permute it differently and get the array {$-3, 2, 1, -3$}. Then the corresponding sum would be $|-3 - 2| \ + \ |1 - (-3)| = 5 + 4 = 9$. You can check that you cannot do any better, and hence the answer is 9.

# cook your dish here
t=int(input())
for i in range(t):
 res=0
 n=int(input())
 l1=list(map(int,input().split()))
 l1.sort()
 for i in range(n//2):
  res=res+abs(l1[i]-l1[n-i-1])
 print(res)