Solve in Python:
You are given an array with several `"even"` words, one `"odd"` word, and some numbers mixed in.

Determine if any of the numbers in the array is the index of the `"odd"` word. If so, return `true`, otherwise `false`.

def odd_ball(xs):
    return xs.index('odd') in xs


Solve in Python:
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west,
    x[2] metres to the south,
    x[3] metres to the east and so on. In other words, after each move your direction changes
    counter-clockwise.

    Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.

Example 1:

Given x = [2, 1, 1, 2],
?????
?   ?
???????>
    ?

Return true (self crossing)

Example 2:

Given x = [1, 2, 3, 4],
????????
?      ?
?
?
?????????????>

Return false (not self crossing)

Example 3:

Given x = [1, 1, 1, 1],
?????
?   ?
?????>

Return true (self crossing)

Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases.

class Solution:
     def isSelfCrossing(self, x):
         """
         :type x: List[int]
         :rtype: bool
         """
         b = c = d = e = 0
         for a in x:
             if d >= b > 0 and (a >= c or a >= c-e >= 0 and f >= d-b):
                 return True
             b, c, d, e, f = a, b, c, d, e
         return False


Solve in Python:
You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].
The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.

Example 1:

Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Explanation:

We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.

Example 2:
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18

Example 3:
Input: points = [[0,0],[1,1],[1,0],[-1,1]]
Output: 4

Example 4:
Input: points = [[-1000000,-1000000],[1000000,1000000]]
Output: 4000000

Example 5:
Input: points = [[0,0]]
Output: 0

Constraints:

1 <= points.length <= 1000
-106 <= xi, yi <= 106
All pairs (xi, yi) are distinct.

class UnionFind:
    def __init__(self, n):
        self.parent = collections.defaultdict(int)
        for i in range(1, n + 1):
            self.parent[i] = i

    def find(self, i):
        if i != self.parent[i]:
            self.parent[i] = self.find(self.parent[i])
        return self.parent[i]

    def union(self, u, v):
        u_parent, v_parent = self.find(u), self.find(v)
        if u_parent == v_parent: return False
        self.parent[u_parent] = v_parent
        return True

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        connections = list()
        for i in range(n - 1):
            for j in range(i+1, n):
                # get distance
                connections.append((i, j, abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])))
        res = 0
        connections_sorted = sorted(connections, key=lambda arr: arr[2])
        UF = UnionFind(n)
        for connection in connections_sorted:
            a, b, cost = connection
            if UF.find(a) != UF.find(b):
                UF.union(a, b)
                res += cost
        return res


Solve in Python:
You are given an axis-aligned rectangle in a 2D Cartesian plane. The bottom left corner of this rectangle has coordinates (0,0)$(0, 0)$ and the top right corner has coordinates (N−1,N−1)$(N-1, N-1)$. You are also given K$K$ light sources; each light source is a point inside or on the perimeter of the rectangle.
For each light source, let's divide the plane into four quadrants by a horizontal and a vertical line passing through this light source. The light source can only illuminate one of these quadrants (including its border, i.e. the point containing the light source and two half-lines), but the quadrants illuminated by different light sources may be different.
You want to assign a quadrant to each light source in such a way that when they illuminate their respective quadrants, the entire rectangle (including its perimeter) is illuminated. Find out whether it is possible to assign quadrants to light sources in such a way.

-----Input-----
- The first line of the input contains an integer T$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 K$K$ and N$N$.
- Each of the next K$K$ lines contains two space-separated integers x$x$ and y$y$ denoting a light source with coordinates (x,y)$(x, y)$.

-----Output-----
For each test case, print a single line containing the string "yes" if it is possible to illuminate the whole rectangle or "no" if it is impossible.

-----Constraints-----
- 1≤T≤5,000$1 \le T \le 5,000$
- 1≤K≤100$1 \le K \le 100$
- 1≤N≤109$1 \le N \le 10^9$
- 0≤x,y≤N−1$0 \le x, y \le N-1$
- no two light sources coincide

-----Example Input-----
2
2 10
0 0
1 0
2 10
1 2
1 1

-----Example Output-----
yes
no

# https://www.codechef.com/problems/RECTLIT

def assess(sq,points):
    EWct = 0
    NSct = 0
    for a,b in points:
        EW = (a == 0 or a == sq)
        NS = (b == 0 or b == sq)
        if EW and NS:
            return 'yes'
        EWct += EW
        NSct += NS
    if NSct + EWct == 0 or len(points) == 1:
        return 'no'
    if EWct >= 2 or NSct >= 2:
        return 'yes'
    if len(points) == 2:
        return 'no'
    # now 3 points
    if NSct == 1 and EWct == 1:
        return 'yes'
    # 3 points, one on edge
    x = -1
    for a,b in points:
        if EWct > 0:
            if a == 0 or a == sq:
                e = b
            elif x == -1:
                x = b
            else:
                y = b
        else:
            if b == 0 or b == sq:
                e = a
            elif x == -1:
                x = a
            else:
                y = a
    if (e-x)*(e-y) < 0: # edge splits mids
        return 'no'
    else:
        return 'yes'

for ti in range(int(input())):
    k,n = map(int, input().split())
    if k > 3:
        for ki in range(k):
            input()
        print('yes')
    else:
        pos = [tuple(map(int, input().split())) for ki in range(k)]
        print(assess(n-1,pos))


Solve in Python:
You are given an empty grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). You should fill this grid with integers in a way that satisfies the following rules:
- For any three cells $c_1$, $c_2$ and $c_3$ such that $c_1$ shares a side with $c_2$ and another side with $c_3$, the integers written in cells $c_2$ and $c_3$ are distinct.
- Let's denote the number of different integers in the grid by $K$; then, each of these integers should lie between $1$ and $K$ inclusive.
- $K$ should be minimum possible.
Find the minimum value of $K$ and a resulting (filled) grid. If there are multiple solutions, you may find any one.

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

-----Output-----
- For each test case, print $N+1$ lines.
- The first line should contain a single integer — the minimum $K$.
- Each of the following $N$ lines should contain $M$ space-separated integers between $1$ and $K$ inclusive. For each valid $i, j$, the $j$-th integer on the $i$-th line should denote the number in the $i$-th row and $j$-th column of the grid.

-----Constraints-----
- $1 \le T \le 500$
- $1 \le N, M \le 50$
- the sum of $N \cdot M$ over all test cases does not exceed $7 \cdot 10^5$

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

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

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

-----Explanation-----
Example case 1: There is only one cell in the grid, so the only valid way to fill it is to write $1$ in this cell. Note that we cannot use any other integer than $1$.
Example case 2: For example, the integers written in the neighbours of cell $(2, 2)$ are $1$, $2$ and $3$; all these numbers are pairwise distinct and the integer written inside the cell $(2, 2)$ does not matter. Note that there are pairs of neighbouring cells with the same integer...

for _ in range(int(input())):
 N,M = map(int,input().split())
 a,b = M//4,M%4
 c,d = M//3,M%3
 strdn1,strdn2,ans='1 1 2 2 ','1 2 3 ',''
 if N==1 and M==1:
  print(1,1,sep="\n")
 elif N==1:
  if M==2:
   print(1)
  else:
   print(2)
  for i in range(1,a+1):
   ans = ans + strdn1
  if b!=0:
   ans = ans+ strdn1[:2*b-1]
  print(ans)
 elif M==1:
  if N==2:
   print(1)
  else:
   print(2)
  for i in range(1,N+1):
   if i%4==1 or i%4==2:
    print(1)
   else:
    print(2)
 elif N==2 and M==2:
  print('2','1 1','2 2',sep="\n")
 elif N==2:
  print(3)
  for i in range(1,c+1):
   ans = ans + strdn2
  if d!=0:
   ans = ans+ strdn2[:2*d-1]
  print(ans)
  print(ans)
 elif M==2:
  print(3)
  for i in range(1,N+1):
   if i%3==0:
    print('3 3')
   else:
    print(str(i%3)+' '+str(i%3))
 else:
  print(4)
  str1,str2='1 2 3 4 ','3 4 1 2 '
  for i in range(1,N+1):
   ans=''
   if i%4==1 or i%4==2:
    for i in range(1,a+1):
     ans = ans + str1
    if b!=0:
     ans = ans+ str1[:2*b-1]
    print(ans)
   else:
    for i in range(1,a+1):
     ans = ans + str2
    if b!=0:
     ans = ans+ str2[:2*b-1]
    print(ans)


Solve in Python:
You are given an equilateral triangle ΔABC with the side BC being the base. Each side of the triangle is of length L. There are L-1 additional points on each of the sides dividing the sides into equal parts of unit lengths. Points on the sides of the triangle are called major points. Joining these points with lines parallel to the sides of ΔABC will produce some more equilateral triangles. The intersection points of these parallel lines are called minor points.

Look at the picture below. It contains

- Major points: A, B, C, P1, P2, Q1, Q3, R1, R4, S1, S2, S3 (note that we consider A, B, C as major points as well)
- Minor points: Q2, R2, R3
- Equilateral triangles ΔP1Q1Q2, ΔQ2S1S3, etc

We consider an equilateral triangle to be valid if

- Each of its vertices is either a major or a minor point, and
- The distance from its base (the base of a triangle is the side parallel to BC) to BC is less than the distance from the other vertex of the triangle (i.e. opposite vertex that doesn't lie on the base of triangle) to BC.

In the figure above, ΔQ2P1P2 is not a valid triangle but ΔQ2R2R3 is a valid triangle.

You will be given L, the length of the original triangle ΔABC. You need to find out the number of valid equilateral triangles with side length exactly K.

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of each testcase follows.
- Each test case has one line containing two space-separated integers: L and K.

-----Output-----
For each testcase, print "Case i: ", and then the answer, where i is the testcase number, 1-indexed.

-----Constraints-----
- 1 ≤ T ≤ 500
-  1 ≤ L, K ≤ 5000

-----Example-----
Input:
2
4 3
4 4

Output:
Case 1: 3
Case 2: 1

-----Explanation-----

The figure presented in the problem description is a triangle with side length 4.
In testcase 1, the valid triangles are ΔAR1R4, ΔP1BS3, ΔP2S1C

In testcase 2, the only valid triangle is ΔABC

case=int(input())
for c in range(case):
 l,k=map(int,input().split())
 sum=0
 for i in range(1,(l-k)+2):
  sum+=i
 print("Case {}:".format(c+1),sum)


Solve in Python:
You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.

-----Input-----

The first line of input will contain two integers n, m (2 ≤ n, m ≤ 2 500), the dimensions of the image.

The next n lines of input will contain a binary string with exactly m characters, representing the image.

-----Output-----

Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.

-----Example-----
Input
3 5
00100
10110
11001

Output
5

-----Note-----

We first choose k = 2.

The image is padded as follows:

001000

101100

110010

000000

We can toggle the image to look as follows:

001100

001100

000000

000000

We can see that this image is compressible for k = 2.

#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt

from sys import stdin

def run(n, m, pixels):
    ans = 1 << 30

    acc = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n):
        for j in range(m):
            acc[i + 1][j + 1] = acc[i + 1][j] + int(pixels[i][j])
        for j in range(m):
            acc[i + 1][j + 1] += acc[i][j + 1]
    # print(acc)

    for k in range(2, max(n, m) + 1):
        r, c = (n + k - 1) // k, (m + k - 1) // k
        res = 0
        for i in range(r):
            for j in range(c):
                x, y = i * k, j * k
                x2, y2 = min(x + k - 1, n - 1), min(y + k - 1, m - 1)
                zero = acc[x2 + 1][y2 + 1] - acc[x][y2 + 1] - acc[x2 + 1][y] + acc[x][y]
                # print(x, y, k, zero, k * k - zero)
                res += min(zero, k * k - zero)
        # print(k, res)
        ans = min(ans, res)
    print(ans)

def main():
    n, m = [int(x) for x in stdin.readline().split()]
    pixels = []
    for i in range(n):
        pixels.append(stdin.readline().strip())
    run(n, m, pixels)

def __starting_point():
    import os

    if os.path.exists('tmp.in'):
        stdin = open('tmp.in')
    main()

__starting_point()


Solve in Python:
You are given an initial 2-value array (x). You will use this to calculate a score.

If both values in (x) are numbers, the score is the sum of the two. If only one is a number, the score is that number. If neither is a number, return 'Void!'.

Once you have your score, you must return an array of arrays. Each sub array will be the same as (x) and the number of sub arrays should be equal to the score.

For example:

if (x) == ['a', 3]  you should return [['a', 3], ['a', 3], ['a', 3]].

def explode(arr):
    return [arr] * sum(v for v in arr if isinstance(v,int)) or 'Void!'


Solve in Python:
You are given an input string.

For each symbol in the string if it's the first character occurrence, replace it with a '1', else replace it with the amount of times you've already seen it...

But will your code be **performant enough**?

___

## Examples:

```
input   =  "Hello, World!"
result  =  "1112111121311"

input   =  "aaaaaaaaaaaa"
result  =  "123456789101112"
```

There might be some non-ascii characters in the string.

~~~if:java
Note: there will be no int domain overflow (character occurrences will be less than 2 billion).
~~~
~~~if:c
(this does not apply to the C language translation)
~~~

def numericals(line):

    counts = dict.fromkeys(line, 0)
    output = []
    for char in line:
        counts[char] += 1
        output.append(counts[char])

    return ''.join(str(number) for number in output)


Solve in Python:
You are given an integer $D$. Find an integer sequence $A_1, A_2, \ldots, A_N$ such that the following conditions are satisfied:
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^5$ for each valid $i$
- $\sum_{i=1}^N \sum_{j=i}^N \left( \mathrm{min}(A_i, A_{i+1}, \ldots, A_j) - \mathrm{GCD}(A_i, A_{i+1}, \ldots, A_j) \right) = D$
It can be proved that a solution always exists under the given constraints.
Note: $\mathrm{GCD}(B_1, B_2, \ldots, B_M)$ is the greatest integer which divides all the integers $B_1, B_2, \ldots, B_M$.

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

-----Output-----
For each test case, print two lines. The first of these lines should contain a single integer $N$. The second line should contain $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
If there are multiple solutions, you may find any one of them.

-----Constraints-----
- $1 \le T \le 10$
- $0 \le D \le 10^9$

-----Example Input-----
4
2
5
200
13

-----Example Output-----
3
3 3 2
5
2 8 5 1 10
7
12 10 15 11 19 13 15
4
5 4 4 10

# cook your dish here
t=int(input())
for i in range(t):
 D=int(input())
 P=10**5-2
 ans=[]
 if(D==0):
  ans.append(1)
 while(D>0):
  P=min(P,D)
  ans.append(P+2)
  ans.append(P+1)
  ans.append(1)
  D-=P
 print(len(ans))
 print(*ans,sep=" ")


Solve in Python:
You are given an integer array A.  From some starting index, you can make a series of jumps.  The (1st, 3rd, 5th, ...) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps.
You may from index i jump forward to index j (with i < j) in the following way:

During odd numbered jumps (ie. jumps 1, 3, 5, ...), you jump to the index j such that A[i] <= A[j] and A[j] is the smallest possible value.  If there are multiple such indexes j, you can only jump to the smallest such index j.
During even numbered jumps (ie. jumps 2, 4, 6, ...), you jump to the index j such that A[i] >= A[j] and A[j] is the largest possible value.  If there are multiple such indexes j, you can only jump to the smallest such index j.
(It may be the case that for some index i, there are no legal jumps.)

A starting index is good if, starting from that index, you can reach the end of the array (index A.length - 1) by jumping some number of times (possibly 0 or more than once.)
Return the number of good starting indexes.

Example 1:
Input: [10,13,12,14,15]
Output: 2
Explanation:
From starting index i = 0, we can jump to i = 2 (since A[2] is the smallest among A[1], A[2], A[3], A[4] that is greater or equal to A[0]), then we can't jump any more.
From starting index i = 1 and i = 2, we can jump to i = 3, then we can't jump any more.
From starting index i = 3, we can jump to i = 4, so we've reached the end.
From starting index i = 4, we've reached the end already.
In total, there are 2 different starting indexes (i = 3, i = 4) where we can reach the end with some number of jumps.

Example 2:
Input: [2,3,1,1,4]
Output: 3
Explanation:
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:

During our 1st jump (odd numbered), we first jump to i = 1 because A[1] is the smallest value in (A[1], A[2], A[3], A[4]) that is greater than or equal to A[0].

During our 2nd jump (even numbered), we jump from i = 1 to i = 2 because A[2] is the largest value in (A[2], A[3],...

class Solution:
    ans = 0
    def bfs(self, index, even, odd, curr):
        # print(index, curr)
        if index == len(even)-1:
            self.ans += 1
            return
        if curr%2 == 0:
            if even[index] != -1:
                self.bfs(even[index], even, odd, curr+1)
        else:
            if odd[index] != -1:
                self.bfs(odd[index],even, odd, curr+1)

    def oddEvenJumps(self, A: List[int]) -> int:
        self.ans = 0
        s = sorted(list(range(len(A))), key = lambda i: A[i])
        a = [-1]*len(A)
        b = [-1]*len(A)
        stack = []
        for val in s:
            while len(stack) > 0 and stack[-1] < val:
                a[stack.pop()] = val
            stack.append(val)
        s = sorted(list(range(len(A))), key = lambda i: A[i], reverse = True)
        stack =[]
        for val in s:
            while len(stack) > 0 and stack[-1] < val:
                b[stack.pop()] = val
            stack.append(val)

        for i, val in enumerate(s):
            self.bfs(i, b, a, 1)
        return self.ans


Solve in Python:
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Input: [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

class Solution:
     def countSmaller(self, nums):
         """
         :type nums: List[int]
         :rtype: List[int]
         """
         s = sorted(nums)
         c = []
         for n in nums:
             p = bisect.bisect_left(s, n)
             c.append(p)
             s.pop(p)
         return c


Solve in Python:
You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all 0 <= i < nums.length-1.
You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.
Find maximum possible value of the final array.

Example 1:
Input: nums = [2,3,1,5,4]
Output: 10
Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.

Example 2:
Input: nums = [2,4,9,24,2,1,10]
Output: 68

Constraints:

1 <= nums.length <= 3*10^4
-10^5 <= nums[i] <= 10^5

class Solution:
    def maxValueAfterReverse(self, nums: List[int]) -> int:
        ans = sum(abs(nums[i+1]-nums[i]) for i in range(len(nums)-1))
        d = 0
        for i in range(1, len(nums)-1):
            d = max(d, abs(nums[0]-nums[i+1]) - abs(nums[i]-nums[i+1]),
                       abs(nums[-1]-nums[i-1]) - abs(nums[i]-nums[i-1]))
        high = -math.inf
        low = math.inf
        for x, y in zip(nums, nums[1:]):
            high = max(high, min(x,y))
            low = min(low, max(x,y))

        return ans + max(d, (high-low)*2)


Solve in Python:
You are given an integer num. You will apply the following steps exactly two times:

Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new integer cannot be 0.

Let a and b be the results of applying the operations to num the first and second times, respectively.
Return the max difference between a and b.

Example 1:
Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888

Example 2:
Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8

Example 3:
Input: num = 123456
Output: 820000

Example 4:
Input: num = 10000
Output: 80000

Example 5:
Input: num = 9288
Output: 8700

Constraints:

1 <= num <= 10^8

class Solution:
    def maxDiff(self, num: int) -> int:
        if num < 10: return 8
        a = b = str(num)
        i = 0
        while i < len(a):
            if a[i] == '9':
                i += 1
            else:
                a = a.replace(a[i], '9')
                break

        if b[0] != '1':
            b = b.replace(b[0], '1')
        else:
            i = 1
            while i < len(b):
                if b[i] == '1' or b[i] == '0':
                    i += 1
                else:
                    b = b.replace(b[i], '0')
                    break
        #print(a,b)
        return int(a) - int(b)


Solve in Python:
You are given an integer sequence $A_1, A_2, \ldots, A_N$ and an integer $X$. Consider a $N \times N$ matrix $B$, where $B_{i,j} = A_i + A_j$ for each valid $i$ and $j$.
You need to find the number of square submatrices of $B$ such that the sum of their elements is $X$. Formally, find the number of quartets $(x_1, y_1, x_2, y_2)$ such that $1 \le x_1 \le x_2 \le N$, $1 \le y_1 \le y_2 \le N$, $x_2-x_1 = y_2-y_1$ and $\sum_{i=x_1}^{x_2}\sum_{j=y_1}^{y_2} B_{i,j} = X$.

-----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 $X$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer ― the number of square submatrices with sum $X$.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le X \le 10^6$
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^6$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$

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

-----Example Input-----
2
5 36
1 2 3 1 12
4 54
3 3 3 3

-----Example Output-----
6
4

from datetime import datetime

class dicta(dict):
 def __init__(self, *args, **kwargs):
  super(dicta, self).__init__(*args, **kwargs)
  self.__dict__ = self

# -----------------------------------------------------------------------------
START_TIME = datetime.now()

def debug(**kwargs):

 return
 diff = str(datetime.now() - START_TIME)
 for key, value in list(kwargs.items()):
  if isinstance(value, list):
   print(diff, key + ':')
   for itemKey, item in enumerate(value):
    print('\t\t\t', str(itemKey) + ': ' + str(item))
  elif isinstance(value, dict):
   print(diff, key + ':')
   for itemKey, item in list(value.items()):
    print('\t\t\t', itemKey + ': ' + str(item))
  else:
   print(diff, key + ': ' + str(value))

# -----------------------------------------------------------------------------
def printResult(result):
 if isinstance(result, list):
  print(*result)
 else:
  print(result)

# -----------------------------------------------------------------------------
def main():
 debug(status='started')
 noOfTests = int(input())

 for i in range(noOfTests):
  result = runATest(i)
  if isinstance(result, tuple):
   for line in result:
    printResult(line)
  else:
   printResult(result)
  if noOfTests > 1:
   debug(status='-------------------- finished Test#' + str(i+1) + '                 --------------------')
 debug(status='finished')

def runATest(_testIndex):

 [count, refTotal] = [int(x) for x in input().split()]

 aList = [int(x) for x in input().split()]
 factors = findFactors(refTotal, count)
 # debug(refTotal=refTotal, count=count, factors=factors)

 total = 0
 for factor in factors:
  total += countSquaresOfSize(aList, refTotal, count, factor)
 return total

def findFactors(refTotal, maxFactor):

 outList = [1]

 for i in range(2, int(refTotal/2)+1):
  if i > maxFactor:
   break
  if refTotal % i == 0:
   outList.append(i)

 if refTotal <= maxFactor:
  outList.append(refTotal)

 return outList

def countSquaresOfSize(aList, refTotal, count, size):

 reqSum = int(refTotal / size)
 sumList = [0]...


Solve in Python:
You are given an integer sequence $A_1, A_2, \ldots, A_N$. For any pair of integers $(l, r)$ such that $1 \le l \le r \le N$, let's define $\mathrm{OR}(l, r)$ as $A_l \lor A_{l+1} \lor \ldots \lor A_r$. Here, $\lor$ is the bitwise OR operator.
In total, there are $\frac{N(N+1)}{2}$ possible pairs $(l, r)$, i.e. $\frac{N(N+1)}{2}$ possible values of $\mathrm{OR}(l, r)$. Determine if all these values are pairwise distinct.

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

-----Output-----
For each test case, print a single line containing the string "YES" if all values of $\mathrm{OR}(l, r)$ are pairwise distinct or "NO" otherwise (without quotes).

-----Constraints-----
- $1 \le T \le 300$
- $1 \le N \le 10^5$
- $0 \le A_i \le 10^{18}$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $3 \cdot 10^5$

-----Example Input-----
4
3
1 2 7
2
1 2
3
6 5 8
5
12 32 45 23 47

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

-----Explanation-----
Example case 1: The values of $\mathrm{OR}(l, r)$ are $1, 2, 7, 3, 7, 7$ (corresponding to the contiguous subsequences $[1], [2], [7], [1,2], [2,7], [1,2,7]$ respectively). We can see that these values are not pairwise distinct.
Example case 2: The values of $\mathrm{OR}(l, r)$ are $1, 2, 3$ (corresponding to the contiguous subsequences $[1], [2], [1, 2]$ respectively) and they are pairwise distinct.

t = int(input())
while t!= 0:
 n = int(input())
 ls = list(map(int,input().split()))
 p ={0}
 res = set()
 for i in ls:
  p = {i|y for y in p} | {i}
  res |= p
 if len(res) ==(n*(n+1))//2:
  print("YES")
 else:
  print("NO")
 t-=1


Solve in Python:
You are given an n by n ( square ) grid of characters, for example:

```python
[['m', 'y', 'e'],
 ['x', 'a', 'm'],
 ['p', 'l', 'e']]
```

You are also given a list of integers as input, for example:

```python
[1, 3, 5, 8]
```

You have to find the characters in these indexes of the grid if you think of the indexes as:

```python
[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
```

Remember that the indexes start from one and not zero.

Then you output a string like this:

```python
"meal"
```

All inputs will be valid.

def grid_index(grid, indexes):
    n = len(grid)
    idxs = (i - 1 for i in indexes)
    return "".join(grid[i // n][i % n] for i in idxs)


Solve in Python:
You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.

Your task is to choose at most $\lfloor\frac{n}{2}\rfloor$ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.

It is guaranteed that the answer exists. If there are multiple answers, you can print any.

You will be given multiple independent queries to answer.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of queries.

Then $t$ queries follow.

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

The following $m$ lines denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge.

There are no self-loops or multiple edges in the given graph, i. e. for each pair ($v_i, u_i$) there are no other pairs ($v_i, u_i$) or ($u_i, v_i$) in the list of edges, and for each pair ($v_i, u_i$) the condition $v_i \ne u_i$ is satisfied. It is guaranteed that the given graph is connected.

It is guaranteed that $\sum m \le 2 \cdot 10^5$ over all queries.

-----Output-----

For each query print two lines.

In the first line print $k$ ($1 \le \lfloor\frac{n}{2}\rfloor$) — the number of chosen vertices.

In the second line print $k$ distinct integers $c_1, c_2, \dots, c_k$ in any order, where $c_i$ is the index of the $i$-th chosen vertex.

It is guaranteed that the answer exists. If there are multiple answers, you can print any.

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

Output
2
1 3
3
4 3 6

-----Note-----

In the first query any vertex or any pair of vertices will suffice.

 [Image]

Note...

import sys
from collections import deque
for _ in range(int(input())):
    n,m=list(map(int,sys.stdin.readline().split()))
    a=[[] for i in range(n+1)]
    for i in range(m):
        x,y=list(map(int,sys.stdin.readline().split()))
        a[x].append(y)
        a[y].append(x)
    col=[-1]*(n+1)
    col[1]=1
    d=deque([1])
    vis=[0]*(n+1)
    # vis[1]=1
    ans=[[],[1]]

    while d:
        p=d.popleft()
        for i in a[p]:
            if col[i]==-1:
                col[i]=1-col[p]
                ans[1-col[p]].append(i)
                d.append(i)

    if len(ans[0])<=n//2:
        print(len(ans[0]))

        print(*ans[0])
    else:
        print(len(ans[1]))

        print(*ans[1])


Solve in Python:
You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts).

Mike has planned a trip from the vertex (district) $a$ to the vertex (district) $b$ and then from the vertex (district) $b$ to the vertex (district) $c$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $p$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.

You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.

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 five integers $n, m, a, b$ and $c$ ($2 \le n \le 2 \cdot 10^5$, $n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$, $1 \le a, b, c \le n$) — the number of vertices, the number of edges and districts in Mike's trip.

The second line of the test case contains $m$ integers $p_1, p_2, \dots, p_m$ ($1 \le p_i \le 10^9$), where $p_i$ is the $i$-th price from the array.

The following $m$ lines of the test case denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge. There are no...

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

t = int(input())
for _ in range(t):
    n, m, a, b, c = list(map(int,input().split()))
    p = list(map(int, input().split()))
    p.sort()

    pref = [0]
    curr = 0
    for i in range(m):
        curr += p[i]
        pref.append(curr)

    adj = [[] for i in range(n)]
    for _ in range(m):
        u, v = list(map(int,input().split()))
        adj[u - 1].append(v - 1)
        adj[v - 1].append(u - 1)

    aD = [-1] * n
    bD = [-1] * n
    cD = [-1] * n

    for i in range(3):
        q = deque()
        q.append(([a,b,c][i]-1,0))
        l = [aD,bD,cD][i]
        l[q[0][0]] = 0
        while q:
            v, d = q.popleft()
            for nex in adj[v]:
                if l[nex] == -1:
                    l[nex] = d + 1
                    q.append((nex,d+1))
    poss = []
    for i in range(n):
        if aD[i] + bD[i] + cD[i] <= m:
            poss.append(pref[aD[i] + bD[i] + cD[i]] + pref[bD[i]])
    print(min(poss))


Solve in Python:
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

Example 1:

Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
Output: 0.25000
Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.

Example 2:

Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
Output: 0.30000

Example 3:

Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Explanation: There is no path between 0 and 2.

Constraints:

2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
There is at most one edge between every two nodes.

from collections import defaultdict, deque

class Solution:
    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
        stack = deque([start])
        paths = {i: 0 for i in range(n)}
        paths[start] = 1

        graph = {i: {} for i in range(n)}
        for (source, dstn), weight in zip(edges, succProb):
            graph[source][dstn] = graph[dstn][source] = weight

        while stack:
            current = stack.popleft()
            for v in graph[current]:
                if paths[current] * graph[current][v] > paths[v]:
                    stack.append(v)
                    paths[v] = max(paths[current] * graph[current][v], paths[v])
        return paths[end]


Solve in Python:
You are given an unweighted tree with N$N$ nodes (numbered 1$1$ through N$N$). Let's denote the distance between any two nodes p$p$ and q$q$ by d(p,q)$d(p, q)$.
You should answer Q$Q$ queries. In each query, you are given parameters a$a$, da$d_a$, b$b$, db$d_b$, and you should find a node x$x$ such that d(x,a)=da$d(x, a) = d_a$ and d(x,b)=db$d(x, b) = d_b$, or determine that there is no such node.

-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and Q$Q$.
- Each of the next N−1$N-1$ lines contains two space-separated integers u$u$ and v$v$ denoting that nodes u$u$ and v$v$ are connected by an edge.
- Each of the next Q$Q$ lines contains four space-separated integers a$a$, da$d_a$, b$b$ and db$d_b$ describing a query.

-----Output-----
For each query, print a single line containing one integer ― the number of a node satisfying the given requirements, or −1$-1$ if no such node exists.
If there are multiple solutions, you may output any one.

-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N,Q≤106$1 \le N, Q \le 10^6$
- 1≤u,v≤N$1 \le u, v \le N$
- the graph on the input is a tree
- 1≤a,b≤N$1 \le a, b \le N$
- 1≤da,db<N$1 \le d_a, d_b < N$
- the sum of N$N$ over all test cases does not exceed 106$10^6$
- the sum of Q$Q$ over all test cases does not exceed 106$10^6$

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

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

-----Example Output-----
3
5
-1

# cook your dish here
def bfs(tr,sp,d):
    temp=[sp]
    vl=[-1]*len(tr)
    vl[sp]=0
    while(len(temp)>0):
        z=temp.pop(0)
        if(vl[z]>=d):
            continue
        for e in tr[z]:
            if(vl[e]==-1):
                vl[e]=vl[z]+1
                temp.append(e)
    return [i for i in range(len(vl)) if vl[i]==d]

def myfunc():
    n,q=list(map(int,input().split()))
    tr=[[] for _ in range(n+1)]
    for _ in range(n-1):
        u,v=list(map(int,input().split()))
        tr[u].append(v)
        tr[v].append(u)
    for qn in range(q):
        a,da,b,db=list(map(int,input().split()))
        ta=set(bfs(tr,a,da))
        tb=set(bfs(tr,b,db))
        x=list(ta.intersection(tb))
        if(len(x)>0):
            print(x[0])
        else:print(-1)

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


Solve in Python:
You are given an unweighted, undirected graph. Write a program to check if it's a tree topology.

-----Input-----

The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

-----Output-----

Print YES if the given graph is a tree, otherwise print NO.

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

Output:
YES

def main():
 try:
  print("YES")
 except:
  return 0

main()


Solve in Python:
You are given array of integers, your task will be to count all pairs in that array and return their count.

**Notes:**

* Array can be empty or contain only one value; in this case return `0`
* If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` (= 2 pairs of `0`s)
* Random tests: maximum array length is 1000, range of values in array is between 0 and 1000

## Examples

```
[1, 2, 5, 6, 5, 2]  -->  2
```
...because there are 2 pairs: `2` and `5`

```
[1, 2, 2, 20, 6, 20, 2, 6, 2]  -->  4
```

...because there are 4 pairs: `2`, `20`, `6` and `2` (again)

def duplicates(arr):
    return sum(arr.count(i)//2 for i in set(arr))


Solve in Python:
You are given a rows x cols matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (rows - 1, cols - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative return -1.
Notice that the modulo is performed after getting the maximum product.

Example 1:
Input: grid = [[-1,-2,-3],
               [-2,-3,-3],
               [-3,-3,-2]]
Output: -1
Explanation: It's not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.

Example 2:
Input: grid = [[1,-2,1],
               [1,-2,1],
               [3,-4,1]]
Output: 8
Explanation: Maximum non-negative product is in bold (1 * 1 * -2 * -4 * 1 = 8).

Example 3:
Input: grid = [[1, 3],
               [0,-4]]
Output: 0
Explanation: Maximum non-negative product is in bold (1 * 0 * -4 = 0).

Example 4:
Input: grid = [[ 1, 4,4,0],
               [-2, 0,0,1],
               [ 1,-1,1,1]]
Output: 2
Explanation: Maximum non-negative product is in bold (1 * -2 * 1 * -1 * 1 * 1 = 2).

Constraints:

1 <= rows, cols <= 15
-4 <= grid[i][j] <= 4

class Solution:
    def maxProductPath(self, grid: List[List[int]]) -> int:
        rows = len(grid)
        if (rows == 0):
            return -1

        cols = len(grid[0])
        if (cols == 0):
            return -1

        dp = [(1,1)] * cols
        for r, col in enumerate(grid):
            for c, item in enumerate(col):
                if (r == 0 and c == 0):
                    dp[c] = (item, item)
                elif (r == 0):
                    dp[c] = (dp[c-1][0] * item, dp[c-1][1]* item)
                elif (c == 0):
                    dp[c] = (dp[c][0] * item, dp[c][1]* item)
                else:
                    candidate_1 = dp[c-1][0] * item
                    candidate_2 = dp[c-1][1]* item
                    candidate_3 = dp[c][0] * item
                    candidate_4 = dp[c][1]* item

                    m = min(candidate_1, candidate_2, candidate_3, candidate_4)
                    M = max(candidate_1, candidate_2, candidate_3, candidate_4)

                    dp[c] = (m, M)

        if (dp[cols-1][1] >= 0):
            return dp[cols-1][1] % (10**9+7)
        else:
            return -1


Solve in Python:
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.

Example 1:
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:
Input: coins = [2], amount = 3
Output: -1

Example 3:
Input: coins = [1], amount = 0
Output: 0

Example 4:
Input: coins = [1], amount = 1
Output: 1

Example 5:
Input: coins = [1], amount = 2
Output: 2

Constraints:

1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        coins.sort(reverse = True)
        min_coins = float('inf')

        def count_coins(start_coin, coin_count, remaining_amount):
          nonlocal min_coins

          if remaining_amount == 0:
            min_coins = min(min_coins, coin_count)
            return

          # Iterate from largest coins to smallest coins
          for i in range(start_coin, len(coins)):
            remaining_coin_allowance = min_coins - coin_count
            max_amount_possible = coins[i] * remaining_coin_allowance

            if coins[i] <= remaining_amount and remaining_amount < max_amount_possible:
              count_coins(i, coin_count + 1, remaining_amount - coins[i])

        count_coins(0, 0, amount)
        return min_coins if min_coins < float('inf') else -1


Solve in Python:
You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions:

  each row of the matrix contains exactly $a$ ones;  each column of the matrix contains exactly $b$ ones;  all other elements are zeros.

If the desired matrix does not exist, indicate this.

For example, for $n=3$, $m=6$, $a=2$, $b=1$, there exists a matrix satisfying the conditions above:

$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$

-----Input-----

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

Each test case is described by four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$), where $n$ and $m$ are the sizes of the matrix, and $a$ and $b$ are the number of ones for rows and columns, respectively.

-----Output-----

For each test case print:

  "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or  "NO" (without quotes) if it does not exist.

To print the matrix $n \times m$, print $n$ rows, each of which consists of $m$ numbers $0$ or $1$ describing a row of the matrix. Numbers must be printed without spaces.

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

Output
YES
010001
100100
001010
NO
YES
11
11
YES
1100
1100
0011
0011
YES
1
1

import io
import os

from collections import Counter, defaultdict, deque

def solve(R, C, A, B):
    if R * A != C * B:
        return "NO"
    grid = [[0 for c in range(C)] for r in range(R)]
    for r in range(R):
        for i in range(A):
            grid[r][(r * A + i) % C] = 1

    return "YES\n" + "\n".join("".join(map(str, row)) for row in grid)

def __starting_point():
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    T = int(input())
    for t in range(T):
        N, M, A, B = [int(x) for x in input().split()]
        ans = solve(N, M, A, B)
        print(ans)

__starting_point()


Solve in Python:
You are given integer $n$. You have to arrange numbers from $1$ to $2n$, using each of them exactly once, on the circle, so that the following condition would be satisfied:

For every $n$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $2n$ numbers differ not more than by $1$.

For example, choose $n = 3$. On the left you can see an example of a valid arrangement: $1 + 4 + 5 = 10$, $4 + 5 + 2 = 11$, $5 + 2 + 3 = 10$, $2 + 3 + 6 = 11$, $3 + 6 + 1 = 10$, $6 + 1 + 4 = 11$, any two numbers differ by at most $1$. On the right you can see an invalid arrangement: for example, $5 + 1 + 6 = 12$, and $3 + 2 + 4 = 9$, $9$ and $12$ differ more than by $1$.

 [Image]

-----Input-----

The first and the only line contain one integer $n$ ($1 \le n \le 10^5$).

-----Output-----

If there is no solution, output "NO" in the first line.

If there is a solution, output "YES" in the first line. In the second line output $2n$ numbers — numbers from $1$ to $2n$ in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.

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

Output
YES
1 4 5 2 3 6
Input
4

Output
NO

-----Note-----

Example from the statement is shown for the first example.

It can be proved that there is no solution in the second example.

def main():
    n = int(input())
    ans = [0] * (2 * n)
    for i in range(n):
        a = 2 * i + 1
        b = 2 * i + 2
        if i & 1:
            ans[i] = a
            ans[i + n] = b
        else:
            ans[i] = b
            ans[i + n] = a
    ans *= 2
    curr = sum(ans[:n])
    mi = curr
    ma = curr
    for i in range(n, 4 * n):
        curr -= ans[i - n]
        curr += ans[i]
        mi = min(mi, curr)
        ma = max(ma, curr)
    if ma - mi > 1:
        print("NO")
    else:
        print("YES")
        print(*ans[:2*n])
    return 0

main()


Solve in Python:
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.

Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order.

Example 1:

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

Note:

The number of given pairs will be in the range [1, 1000].

class Solution:
     def findLongestChain(self, pairs):
         """
         :type pairs: List[List[int]]
         :rtype: int
         """
         queue = collections.deque(sorted(pairs, key=lambda pair: pair[1]))

         count = 0

         while len(queue) > 0:
           count += 1
           curr = queue.popleft()
           while len(queue) > 0 and queue[0][0] <= curr[1]:
             queue.popleft()

         return count


Solve in Python:
You are given n strings s_1, s_2, ..., s_{n} consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation s_{a}_{i}s_{b}_{i} is saved into a new string s_{n} + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2^{k} such strings) are substrings of the new string. If there is no such k, print 0.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s_1, s_2, ..., s_{n} (1 ≤ |s_{i}| ≤ 100), one per line. The total length of strings is not greater than 100.

The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers a_{i} abd b_{i} (1 ≤ a_{i}, b_{i} ≤ n + i - 1) — the number of strings that are concatenated to form s_{n} + i.

-----Output-----

Print m lines, each should contain one integer — the answer to the question after the corresponding operation.

-----Example-----
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4

Output
1
2
0

-----Note-----

On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.

On the second operation the string "01100" is created. Now all strings of length k = 2 are present.

On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.

from math import log
n = int(input())
p = [bin(p)[2:] for p in range(0,512)]
def mset(s):
    ss = set()
    for k in range(0,10):
        for pi in range(0,2 ** k):
            cs = p[pi]
            cs = (k - len(cs)) * "0" + cs
            if cs in s:
                ss.add(cs)
    return ss
def q(s):
    for k in range(0,10):
        for pi in range(0,2 ** k):
            cs = p[pi]
            cs = (k - len(cs)) * "0" + cs
            if not cs in s:
                return k - 1
s = [[v[:9], v[-9:], mset(v)] for v in [input() for i in range(n)]]
for qa, qb in [[int(v) - 1 for v in input().split()] for i in range(int(input()))]:
    v = [s[qa][0], s[qb][1], mset(s[qa][1] + s[qb][0]) | s[qa][2] | s[qb][2]]
    if len(v[0]) < 9:
        v[0] = (v[0] + s[qb][0])[:9]
    if len(v[1]) < 9:
        v[1] = (s[qa][1] + s[qb][1])[-9:]
    s += [v]
    print(max(q(v[2]),0))


Solve in Python:
You are given positive integers $L$ and $R$. You have to find the sum
S=∑i=LR(L∧(L+1)∧…∧i),S=∑i=LR(L∧(L+1)∧…∧i),S = \sum_{i=L}^R \left(L \wedge (L+1) \wedge \ldots \wedge i\right) \,,
where $\wedge$ denotes the bitwise AND operation. Since the sum could be 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 and only line of each test case contains two space-separated integers $L$ and $R$.

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

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le L \le R \le 10^{18}$

-----Example Input-----
2
1 4
4 10

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

-----Explanation-----
Example case 1: The sum is 1 + 1 AND 2 + 1 AND 2 AND 3 + 1 AND 2 AND 3 AND 4 = 1 + 0 + 0 + 0 = 1.
Example case 2: The sum is 4 + 4 AND 5 + 4 AND 5 AND 6 + 4 AND 5 AND 6 AND 7 + … + 4 AND 5 AND … AND 10 = 4 + 4 + … + 0 = 16.

t=int(input())
m=10**9+7
while t:
 p=0
 res=0
 l,r=map(int,input().split())
 d=r-l+1
 br=bin(r)[2:]
 lbr=len(br)
 l=bin(l)[2:]
 k=-1
 lol=0
 ll=len(l)
 ind=ll-1

 if(2**ll>r):
  for i in range(ll):
   if(l[i]=='0' and br[i]=='1'):
    ind=i
    break
  #print(ind)
  for i in range(len(l)-1,ind,-1):
   k+=1
   if(l[i]=='1'):
    a=2**k
    p+=a
    res+=(min(r+1,2**(k+1))-p)*a
  for i in range(ind+1):
   if(l[i]=='1'):
    res+=2**(ll-i-1)*d

 else:
  for i in range(len(l)-1,-1,-1):
   k+=1
   if(l[i]=='1'):
    a=2**k
    p+=a
    res+=(min(r+1,2**(k+1))-p)*a
 print(res%m)
 t-=1


Solve in Python:
You are given positive integers $N$ and $D$. You may perform operations of the following two types:
- add $D$ to $N$, i.e. change $N$ to $N+D$
- change $N$ to $\mathop{\mathrm{digitsum}}(N)$
Here, $\mathop{\mathrm{digitsum}}(x)$ is the sum of decimal digits of $x$. For example, $\mathop{\mathrm{digitsum}}(123)=1+2+3=6$, $\mathop{\mathrm{digitsum}}(100)=1+0+0=1$, $\mathop{\mathrm{digitsum}}(365)=3+6+5=14$.
You may perform any number of operations (including zero) in any order. Please find the minimum obtainable value of $N$ and the minimum number of operations required to obtain this value.

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

-----Output-----
For each test case, print a single line containing two space-separated integers — the minimum value of $N$ and the minimum required number of operations.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N, D \le 10^{10}$

-----Subtasks-----
Subtask #1 (30 points): $1 \le N, D \le 100$
Subtask #2 (70 points): original constraints

-----Example Input-----
3
2 1
9 3
11 13

-----Example Output-----
1 9
3 2
1 4

-----Explanation-----
Example case 1: The value $N=1$ can be achieved by 8 successive "add" operations (changing $N$ to $10$) and one "digit-sum" operation.
Example case 2: You can prove that you cannot obtain $N=1$ and $N=2$, and you can obtain $N=3$.
The value $N=3$ can be achieved by one "add" and one "digitsum" operation, changing $9$ to $12$ and $12$ to $3$.
Example case 3: $N=1$ can be achieved by operations "add", "add", "digitsum", "digitsum": $11 \rightarrow 24 \rightarrow 37 \rightarrow 10 \rightarrow 1$.

def ds(n):
    num_str = str(n)
    sum = 0
    for i in range(0, len(num_str)):
        sum += int(num_str[i])
    return sum

t = int(input())

for _ in range(t):
	n,d = input().split()
	n = int(n)
	d = int(d)

	s = set()
	temp = n
	for i in range(500000):
		if temp<=9:
			if not temp in s:
				s.add(temp)
				temp = temp+d
			else:
				break
		else:
			temp = ds(temp)

	s = sorted(s)
	k = s[0]

	q = []
	ans = 0
	q.append((n,1))
	while len(q) != 0:
		num = q[0][0]
		step = q[0][1]
		q.pop(0)
		if num is k:
			ans = step-1
			break
		q.append((num+d,step+1))
		q.append((ds(num),step+1))

	print(str(k)+" "+str(ans))


Solve in Python:
You are given sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.
Tozan and Gezan repeats the following sequence of operations:
 - If A and B are equal sequences, terminate the process.
 - Otherwise, first Tozan chooses a positive element in A and decrease it by 1.
 - Then, Gezan chooses a positive element in B and decrease it by 1.
 - Then, give one candy to Takahashi, their pet.
Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

-----Constraints-----
 - 1 \leq N \leq 2 × 10^5
 - 0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)
 - The sums of the elements in A and B are equal.
 - All values in input are integers.

-----Input-----
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_N B_N

-----Output-----
Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

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

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

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:
 - Tozan decreases A_1 by 1.
 - Gezan decreases B_1 by 1.
 - One candy is given to Takahashi.
 - Tozan decreases A_2 by 1.
 - Gezan decreases B_1 by 1.
 - One candy is given to Takahashi.
 - As A and B are equal, the process is terminated.

import sys
input = sys.stdin.readline
from collections import defaultdict
mod = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

def main():
	N = int(input())
	jud = 0
	ans = 0
	S = 0
	m = INF
	for i in range(N):
		A, B = getlist()
		S += A
		if A != B:
			jud = 1
		if A > B:
			m = min(m, B)

	if jud == 0:
		print(0)
	else:
		print(S - m)

def __starting_point():
	main()
__starting_point()


Solve in Python:
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.

We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors $\vec{ab}$ and $\vec{ac}$ is acute (i.e. strictly less than $90^{\circ}$). Otherwise, the point is called good.

The angle between vectors $\vec{x}$ and $\vec{y}$ in 5-dimensional space is defined as $\operatorname{arccos}(\frac{\vec{x} \cdot \vec{y}}{|\vec{x}||\vec{y}|})$, where $\vec{x} \cdot \vec{y} = x_{1} y_{1} + x_{2} y_{2} + x_{3} y_{3} + x_{4} y_{4} + x_{5} y_{5}$ is the scalar product and $|\vec{x}|= \sqrt{\vec{x} \cdot \vec{x}}$ is length of $\vec{x}$.

Given the list of points, print the indices of the good points in ascending order.

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 10^3) — the number of points.

The next n lines of input contain five integers a_{i}, b_{i}, c_{i}, d_{i}, e_{i} (|a_{i}|, |b_{i}|, |c_{i}|, |d_{i}|, |e_{i}| ≤ 10^3)  — the coordinates of the i-th point. All points are distinct.

-----Output-----

First, print a single integer k — the number of good points.

Then, print k integers, each on their own line — the indices of the good points in ascending order.

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

Output
1
1

Input
3
0 0 1 2 0
0 0 9 2 0
0 0 5 9 0

Output
0

-----Note-----

In the first sample, the first point forms exactly a $90^{\circ}$ angle with all other pairs of points, so it is good.

In the second sample, along the cd plane, we can see the points look as follows:

[Image]

We can see that all angles here are acute, so no points are good.

n = int(input())
p = [tuple(map(int, input().split())) for i in range(n)]

def d(a, b):
    return (a[0]-b[0], a[1]-b[1], a[2]-b[2], a[3]-b[3], a[4]-b[4])

def m(a, b):
    t = 0
    for i in range(5):
        t += a[i] * b[i]
    return t

good_points = []
for i in range(n):
    good = True

    for j in range(n):
        if j == i:
            continue

        ab = d(p[j], p[i])

        for k in range(j + 1, n):
            if k == i:
                continue

            ac = d(p[k], p[i])

            if m(ab, ac) > 0:
                good = False
                break

        if not good:
            break

    if good:
        good_points.append(i)

print(len(good_points))
for i in good_points:
    print(i + 1)


Solve in Python:
You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction.

A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.

-----Input-----

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

Next $n$ lines contain queries, one per line. Each line contains three integers $p$, $q$, and $b$ ($0 \le p \le 10^{18}$, $1 \le q \le 10^{18}$, $2 \le b \le 10^{18}$). All numbers are given in notation with base $10$.

-----Output-----

For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.

-----Examples-----
Input
2
6 12 10
4 3 10

Output
Finite
Infinite

Input
4
1 1 2
9 36 2
4 12 3
3 5 4

Output
Finite
Finite
Finite
Infinite

-----Note-----

$\frac{6}{12} = \frac{1}{2} = 0,5_{10}$

$\frac{4}{3} = 1,(3)_{10}$

$\frac{9}{36} = \frac{1}{4} = 0,01_2$

$\frac{4}{12} = \frac{1}{3} = 0,1_3$

n = int(input())
ans = ''
while n > 0:
	p, q, b = list(map(int, input().split(' ')))
	for i in range(6):
		b = b * b % q
	if b * p % q == 0: ans += 'Finite\n'
	else: ans += 'Infinite\n'
	n -= 1
print (ans)


Solve in Python:
You are given the `length` and `width` of a 4-sided polygon. The polygon can either be a rectangle or a square.
If it is a square, return its area. If it is a rectangle, return its perimeter.

```
area_or_perimeter(6, 10) --> 32
area_or_perimeter(4, 4) --> 16
```

> Note: for the purposes of this kata you will assume that it is a square if its `length` and `width` are equal, otherwise it is a rectangle.

def area_or_perimeter(l, w):
    if l != w:
        return l*2 + w*2
    elif l == w:
        return l*w


Solve in Python:
You are given three integers in the range [0-99]. You must determine if any ordering of the numbers forms a date from the 20th century.

- If no ordering forms a date, return the string `"invalid"`.

- If multiple distinct orderings form dates, return the string `"ambiguous"`.

- If only one ordering forms a date, return that date as a string with format `"YY/MM/DD"`.

## Examples

```python
unique_date(13, 12, 77) == '77/12/13' # only the ordering (77, 12, 13) forms a date
unique_date(13, 77, 12) == '77/12/13' # argument order is irrelevant

unique_date(1, 2, 3) == 'ambiguous' # 01/02/03, 02/01/03, ...
unique_date(3, 2, 1) == 'ambiguous'

unique_date(50, 40, 60) == 'invalid' # no ordering could form a date
unique_date(40, 50, 60) == 'invalid'
```

## Note
This kata was inspired by my encounter with [google.com/foobar](http://www.google.com/foobar)

from datetime import datetime
from itertools import permutations

def unique_date(*args):
    dates = set()
    for p in permutations(args):
        try:
            date = '{:02}/{:02}/{:02}'.format(*p)
            datetime.strptime(date, '%y/%m/%d')
            dates.add(date)
        except ValueError: pass
    return dates.pop() if len(dates) == 1 else "ambiguous" if dates else "invalid"


Solve in Python:
You are given three non-negative integers $X$, $Y$ and $N$. Find the number of integers $Z$ such that $0 \le Z \le N$ and $(X \oplus Z) < (Y \oplus Z)$, where $\oplus$ denotes the bitwise XOR operation.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains three space-separated integers $X$, $Y$ and $N$.

-----Output-----
For each test case, print a single line containing one integer ― the number of integers $Z$ which satisfy all conditions.

-----Constraints-----
- $1 \le T \le 1,000$
- $0 \le X, Y, N \le 2^{30} - 1$

-----Subtasks-----
Subtask #1 (5 points): $X, Y, N \le 2^6 - 1$
Subtask #2 (95 points): original constraints

-----Example Input-----
3
1 2 10
2 1 10
0 0 7

-----Example Output-----
6
5
0

# cook your dish here
a = int(input())
for i in range(a):
 b = list(map(int,str(input()).split(' ')))
 Ans = 0
 for i1 in range(b[2]+1):
  if (b[0]^i1)<(b[1]^i1):
   Ans+=1
 print(Ans)


Solve in Python:
You are given three numbers $a$, $b$, $c$ . Write a program to determine the largest number that is less than or equal to $c$ and leaves a remainder $b$ when divided by $a$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains a single line of input, having three integers $a$, $b$, $c$.

-----Output:-----
- For each testcase, output in a single line the largest number less than or equal to $c$.

-----Constraints:-----
- $1 \leq T  \leq 100000$
- $0 \leq b < a < c \leq$ $10$^18

-----Sample Input:-----
1
7 2 10

-----Sample Output:-----
9

t=int(input())
for _ in range(t):
    l=list(map(int,input().split()))
    a=l[0]
    b=l[1]
    c=l[2]
    x=c//a
    while(1):
        if a*x+b<=c:
            print(a*x+b)
            break
        else:
            x=x-1


Solve in Python:
You are given three piles of casino chips: white, green and black chips:

* the first pile contains only white chips
* the second pile contains only green chips
* the third pile contains only black chips

Each day you take exactly two chips of different colors and head to the casino. You can choose any color, but you are not allowed to take two chips of the same color in a day.

You will be given an array representing the number of chips of each color and your task is to return the maximum number of days you can pick the chips. Each day you need to take exactly two chips.

```python
solve([1,1,1]) = 1, because after you pick on day one, there will be only one chip left
solve([1,2,1] = 2, you can pick twice; you pick two chips on day one then on day two
solve([4,1,1]) = 2
```

```javascript
solve([1,1,1]) = 1, because after you pick on day one, there will be only one chip left
solve([1,2,1]) = 2, you can pick twice; you pick two chips on day one then on day two
solve([4,1,1]) = 2
```

```go
solve([1,1,1]) = 1, because after you pick on day one, there will be only one chip left
solve([1,2,1]) = 2, you can pick twice; you pick two chips on day one then on day two
solve([4,1,1]) = 2
```

```ruby
solve([1,1,1]) = 1, because after you pick on day one, there will be only one chip left
solve([1,2,1]) = 2, you can pick twice; you pick two chips on day, two chips on day two
solve([4,1,1]) = 2
```

More examples in the test cases. Good luck!

Brute force is not the way to go here. Look for a simplifying mathematical approach.

def solve(arr):
    return sum(arr)-max(arr) if max(arr)>sum(arr)-max(arr) else sum(arr)//2


Solve in Python:
You are given three sequences: $a_1, a_2, \ldots, a_n$; $b_1, b_2, \ldots, b_n$; $c_1, c_2, \ldots, c_n$.

For each $i$, $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$.

Find a sequence $p_1, p_2, \ldots, p_n$, that satisfy the following conditions:

 $p_i \in \{a_i, b_i, c_i\}$

 $p_i \neq p_{(i \mod n) + 1}$.

In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $i,i+1$ adjacent for $i<n$ and also elements $1$ and $n$) will have equal value.

It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.

-----Input-----

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

The first line of each test case contains one integer $n$ ($3 \leq n \leq 100$): the number of elements in the given sequences.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$).

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \leq b_i \leq 100$).

The fourth line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 100$).

It is guaranteed that $a_i \neq b_i$, $a_i \neq c_i$, $b_i \neq c_i$ for all $i$.

-----Output-----

For each test case, print $n$ integers: $p_1, p_2, \ldots, p_n$ ($p_i \in \{a_i, b_i, c_i\}$, $p_i \neq p_{i \mod n + 1}$).

If there are several solutions, you can print any.

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

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

-----Note-----

In the first test case $p = [1, 2, 3]$.

It is a correct answer, because:

  $p_1 = 1 = a_1$, $p_2 = 2 = b_2$, $p_3 = 3 = c_3$  $p_1 \neq p_2 $, $p_2 \neq p_3 $, $p_3 \neq p_1$

All possible correct answers to this test case are: $[1, 2, 3]$, $[1, 3, 2]$, $[2, 1, 3]$,...

for __ in range(int(input())):
    n = int(input())
    ar1 = list(map(int, input().split()))
    ar2 = list(map(int, input().split()))
    ar3 = list(map(int, input().split()))
    ans = [ar1[0]]
    for i in range(1, n - 1):
        if ar1[i] != ans[-1]:
            ans.append(ar1[i])
        elif ar2[i] != ans[-1]:
            ans.append(ar2[i])
        elif ar3[i] != ans[-1]:
            ans.append(ar3[i])
    if ar1[-1] != ans[-1] and ar1[-1] != ans[0]:
        ans.append(ar1[-1])
    elif ar2[-1] != ans[-1] and ar2[-1] != ans[0]:
        ans.append(ar2[-1])
    elif ar3[-1] != ans[-1] and ar3[-1] != ans[0]:
        ans.append(ar3[-1])
    print(*ans)


Solve in Python:
You are given three strings $a$, $b$ and $c$ of the same length $n$. The strings consist of lowercase English letters only. The $i$-th letter of $a$ is $a_i$, the $i$-th letter of $b$ is $b_i$, the $i$-th letter of $c$ is $c_i$.

For every $i$ ($1 \leq i \leq n$) you must swap (i.e. exchange) $c_i$ with either $a_i$ or $b_i$. So in total you'll perform exactly $n$ swap operations, each of them either $c_i \leftrightarrow a_i$ or $c_i \leftrightarrow b_i$ ($i$ iterates over all integers between $1$ and $n$, inclusive).

For example, if $a$ is "code", $b$ is "true", and $c$ is "help", you can make $c$ equal to "crue" taking the $1$-st and the $4$-th letters from $a$ and the others from $b$. In this way $a$ becomes "hodp" and $b$ becomes "tele".

Is it possible that after these swaps the string $a$ becomes exactly the same as the string $b$?

-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 100$)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains a string of lowercase English letters $a$.

The second line of each test case contains a string of lowercase English letters $b$.

The third line of each test case contains a string of lowercase English letters $c$.

It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding $100$.

-----Output-----

Print $t$ lines with answers for all test cases. For each test case:

If it is possible to make string $a$ equal to string $b$ print "YES" (without quotes), otherwise print "NO" (without quotes).

You can print either lowercase or uppercase letters in the answers.

-----Example-----
Input
4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim

Output
NO
YES
YES
NO

-----Note-----

In the first test case, it is impossible to do the swaps so that string $a$ becomes exactly the same as string $b$.

In the second test case, you should swap $c_i$ with $a_i$ for all possible $i$....

for _ in range(int(input())):
	a, b, c = input(), input(), input()
	n = len(a)

	ok = True
	for i in range(n):
		if c[i] not in [a[i], b[i]]:
			ok = False

	print('YES' if ok else 'NO')


Solve in Python:
You are given two arrays `arr1` and `arr2`, where `arr2` always contains integers.

Write the function `find_array(arr1, arr2)` such that:

For `arr1 = ['a', 'a', 'a', 'a', 'a']`, `arr2 = [2, 4]`
`find_array returns ['a', 'a']`

For `arr1 = [0, 1, 5, 2, 1, 8, 9, 1, 5]`, `arr2 = [1, 4, 7]`
`find_array returns [1, 1, 1]`

For `arr1 = [0, 3, 4]`, `arr2 = [2, 6]`
`find_array returns [4]`

For `arr1=["a","b","c","d"]` , `arr2=[2,2,2]`,
`find_array returns ["c","c","c"]`

For `arr1=["a","b","c","d"]`, `arr2=[3,0,2]`
`find_array returns ["d","a","c"]`

If either `arr1` or `arr2` is empty, you should return an empty arr (empty list in python,
empty vector in c++). Note for c++ use std::vector arr1, arr2.

def find_array(xs, ys):
    return [xs[y] for y in ys if 0 <= y < len(xs)]


Solve in Python:
You are given two binary strings $S$ and $P$, each with length $N$. A binary string contains only characters '0' and '1'. For each valid $i$, let's denote the $i$-th character of $S$ by $S_i$.
You have to convert the string $S$ into $P$ using zero or more operations. In one operation, you should choose two indices $i$ and $j$ ($1 \leq i < j \leq N$) such that $S_i$ is '1' and $S_j$ is '0', and swap $S_i$ with $S_j$.
Determine if it is possible to convert $S$ into $P$ by performing some operations.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains a single string $S$.
- The third line contains a single string $P$.

-----Output-----
For each test case, print a single line containing the string "Yes" if it is possible to convert $S$ into $P$ or "No" otherwise (without quotes).

-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^5$
- $S$ and $P$ contain only characters '0' and '1'
- the sum of $N$ over all test cases does not exceed $10^5$

-----Subtasks-----
Subtask #1 (20 points):
- $N \leq 14$
- the sum of $N$ over all test cases does not exceed $100$
Subtask #2 (30 points): the sum of $N$ over all test cases does not exceed $1,000$
Subtask #3 (50 points): original constraints

-----Example Input-----
3
2
00
00
3
101
010
4
0110
0011

-----Example Output-----
Yes
No
Yes

-----Explanation-----
Example case 1: The strings are already equal.
Example case 2: It can be showed that it is impossible to convert $S$ into $P$.
Example case 3: You can swap $S_2$ with $S_4$. The strings will then be equal.

t = int(input())
for _ in range(t):
 n = int(input())
 s1 = input()
 s2 = input()
 rem = 0
 if (s1.count('1') == s2.count('1') and s1.count('0') == s2.count('0')):
  u1 = 0
  n1 = 0
  s1 = list(s1)
  s2 = list(s2)
  for i in range(n):
   if s1[i] != s2[i]:
    if s1[i] == '1':
     u1 += 1
    elif s2[i] == '1':
     n1 += 1
    if u1 < n1:
     rem = 1
     break
  if rem == 0:
   print("Yes")
  else:
   print("No")
 else:   print("No")


Solve in Python:
You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$:

  Swap any two bits at indices $i$ and $j$ respectively ($1 \le i, j \le n$), the cost of this operation is $|i - j|$, that is, the absolute difference between $i$ and $j$.  Select any arbitrary index $i$ ($1 \le i \le n$) and flip (change $0$ to $1$ or $1$ to $0$) the bit at this index. The cost of this operation is $1$.

Find the minimum cost to make the string $a$ equal to $b$. It is not allowed to modify string $b$.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of the strings $a$ and $b$.

The second and third lines contain strings $a$ and $b$ respectively.

Both strings $a$ and $b$ have length $n$ and contain only '0' and '1'.

-----Output-----

Output the minimum cost to make the string $a$ equal to $b$.

-----Examples-----
Input
3
100
001

Output
2

Input
4
0101
0011

Output
1

-----Note-----

In the first example, one of the optimal solutions is to flip index $1$ and index $3$, the string $a$ changes in the following way: "100" $\to$ "000" $\to$ "001". The cost is $1 + 1 = 2$.

The other optimal solution is to swap bits and indices $1$ and $3$, the string $a$ changes then "100" $\to$ "001", the cost is also $|1 - 3| = 2$.

In the second example, the optimal solution is to swap bits at indices $2$ and $3$, the string $a$ changes as "0101" $\to$ "0011". The cost is $|2 - 3| = 1$.


Solve in Python:
You are given two images img1 and img2 both of size n x n, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image.  After, the overlap of this translation is the number of positions that have a 1 in both images.
(Note also that a translation does not include any kind of rotation.)
What is the largest possible overlap?

Example 1:

Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
Output: 3
Explanation: We slide img1 to right by 1 unit and down by 1 unit.

The number of positions that have a 1 in both images is 3. (Shown in red)

Example 2:
Input: img1 = [[1]], img2 = [[1]]
Output: 1

Example 3:
Input: img1 = [[0]], img2 = [[0]]
Output: 0

Constraints:

n == img1.length
n == img1[i].length
n == img2.length
n == img2[i].length
1 <= n <= 30
img1[i][j] is 0 or 1.
img2[i][j] is 0 or 1.

class Solution:
    def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
        N = len(img1)
        if N == 1:
            return 1 if img1[0][0] == 1 and img2[0][0] == 1 else 0
        max_slide = N
        sliders = set()
        for i in range(N):
            for j in range(N):
                sliders.add((i, j))
                sliders.add((-i, j))
                sliders.add((i, -j))
                sliders.add((-i, -j))

        def slide_and_count(slide):
            res = 0
            left, down = slide
            for i in range(min(N, N-left)):
                i2 = i + left
                for j in range(min(N, N-down)):
                    j2 = j + down
                    if i2 < 0 or j2 < 0:
                        continue
                    try:
                        if img1[i][j] == 1 and img2[i2][j2] == 1:
                            res += 1
                    except:
                        pass

            print(slide, res)
            return res

        return max(slide_and_count(slide) for slide in sliders)


Solve in Python:
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

Define a pair (u,v) which consists of one element from the first array and one element from the second array.

Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.

Example 1:

Given nums1 = [1,7,11], nums2 = [2,4,6],  k = 3

Return: [1,2],[1,4],[1,6]

The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:

Given nums1 = [1,1,2], nums2 = [1,2,3],  k = 2

Return: [1,1],[1,1]

The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

Example 3:

Given nums1 = [1,2], nums2 = [3],  k = 3

Return: [1,3],[2,3]

All possible pairs are returned from the sequence:
[1,3],[2,3]

Credits:Special thanks to @elmirap and @StefanPochmann for adding this problem and creating all test cases.

class Solution:
     def kSmallestPairs(self, nums1, nums2, k):
         """
         :type nums1: List[int]
         :type nums2: List[int]
         :type k: int
         :rtype: List[List[int]]
         """
         #heap based solution
         #visualize as a matrix
         #best possible solution will be first row or first column
         #O(2K + Klog2K) time; O(1) time

         if not nums1 or not nums2:
             return []

         queue = [(nums1[0]+nums2[0],0,0)]
         ans = []
         while queue and len(ans) < k:
             _, i, j = heapq.heappop(queue)
             ans.append([nums1[i],nums2[j]])
             if j+1 < len(nums2): #smallest values #row-wise
                 heapq.heappush(queue, (nums1[i]+nums2[j+1],i,j+1))
             if j == 0 and i+1 < len(nums1): #smallest values #column-wise #takes care of row traversal
                 heapq.heappush(queue, (nums1[i+1]+nums2[j],i+1,j))
         return ans


Solve in Python:
You are given two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. For any two sequences $U_1, U_2, \ldots, U_p$ and $V_1, V_2, \ldots, V_q$, we define
Score(U,V)=∑i=1p∑j=1qUi⋅Vj.Score(U,V)=∑i=1p∑j=1qUi⋅Vj.Score(U, V) = \sum_{i=1}^p \sum_{j=1}^q  U_i \cdot V_j \,.
You should process $Q$ queries of three types:
- $1$ $L$ $R$ $X$: Add $X$ to each of the elements $A_L, A_{L+1}, \ldots, A_R$.
- $2$ $L$ $R$ $X$: Add $X$ to each of the elements $B_L, B_{L+1}, \ldots, B_R$.
- $3$: Print $Score(A, B)$ modulo $998,244,353$.

-----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 integers, $N$ and $M$, denoting the length of $A$ and $B$ respectively.
- The second line contains $N$ integers, elements of $A$.
- The third line contains $M$ integers, elements of $B$.
- The next line will contain an integer, $Q$, number of queries.
- Each of the next $Q$ lines will contain one of $3$ kinds of updates as mentioned in the statement
It’s guaranteed that each update is a valid update operation.

-----Output-----
For each query of the third type, print a single line containing one integer - the answer to that query.

-----Constraints-----
- $1 \le T \le 10$
- $2 \le N, M, Q \le 10^5$
- $0 \le |A_i|, |B_i|, |X| \le 10^5$

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

-----Example Output-----
72
24
90

-----Explanation-----
Before the first operation, $A = [2, -1, 5],\ B = [3, 3, 2, 4]$
So, for the first operation,
$Score(A,\ B) = 2*3 + 2*3 + 2*2 + 2*4$ $+ (-1)*3$ $+ (-1)*3$ $+ (-1)*2$ $+$ $(-1)*4$ $+  5*3$ $+ 5*3$ $+ 5*2$ $+ 5*4$ $= 72.$
After the second query $A = [2, -3, 3]$, $B = [3, 3, 2, 4]$
So, for the third query, $Score(A, B) = 2*3 + 2*3 + 2*2$ $+ 2*4$ $+ (-3)*3$ $+ (-3)*3$ $+ (-3)*2$ $+ (-3)*4$ $+  3*3$ $+ 3*3$ $+ 3*2$ $+ 3*4$ $= 24$.

import sys

mod = 998244353

input = sys.stdin.readline

t = int(input())
for _ in range(t):
 n, m = list(map(int, input().split()))
 arr1 = [int(j) for j in input().split()]
 arr2 = [int(j) for j in input().split()]

 a = sum(arr1)
 b = sum(arr2)

 q = int(input())
 for i in range(q):
  s = input().split()
  if len(s) == 1:
   print(a*b % mod)
  else:
   num, l, r, x = list(map(int, s))
   if num == 1:
    a += (r-l+1)*x
    a %= mod
   else:
    b += (r-l+1)*x
    b %= mod


Solve in Python:
You are given two integer sequences, each of length N: a_1, ..., a_N and b_1, ..., b_N.
There are N^2 ways to choose two integers i and j such that 1 \leq i, j \leq N. For each of these N^2 pairs, we will compute a_i + b_j and write it on a sheet of paper.
That is, we will write N^2 integers in total.
Compute the XOR of these N^2 integers.
Definition of XOR
The XOR of integers c_1, c_2, ..., c_m is defined as follows:
 - Let the XOR be X. In the binary representation of X, the digit in the 2^k's place (0 \leq k; k is an integer) is 1 if there are an odd number of integers among c_1, c_2, ...c_m whose binary representation has 1 in the 2^k's place, and 0 if that number is even.
For example, let us compute the XOR of 3 and 5. The binary representation of 3 is 011, and the binary representation of 5 is 101, thus the XOR has the binary representation 110, that is, the XOR is 6.

-----Constraints-----
 - All input values are integers.
 - 1 \leq N \leq 200,000
 - 0 \leq a_i, b_i < 2^{28}

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N

-----Output-----
Print the result of the computation.

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

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

On the sheet, the following four integers will be written: 4(1+3), 5(1+4), 5(2+3) and 6(2+4).

import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
res = 0
ln = max(max(a), max(b)).bit_length() + 1
for i in range(ln):
  y = (1 << (i + 1))
  u = [x % y for x in a]
  v = [x % y for x in b]
  y >>= 1
  u.sort(reverse = True)
  v.sort()
  t = 0
  k = 0
  kk = 0
  for x in u:
    while k < N and x + v[k] < y: k += 1
    t += N - k
    while kk < N and x + v[kk] < y * 2: kk += 1
    t -= N - kk
  k = 0
  kk = 0
  #print(t)
  for x in u:
    while k < N and x + v[k] < y * 2 + y: k += 1
    t += N - k
    while kk < N and x + v[kk] < y * 4: kk += 1
    t -= N - kk
    #print(t)
  #print(u, v, t)
  res ^= t % 2 * y
print(res)


Solve in Python:
You are given two integers $N$ and $M$. Find the number of sequences $A_1, A_2, \ldots, A_N$, where each element is an integer between $1$ and $M$ (inclusive) and no three consecutive elements are equal. Since this number 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 and only line of each test case contains two space-separated integers $N$ and $M$.

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

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le N, M \le 10^{18}$

-----Subtasks-----
Subtask #1 (50 points):
- $T \le 20$
- $N \le 10^5$
Subtask #2 (50 points): original constraints

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

-----Example Output-----
4
60

t=int(input())
mod=10**9+7
for _ in range(t):
 n,m=map(int,input().split())
 same=[0]
 diff=[m]
 for i in range(n-1):
  s=diff[-1]
  d=(same[-1]+diff[-1])*(m-1)
  same+=[s%mod]
  diff+=[d%mod]
 print((same[-1]+diff[-1])%mod)


Solve in Python:
You are given two integers N$N$ and M$M$. You have to construct a matrix with N$N$ rows and M$M$ columns. Consider a multiset S$S$ which contains N+M$N + M$ integers: for each row and each column of this matrix, the MEX of the elements of this row/column belongs to S$S$. Then, in the matrix you construct, the MEX of S$S$ must be maximum possible.
Note: The MEX of a multiset of integers is the smallest non-negative integer that is not present in this multiset. For example, MEX({4,9,0,1,1,5})=2$\mathrm{MEX}(\{4,9,0,1,1,5\}) = 2$ and MEX({1,2,3})=0$\mathrm{MEX}(\{1,2,3\}) = 0$.

-----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 and only line of each test case contains two space-separated integers N$N$ and M$M$.

-----Output-----
For each test case, print N$N$ lines. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines should contain M$M$ space-separated integers ― the elements in the i$i$-th row of your matrix. Each element of the matrix must be non-negative and must not exceed 109$10^9$.
If there are multiple solutions, you may find any one of them.

-----Constraints-----
- 1≤T≤400$1 \le T \le 400$
- 1≤N,M≤100$1 \le N, M \le 100$
- the sum of N⋅M$N \cdot M$ over all test cases does not exceed 105$10^5$

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

-----Example Output-----
9 1 0
1 0 2
7 5 8
2 2
3 0
1 1
0 1

-----Explanation-----
Example case 1: The MEXs of the rows {9,1,0}$\{9, 1, 0\}$, {1,0,2}$\{1, 0, 2\}$ and {7,5,8}$\{7, 5, 8\}$ are 2$2$, 3$3$ and 0$0$ respectively. The MEXs of the columns {9,1,7}$\{9, 1, 7\}$, {1,0,5}$\{1, 0, 5\}$ and {0,2,8}$\{0, 2, 8\}$ are 0$0$, 2$2$ and 1$1$ respectively. Therefore, the multiset which contains the MEX of each row and each column is S={0,0,1,2,2,3}$S = \{0, 0, 1, 2, 2, 3\}$ and MEX(S)=4$\mathrm{MEX}(S) = 4$. We can show that this is the largest MEX that can be obtained for a 3×3$3 \times 3$ matrix.

for _ in range(int(input())):
    x,y=map(int,input().split())
    if(x==y):
        if(x==1):
            print(1)
        else:
            n=0
            for i in range(x-1):
                n=i
                for _ in range(y):
                    print(n,end=' ')
                    n=(n+1)%x
                print()
            for i in range(x):
                print(i,end=' ')
            print( )
    else:
        l=[]
        n=min(x,y)
        m=max(x,y)
        for _ in range(n):
            l.append([])
        v=n+1
        for i in range(n):
            u=i
            for j in range(m):
                if(j<=n):
                    l[i].append(u)
                    u=(u+1)%(n+1)
                else:
                    if(j>=v):
                        l[i].append(j+1)
                    else:
                        l[i].append(j)
            v=v+1
        if(x>y):
            for i in range(x):
                for j in l:
                    print(j[i],end=' ')
                print( )
        else:
            for i in l:
                for j in i:
                    print(j,end=' ')
                print( )


Solve in Python:
You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available.
You need to determine whether it is possible to measure exactly z litres using these two jugs.

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.

Operations allowed:

Fill any of the jugs completely with water.
Empty any of the jugs.
Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

Example 1: (From the famous "Die Hard" example)

Input: x = 3, y = 5, z = 4
Output: True

Example 2:

Input: x = 2, y = 6, z = 5
Output: False

Credits:Special thanks to @vinod23 for adding this problem and creating all test cases.

class Solution:
     def canMeasureWater(self, x, y, z):
         """
         :type x: int
         :type y: int
         :type z: int
         :rtype: bool
         """

         a,b=x,y
         while y:
             r=x%y
             x=y
             y=r
         return bool(not z or (x and z<=a+b and not z%x))


Solve in Python:
You are given two points $P$ and $Q$ and an opaque sphere in a three-dimensional space. The point $P$ is not moving, while $Q$ is moving in a straight line with constant velocity. You are also given a direction vector $d$ with the following meaning: the position of $Q$ at time $t$ is $Q(t) = Q(0) + d \cdot t$, where $Q(0)$ is the initial position of $Q$.
It is guaranteed that $Q$ is not visible from $P$ initially (at time $t=0$). It is also guaranteed that $P$ and $Q$ do not touch the sphere at any time.
Find the smallest positive time $t_v$ when $Q$ is visible from $P$, i.e. when the line segment connecting points $P$ and $Q$ does not intersect the sphere.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains 13 space-separated integers.
- The first three integers $P_x, P_y, P_z$ denote the coordinates of $P$.
- The next three integers $Q_x, Q_y, Q_z$ denote the initial coordinates of $Q$.
- The next three integers $d_x, d_y, d_z$ denote the components of the direction vector $d$.
- The last four integers $c_x, c_y, c_z, r$ denote the coordinates of the centre of the sphere and its radius.

-----Output-----
For each test case, print a single line containing one real number — the time $t_v$. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$. It is guaranteed that $t_v$ exists and does not exceed $10^9$.

-----Constraints-----
- $1 \le T \le 10^5$
- the absolute values of coordinates of all points do not exceed $2\cdot10^9$
- $1 \le r \le 10^9$

-----Subtasks-----
Subtask #1 (25 points): $P_z = Q_z = d_z = c_z = 0$
Subtask #2 (75 points): original constraints

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

-----Example Output-----
1.0000000000

# cook your dish here
epi=10**-2
def vision(t):
 a1=x0+(dx*t)-x1
 a2=y0+(dy*t)-y1
 a3=z0+(dz*t)-z1
 b=4*((a1*d1)+(a2*d2)+(a3*d3))*((a1*d1)+(a2*d2)+(a3*d3))
 a=4*((a1*a1)+(a2*a2)+(a3*a3))
 value=(b-(a*c))
 return value
xrange=range
for _ in range(int(input())):
 x1,y1,z1,x0,y0,z0,dx,dy,dz,cx,cy,cz,r=list(map(int,input().split()))
 d1=x1-cx
 d2=y1-cy
 d3=z1-cz
 c=(d1*d1)+(d2*d2)+(d3*d3)-(r*r)
 low=0
 high=10**9+1
 while low<(high-10**-6):
  mid=low+(high-low)*1.0/2;
  value=vision(mid);
  if abs(value)<=epi:
   break;
  elif value>0:
   low=mid;
  else:
   high=mid;
 print(mid)


Solve in Python:
You are given two positive integer lists with a random number of elements (1 <= n <= 100). Create a [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) matrix and calculate the average of all values.

Return a float value rounded to 3 decimal places.

## Example

```
a = [1, 2, 3]
b = [4, 5, 6]

#       a =    1  2  3     b =
gcd(a, b) = [ [1, 2, 1],   # 4
              [1, 1, 1],   # 5
              [1, 2, 3] ]  # 6

average(gcd(a, b)) = 1.444
```

from fractions import gcd
from itertools import product, starmap
from statistics import mean

def gcd_matrix(a, b):
    return round(mean(starmap(gcd, product(a, b))), 3)


Solve in Python:
You are given two positive integers $A$ and $B$. Find the number of pairs of positive integers $(X, Y)$ such that $1 \le X \le A$, $1 \le Y \le B$ and $X + Y$ is even.

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

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

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

-----Subtasks-----
Subtask #1 (10 points): $A, B \le 10$
Subtask #2 (10 points): $A, B \le 1,000$
Subtask #3 (80 points): original constraints

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

-----Example Output-----
1
3
12
36

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

for i in range(t):
 a,b = list(map(int,input().split()))

 #x=min(a,b)
 #y=max(a,b)
 count=0

 # for i in range(1,a+1):
 #     for j in range(1,b+1):

 #         if (i+j) %2 ==0:
 #             count+=1

 x = list(range(1,a+1))
 y = list(range(1,b+1))
 #print(x)
 #print(y)

 if len(x) % 2 != 0:
  even_x = len(x)//2
  odd_x = len(x)//2 +1
 else:
  even_x = len(x)//2
  odd_x = len(x)//2

 if len(y) % 2 !=0:
  even_y = len(y)//2
  odd_y = len(y)//2 +1
 else:
  even_y = len(y)//2
  odd_y = len(y)//2

 #print("even_x & even_y : ",even_x,even_y)
 #print("odd_x & odd_y : ",odd_x,odd_y)
 count = (even_x * even_y) + (odd_x * odd_y)

 print(count)


Solve in Python:
You are given two positive integers $N$ and $K$, where $K \le N$. Find a sequence $A_1, A_2, \ldots, A_N$ such that:
- for each valid $i$, $A_i$ is either $i$ or $-i$
- there are exactly $K$ values of $i$ such that $1 \le i \le N$ and $A_1 + A_2 + \ldots + A_i > 0$
If there are multiple solutions, you may print any one of them. It can be proved that at least one solution always exists.

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

-----Output-----
For each test case, print a single line containing $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le K \le N \le 1,000$

-----Subtasks-----
Subtask #1 (10 points): $N \le 10$
Subtask #2 (90 points): original constraints

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

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

for _ in range(int(input())):
 a,b=map(int,input().split())
 arr=[0]*a
 for i in range(a):
  arr[i]=i+1
 x=0
 b=a-b
 if(b>a//2):
  x=b-a//2
  b=a//2
 #print(b,x)
 for i in range(b):
  arr[(2*i)+1]*=-1
 if(a%2==0):
  for i in range(x):
   arr[a-2*i-2]*=-1
 if(a%2!=0):
  for i in range(x):
   arr[a-2*i-1]*=-1
 print(*arr)


Solve in Python:
You are given two positive integers N and K. How many multisets of rational numbers satisfy all of the following conditions?
 - The multiset has exactly N elements and the sum of them is equal to K.
 - Each element of the multiset is one of 1, \frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \dots. In other words, each element can be represented as \frac{1}{2^i}\ (i = 0,1,\dots).
The answer may be large, so print it modulo 998244353.

-----Constraints-----
 - 1 \leq K \leq N \leq 3000
 - All values in input are integers.

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

-----Output-----
Print the number of multisets of rational numbers that satisfy all of the given conditions modulo 998244353.

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

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

The following two multisets satisfy all of the given conditions:
 - {1, \frac{1}{2}, \frac{1}{4}, \frac{1}{4}}
 - {\frac{1}{2}, \frac{1}{2}, \frac{1}{2}, \frac{1}{2}}