Solve in Python:
There are $N$ villages numbered $1$ to $N$. The villages are connected through bi-directional paths in between them. The whole network is in the form of a tree.
Each village has only $1$ fighter but they help each other in times of crisis by sending their fighter to the village in danger through paths along the villages. Defeating a fighter will mean conquering his village. In particular, If village $X$ is under attack, all villages having a path to $X$ will send their fighters for help.
Naruto wants to conquer all the villages. But he cannot take on so many fighters at the same time so he plans to use  a secret technique with which he can destroy  any $1$ village (along with paths connected to it) in the blink of an eye.  However, it can be used only once. He realized that if he destroys any village, say $X$, the maximum number of fighters he has to fight at once reduces to $W$. He wants $W$ to be as small as possible. Help him find the optimal $X$.
In case of multiple answers, choose the smallest value of $X$.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First Line contains $N$.
- Next $N - 1$ lines contain $U, V$, denoting a path between village $U$ and $V$.

-----Output:-----
- For each Test case, print in a new line, optimal $X$ and corresponding value of $W$.

-----Constraints-----
- $1 \leq T \leq 10$
- $3 \leq N \leq 10^5$
- $1 \leq U, V \leq N$
- $U != V$

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

-----Sample Output:-----
1 2
2 1

-----EXPLANATION:-----
Sample 1:  By destroying village $1$,  The fighters Naruto will be fighting at the same time will be from villages $[2, 4]$ and $[3, 5]$.  For this $W$ = $2$. No other choice can give lesser $W$. Hence $1$ is optimal choice.

# cook your dish here
def solve(edges,ans):
 n = len(edges)
 visited = set()
 parents = [-1]*(n+1)
 dp = [0]*(n+1)
 stack = [1]
 w = float('inf')
 x = -1
 while stack:
  node = stack[-1]
  if node not in visited:
   count = 0
   for kid in edges[node]:
    if parents[kid] == -1:
     if kid != 1:
      parents[kid] = node
    else:
     if kid != parents[node]:
      if kid in visited:
       count += 1
      else:
       stack.append(kid)

   if node == 1:
    count -= 1
   if count == len(edges[node])-1:
    stack.pop()
    visited.add(node)
    max_val = 0
    for kid in edges[node]:
     dp[node] += dp[kid]
     max_val = max(max_val,dp[kid])

    dp[node] += 1

    max_val = max(max_val,n-dp[node])
    if max_val < w:
     w = max_val
     x = node
    elif max_val == w:
     x = min(x,node)

 ans.append(str(x)+' '+str(w))

def main():
 t = int(input())
 ans = []
 for i in range(t):
  n = int(input())
  edges = {}
  for j in range(1,n+1):
   edges[j] = []

  for j in range(n-1):
   x,y = list(map(int,input().split()))
   edges[x].append(y)
   edges[y].append(x)

  solve(edges,ans)

 print('\n'.join(ans))

main()


Solve in Python:
There are $X$ people participating in a quiz competition and their IDs have been numbered from $1$ to $X$ (both inclusive). Beth needs to form a team among these $X$ participants. She has been given an integer $Y$. She can choose participants whose ID numbers are divisible by $Y$.
Now that the team is formed, Beth wants to know the strength of her team. The strength of a team is the sum of all the last digits of the team members’ ID numbers.
Can you help Beth in finding the strength of her team?

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. $T$ lines follow
- The first line of each test case contains $X$ and $Y$.

-----Output:-----
- For each test case print the strength of Beth's team

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq X,Y \leq 10^{20}$

-----Sample Input:-----
2
10 3

15 5

-----Sample Output:-----
18

10

-----EXPLANATION:-----
- Example case 1: ID numbers divisible by 3 are 3,6,9 and the sum of the last digits are 3+6+9=18

T = int(input())
while(T):
    xy = [int(x) for x in input().split()]
    st = 0
    n = xy[0] //xy[1]
    for i in range(1,n+1):
        st+=int(str(i*xy[1])[-1])
    print(st)
    T =T-1


Solve in Python:
There are $n$ athletes in front of you. Athletes are numbered from $1$ to $n$ from left to right. You know the strength of each athlete — the athlete number $i$ has the strength $s_i$.

You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.

You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $A$ and $B$ so that the value $|\max(A) - \min(B)|$ is as small as possible, where $\max(A)$ is the maximum strength of an athlete from team $A$, and $\min(B)$ is the minimum strength of an athlete from team $B$.

For example, if $n=5$ and the strength of the athletes is $s=[3, 1, 2, 6, 4]$, then one of the possible split into teams is:   first team: $A = [1, 2, 4]$,  second team: $B = [3, 6]$.

In this case, the value $|\max(A) - \min(B)|$ will be equal to $|4-3|=1$. This example illustrates one of the ways of optimal split into two teams.

Print the minimum value $|\max(A) - \min(B)|$.

-----Input-----

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

Each test case consists of two lines.

The first line contains positive integer $n$ ($2 \le n \le 50$) — number of athletes.

The second line contains $n$ positive integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 1000$), where $s_i$ — is the strength of the $i$-th athlete. Please note that $s$ values may not be distinct.

-----Output-----

For each test case print one integer — the minimum value of $|\max(A) - \min(B)|$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.

-----Example-----
Input
5
5
3 1 2 6 4
6
2 1 3 2 4 3
4
7 9 3 1
2
1 1000
3
100 150 200

Output
1
0
2
999
50

-----Note-----

The first test case was explained in the statement. In the second test case, one of the optimal splits is...

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int,input().split()))
    c = []
    a.sort()
    for i in range(n-1):
        c.append(a[i+1]-a[i])
    print(min(c))


Solve in Python:
There are $n$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $1$ to $n$.

Two fairs are currently taking place in Berland — they are held in two different cities $a$ and $b$ ($1 \le a, b \le n$; $a \ne b$).

Find the number of pairs of cities $x$ and $y$ ($x \ne a, x \ne b, y \ne a, y \ne b$) such that if you go from $x$ to $y$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $x,y$ such that any path from $x$ to $y$ goes through $a$ and $b$ (in any order).

Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $(x,y)$ and $(y,x)$ must be taken into account only once.

-----Input-----

The first line of the input contains an integer $t$ ($1 \le t \le 4\cdot10^4$) — the number of test cases in the input. Next, $t$ test cases are specified.

The first line of each test case contains four integers $n$, $m$, $a$ and $b$ ($4 \le n \le 2\cdot10^5$, $n - 1 \le m \le 5\cdot10^5$, $1 \le a,b \le n$, $a \ne b$) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.

The following $m$ lines contain descriptions of roads between cities. Each of road description contains a pair of integers $u_i, v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$) — numbers of cities connected by the road.

Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.

The sum of the values of $n$ for all sets of input data in the test does not exceed $2\cdot10^5$. The sum of the values of $m$ for all sets of input data in the test does not exceed $5\cdot10^5$.

-----Output-----

Print $t$ integers — the answers to the given test cases in the order they are written in the...

import sys
readline = sys.stdin.readline

def dfs(s, t, Edge):
    N = len(Edge)
    used = [0]*N
    used[s] = 1
    used[t] = 1
    stack = [s]
    while stack:
        vn = stack.pop()
        for vf in Edge[vn]:
            if not used[vf]:
                used[vf] = 1
                stack.append(vf)
    return used

T = int(readline())
Ans = [None]*T
for qu in range(T):
    N, M, A, B = map(int, readline().split())
    A -= 1
    B -= 1
    Edge = [[] for _ in range(N)]
    for _ in range(M):
        a, b = map(int, readline().split())
        a -= 1
        b -= 1
        Edge[a].append(b)
        Edge[b].append(a)
    sa = dfs(A, B, Edge)
    sb = dfs(B, A, Edge)
    ca = 0
    cb = 0
    for fa, fb in zip(sa, sb):
        if fa == fb:
            continue
        if fa:
            ca += 1
        elif fb:
            cb += 1
    Ans[qu] = ca*cb
print('\n'.join(map(str, Ans)))


Solve in Python:
There are $n$ football teams in the world.

The Main Football Organization (MFO) wants to host at most $m$ games. MFO wants the $i$-th game to be played between the teams $a_i$ and $b_i$ in one of the $k$ stadiums.

Let $s_{ij}$ be the numbers of games the $i$-th team played in the $j$-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team $i$, the absolute difference between the maximum and minimum among $s_{i1}, s_{i2}, \ldots, s_{ik}$ should not exceed $2$.

Each team has $w_i$ — the amount of money MFO will earn for each game of the $i$-th team. If the $i$-th team plays $l$ games, MFO will earn $w_i \cdot l$.

MFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set.

However, this problem is too complicated for MFO. Therefore, they are asking you to help them.

-----Input-----

The first line contains three integers $n$, $m$, $k$ ($3 \leq n \leq 100$, $0 \leq m \leq 1\,000$, $1 \leq k \leq 1\,000$) — the number of teams, the number of games, and the number of stadiums.

The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($1 \leq w_i \leq 1\,000$) — the amount of money MFO will earn for each game of the $i$-th game.

Each of the following $m$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) — the teams that can play the $i$-th game. It is guaranteed that each pair of teams can play at most one game.

-----Output-----

For each game in the same order, print $t_i$ ($1 \leq t_i \leq k$) — the number of the stadium, in which $a_i$ and $b_i$ will play the game. If the $i$-th game should not be played, $t_i$ should be equal to $0$.

If there are multiple answers, print any.

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

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

-----Note-----

One of possible solutions to the example is shown below: [Image]

import random
import math

def set_color(game, color):
    color_count[game[0]][game[2]] -= 1
    color_count[game[1]][game[2]] -= 1
    game[2] = color
    color_count[game[0]][game[2]] += 1
    color_count[game[1]][game[2]] += 1

def fix(node):
    minimum = math.inf
    maximum = 0

    for i in range(k):
        minimum = min(minimum, color_count[node][i])
        maximum = max(maximum, color_count[node][i])

    if maximum - minimum <= 2:
        return False

    rand = 0
    for game in games:
        if (game[0] == node or game[1] == node) and color_count[node][game[2]] == maximum:
            rand = r(1,k)
            set_color(game, rand % k)
            return True

    return False

n, m, k = list(map(int,input().split()))
games = [[0 for _ in range(4)] for _ in range(m)]
color_count = [[0 for _ in range(k)] for _ in range(n)]
answers = [0 for _ in range(m)]
_ = list(map(int,input().split()))

color = 0
r = lambda x,y : random.randint(x,y)
for i in range(m):
    a, b = list(map(int,input().split()))
    color = r(1,k) % k
    games[i] = [a-1,b-1,color,i]
    color_count[games[i][0]][color] += 1
    color_count[games[i][1]][color] += 1

bad = True

while bad:
    random.shuffle(games)
    bad = False

    for i in range(n):
        while(fix(i)):
            bad = True

for game in games:
    answers[game[3]] = game[2] + 1

for i in range(m):
    print(answers[i])


Solve in Python:
There are $n$ lamps on a line, numbered from $1$ to $n$. Each one has an initial state off ($0$) or on ($1$).

You're given $k$ subsets $A_1, \ldots, A_k$ of $\{1, 2, \dots, n\}$, such that the intersection of any three subsets is empty. In other words, for all $1 \le i_1 < i_2 < i_3 \le k$, $A_{i_1} \cap A_{i_2} \cap A_{i_3} = \varnothing$.

In one operation, you can choose one of these $k$ subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.

Let $m_i$ be the minimum number of operations you have to do in order to make the $i$ first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between $i+1$ and $n$), they can be either off or on.

You have to compute $m_i$ for all $1 \le i \le n$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n, k \le 3 \cdot 10^5$).

The second line contains a binary string of length $n$, representing the initial state of each lamp (the lamp $i$ is off if $s_i = 0$, on if $s_i = 1$).

The description of each one of the $k$ subsets follows, in the following format:

The first line of the description contains a single integer $c$ ($1 \le c \le n$)  — the number of elements in the subset.

The second line of the description contains $c$ distinct integers $x_1, \ldots, x_c$ ($1 \le x_i \le n$)  — the elements of the subset.

It is guaranteed that:   The intersection of any three subsets is empty;  It's possible to make all lamps be simultaneously on using some operations.

-----Output-----

You must output $n$ lines. The $i$-th line should contain a single integer $m_i$  — the minimum number of operations required to make the lamps $1$ to $i$ be simultaneously on.

-----Examples-----
Input
7 3
0011100
3
1 4 6
3
3 4 7
2
2 3

Output
1
2
3
3
3
3
3

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

Output
1
1
1
1
1
1
4
4

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

Output
1
1
1
1
1

Input
19...

import sys
readline = sys.stdin.readline
class UF():
    def __init__(self, num):
        self.par = [-1]*num
        self.weight = [0]*num
    def find(self, x):
        stack = []
        while self.par[x] >= 0:
            stack.append(x)
            x = self.par[x]
        for xi in stack:
            self.par[xi] = x
        return x

    def union(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            if self.par[rx] > self.par[ry]:
                rx, ry = ry, rx
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
            self.weight[rx] += self.weight[ry]
        return rx

N, K = list(map(int, readline().split()))
S = list(map(int, readline().strip()))

A = [[] for _ in range(N)]

for k in range(K):
    BL = int(readline())
    B = list(map(int, readline().split()))
    for b in B:
        A[b-1].append(k)

cnt = 0
T = UF(2*K)
used = set()
Ans = [None]*N
inf = 10**9+7
for i in range(N):
    if not len(A[i]):
        Ans[i] = cnt
        continue
    kk = 0
    if len(A[i]) == 2:
        x, y = A[i]
        if S[i]:
            rx = T.find(x)
            ry = T.find(y)
            if rx != ry:
                rx2 = T.find(x+K)
                ry2 = T.find(y+K)
                sp = min(T.weight[rx], T.weight[rx2]) + min(T.weight[ry], T.weight[ry2])
                if x not in used:
                    used.add(x)
                    T.weight[rx] += 1
                if y not in used:
                    used.add(y)
                    T.weight[ry] += 1
                rz = T.union(rx, ry)
                rz2 = T.union(rx2, ry2)
                sf = min(T.weight[rz], T.weight[rz2])
                kk = sf - sp
        else:
            rx = T.find(x)
            ry2 = T.find(y+K)
            sp = 0
            if rx != ry2:
                ry = T.find(y)
                rx2 = T.find(x+K)
                sp = min(T.weight[rx], T.weight[rx2]) + min(T.weight[ry], T.weight[ry2])
                if x not in used:
                   ...


Solve in Python:
There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.

We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:   Either this person does not go on the trip,  Or at least $k$ of his friends also go on the trip.

Note that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends.

For each day, find the maximum number of people that can go on the trip on that day.

-----Input-----

The first line contains three integers $n$, $m$, and $k$ ($2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$, $1 \le k < n$) — the number of people, the number of days and the number of friends each person on the trip should have in the group.

The $i$-th ($1 \leq i \leq m$) of the next $m$ lines contains two integers $x$ and $y$ ($1\leq x, y\leq n$, $x\ne y$), meaning that persons $x$ and $y$ become friends on the morning of day $i$. It is guaranteed that $x$ and $y$ were not friends before.

-----Output-----

Print exactly $m$ lines, where the $i$-th of them ($1\leq i\leq m$) contains the maximum number of people that can go on the trip on the evening of the day $i$.

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

Output
0
0
3
3

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

Output
0
0
0
3
3
4
4
5

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

Output
0
0
0
0
3
4
4

-----Note-----

In the first example,   $1,2,3$ can go on day $3$ and $4$.

In the second example,   $2,4,5$ can go on day $4$ and $5$.  $1,2,4,5$ can go on day $6$ and $7$.  $1,2,3,4,5$ can go on day $8$.

In the third example,   $1,2,5$ can go on day $5$.  $1,2,3,5$ can go on day $6$ and $7$.

from collections import deque

def solve(adj, m, k, uv):
    n = len(adj)
    nn = [len(a) for a in adj]
    q = deque()
    for i in range(n):
        if nn[i] < k:
            q.append(i)
    while q:
        v = q.popleft()
        for u in adj[v]:
            nn[u] -= 1
            if nn[u] == k-1:
                q.append(u)
    res = [0]*m
    nk = len([1 for i in nn if i >= k])
    res[-1] = nk
    for i in range(m-1, 0, -1):
        u1, v1 = uv[i]

        if nn[u1] < k or nn[v1] < k:
            res[i - 1] = nk
            continue
        if nn[u1] == k:
            q.append(u1)
            nn[u1] -= 1
        if not q and nn[v1] == k:
            q.append(v1)
            nn[v1] -= 1

        if not q:
            nn[u1] -= 1
            nn[v1] -= 1
            adj[u1].remove(v1)
            adj[v1].remove(u1)

        while q:
            v = q.popleft()
            nk -= 1
            for u in adj[v]:
                nn[u] -= 1
                if nn[u] == k - 1:
                    q.append(u)
        res[i - 1] = nk
    return res

n, m, k = map(int, input().split())
a = [set() for i in range(n)]
uv = []
for i in range(m):
    u, v = map(int, input().split())
    a[u - 1].add(v - 1)
    a[v - 1].add(u - 1)
    uv.append((u-1, v-1))

res = solve(a, m, k, uv)
print(str(res)[1:-1].replace(' ', '').replace(',', '\n'))


Solve in Python:
There are $n$ positive integers $a_1, a_2, \dots, a_n$. For the one move you can choose any even value $c$ and divide by two all elements that equal $c$.

For example, if $a=[6,8,12,6,3,12]$ and you choose $c=6$, and $a$ is transformed into $a=[3,8,12,3,3,12]$ after the move.

You need to find the minimal number of moves for transforming $a$ to an array of only odd integers (each element shouldn't be divisible by $2$).

-----Input-----

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

The first line of a test case contains $n$ ($1 \le n \le 2\cdot10^5$) — the number of integers in the sequence $a$. The second line contains positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).

The sum of $n$ for all test cases in the input doesn't exceed $2\cdot10^5$.

-----Output-----

For $t$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $2$).

-----Example-----
Input
4
6
40 6 40 3 20 1
1
1024
4
2 4 8 16
3
3 1 7

Output
4
10
4
0

-----Note-----

In the first test case of the example, the optimal sequence of moves can be as follows:

  before making moves $a=[40, 6, 40, 3, 20, 1]$;  choose $c=6$;  now $a=[40, 3, 40, 3, 20, 1]$;  choose $c=40$;  now $a=[20, 3, 20, 3, 20, 1]$;  choose $c=20$;  now $a=[10, 3, 10, 3, 10, 1]$;  choose $c=10$;  now $a=[5, 3, 5, 3, 5, 1]$ — all numbers are odd.

Thus, all numbers became odd after $4$ moves. In $3$ or fewer moves, you cannot make them all odd.

t=int(input())
for _ in range(t):
        n=int(input())
        a=[int (i) for i in  input().split()]
        d=dict()
        su=0
        for i in a:
                k=0
                while i%2==0:
                        i=i//2
                        k+=1
                if i not in d:
                        d[i]=k
                else:
                        d[i]=max(d[i],k)
        for i in list(d.values()):
                su+=i
        print(su)


Solve in Python:
There are $n$ programmers that you want to split into several non-empty teams. The skill of the $i$-th programmer is $a_i$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $x$.

Each programmer should belong to at most one team. Some programmers may be left without a team.

Calculate the maximum number of teams that you can assemble.

-----Input-----

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

The first line of each test case contains two integers $n$ and $x$ ($1 \le n \le 10^5; 1 \le x \le 10^9$) — the number of programmers and the restriction of team skill respectively.

The second line of each test case contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the skill of the $i$-th programmer.

The sum of $n$ over all inputs does not exceed $10^5$.

-----Output-----

For each test case print one integer — the maximum number of teams that you can assemble.

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

Output
2
1
0

t=int(input())
for _ in range(t):
  n,x=map(int,input().split())
  a=list(map(int,input().split()))
  a.sort()
  a.reverse()
  count=0
  ans=0
  for i in range(n):
    count+=1
    if count*a[i]>=x:
      ans+=1
      count=0
  print(ans)


Solve in Python:
There are $n$ segments $[l_i, r_i]$ for $1 \le i \le n$. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.

To optimize testing process you will be given multitest.

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 50000$) — the number of queries. Each query contains description of the set of segments. Queries are independent.

First line of each query contains single integer $n$ ($2 \le n \le 10^5$) — number of segments. It is guaranteed that $\sum{n}$ over all queries does not exceed $10^5$.

The next $n$ lines contains two integers $l_i$, $r_i$ per line ($1 \le l_i \le r_i \le 2 \cdot 10^5$) — the $i$-th segment.

-----Output-----

For each query print $n$ integers $t_1, t_2, \dots, t_n$ ($t_i \in \{1, 2\}$) — for each segment (in the same order as in the input) $t_i$ equals $1$ if the $i$-th segment will belongs to the first group and $2$ otherwise.

If there are multiple answers, you can print any of them. If there is no answer, print $-1$.

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

Output
2 1
-1
1 1 2

-----Note-----

In the first query the first and the second segments should be in different groups, but exact numbers don't matter.

In the second query the third segment intersects with the first and the second segments, so they should be in the same group, but then the other group becomes empty, so answer is $-1$.

In the third query we can distribute segments in any way that makes groups non-empty, so any answer of $6$ possible is correct.

T = int(input())
for _ in range(T):
    n = int(input())
    events = []
    results = [0 for i in range(n)]
    fail = False
    for i in range(n):
        l, r = map(int, input().split())
        events.append((l, 0, i))
        events.append((r, 1, i))

    events.sort()
    cnt = 0
    cur_seg = 1
    for _, t, i in events:
        if t == 0:
            cnt += 1
            results[i] = cur_seg
        else:
            cnt -= 1

        if cnt == 0:
            cur_seg = 1 + cur_seg % 2

    if len(set(results)) == 2:
        print(*results)
    else:
        print(-1)


Solve in Python:
There are $n$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup.

The following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day.  Two distinct active startups $A$, $B$, are chosen uniformly at random.  A fair coin is flipped, and with equal probability, $A$ acquires $B$ or $B$ acquires $A$ (i.e. if $A$ acquires $B$, then that means $B$'s state changes from active to acquired, and its starts following $A$).  When a startup changes from active to acquired, all of its previously acquired startups become active.

For example, the following scenario can happen: Let's say $A$, $B$ are active startups. $C$, $D$, $E$ are acquired startups under $A$, and $F$, $G$ are acquired startups under $B$: [Image]

Active startups are shown in red.

If $A$ acquires $B$, then the state will be $A$, $F$, $G$ are active startups. $C$, $D$, $E$, $B$ are acquired startups under $A$. $F$ and $G$ have no acquired startups: $G$

If instead, $B$ acquires $A$, then the state will be $B$, $C$, $D$, $E$ are active startups. $F$, $G$, $A$ are acquired startups under $B$. $C$, $D$, $E$ have no acquired startups: [Image]

You are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following.

You're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end.

It can be shown the expected number of days can be written as a rational number $P/Q$, where $P$ and $Q$ are co-prime integers, and $Q \not= 0 \pmod{10^9+7}$. Return the value of $P \cdot Q^{-1}$ modulo $10^9+7$.

-----Input-----

The first line contains a single integer $n$ ($2 \leq n \leq 500$),...

m = 1000000007
n = int(input())
a = list(map(int, input().split()))
print(pow(2,n-1,m)-1 - sum(pow(2,a.count(x),m)-1 for x in set(a) if x != -1) % m)


Solve in Python:
There are $n$ water tanks in a row, $i$-th of them contains $a_i$ liters of water. The tanks are numbered from $1$ to $n$ from left to right.

You can perform the following operation: choose some subsegment $[l, r]$ ($1\le l \le r \le n$), and redistribute water in tanks $l, l+1, \dots, r$ evenly. In other words, replace each of $a_l, a_{l+1}, \dots, a_r$ by $\frac{a_l + a_{l+1} + \dots + a_r}{r-l+1}$. For example, if for volumes $[1, 3, 6, 7]$ you choose $l = 2, r = 3$, new volumes of water will be $[1, 4.5, 4.5, 7]$. You can perform this operation any number of times.

What is the lexicographically smallest sequence of volumes of water that you can achieve?

As a reminder:

A sequence $a$ is lexicographically smaller than a sequence $b$ of the same length if and only if the following holds: in the first (leftmost) position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.

-----Input-----

The first line contains an integer $n$ ($1 \le n \le 10^6$) — the number of water tanks.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — initial volumes of water in the water tanks, in liters.

Because of large input, reading input as doubles is not recommended.

-----Output-----

Print the lexicographically smallest sequence you can get. In the $i$-th line print the final volume of water in the $i$-th tank.

Your answer is considered correct if the absolute or relative error of each $a_i$ does not exceed $10^{-9}$.

Formally, let your answer be $a_1, a_2, \dots, a_n$, and the jury's answer be $b_1, b_2, \dots, b_n$. Your answer is accepted if and only if $\frac{|a_i - b_i|}{\max{(1, |b_i|)}} \le 10^{-9}$ for each $i$.

-----Examples-----
Input
4
7 5 5 7

Output
5.666666667
5.666666667
5.666666667
7.000000000

Input
5
7 8 8 10 12

Output
7.000000000
8.000000000
8.000000000
10.000000000
12.000000000

Input
10
3 9 5 5 1 7 5 3 8...

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

stack = []
for v in l:
    currVal = v
    currSize = 1
    div = v

    while stack:
        nex, nexS, nDiv = stack[-1]

        if div < nDiv:
            currSize += nexS
            currVal += nex
            stack.pop()

            div = currVal / currSize
        else:
            break
    stack.append((currVal, currSize, div))

out = []
for a, b, d in stack:
    thingy = str(d)
    for _ in range(b):
        out.append(thingy)

print('\n'.join(out))


Solve in Python:
There are 2N balls in the xy-plane. The coordinates of the i-th of them is (x_i, y_i).
Here, x_i and y_i are integers between 1 and N (inclusive) for all i, and no two balls occupy the same coordinates.
In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the type-A robots at coordinates (1, 0), (2, 0), ..., (N, 0), and the type-B robots at coordinates (0, 1), (0, 2), ..., (0, N), one at each position.
When activated, each type of robot will operate as follows.
 - When a type-A robot is activated at coordinates (a, 0), it will move to the position of the ball with the lowest y-coordinate among the balls on the line x = a, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.
 - When a type-B robot is activated at coordinates (0, b), it will move to the position of the ball with the lowest x-coordinate among the balls on the line y = b, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.
Once deactivated, a robot cannot be activated again. Also, while a robot is operating, no new robot can be activated until the operating robot is deactivated.
When Snuke was about to activate a robot, he noticed that he may fail to collect all the balls, depending on the order of activating the robots.
Among the (2N)! possible orders of activating the robots, find the number of the ones such that all the balls can be collected, modulo 1 000 000 007.

-----Constraints-----
 - 2 \leq N \leq 10^5
 - 1 \leq x_i \leq N
 - 1 \leq y_i \leq N
 - If i ≠ j, either x_i ≠ x_j or y_i ≠ y_j.

-----Inputs-----
Input is given from Standard Input in the following format:
N
x_1 y_1
...
x_{2N} y_{2N}

-----Outputs-----
Print the number of the orders of activating the robots such that all the balls can be collected, modulo 1 000 000 007.

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

-----Sample Output-----
8

We will refer to the robots placed at (1, 0) and (2, 0)...

import sys
input = sys.stdin.readline

MOD = 10**9 + 7

N = int(input())
ball = (tuple(int(x) for x in row.split()) for row in sys.stdin.readlines())

# x座標を1,2,...,N
# y座標をN+1,N+2,...,N+N

graph = [set() for _ in range(N+N+1)]
for x,y in ball:
    graph[x].add(y+N)
    graph[y+N].add(x)

visited = [False] * (N+N+1)
components = []
for x in range(1,N+N+1):
    if visited[x]:
        continue
    V = set([x])
    E = []
    q = [x]
    visited[x] = True
    while q:
        y = q.pop()
        for z in graph[y]:
            if y < z:
                E.append((y,z))
            if visited[z]:
                continue
            V.add(z)
            visited[z] = True
            q.append(z)
    components.append((V,E))

def make_get_pattern(V):
    deg1 = [x for x in V if len(graph[x]) == 1]
    get = {}
    while deg1:
        x = deg1.pop()
        if not graph[x]:
            continue
        y = graph[x].pop()
        se = graph[y]; se.remove(x)
        if len(se) == 1: deg1.append(y)
        if x < y:
            get[(x,y)] = 0
        else:
            get[(y,x)] = 1
    for x in V:
        if graph[x]:
            y = graph[x].pop()
            break
    # 残りはサイクル
    graph[y].remove(x)
    if x > y: x,y = y,x
    get[(x,y)] = 2
    while graph[x]:
        y = graph[x].pop()
        graph[y].remove(x)
        if x < y:
            get[(x,y)] = 3
        else:
            get[(y,x)] = 2
        x = y
    return get

def F(V,E):
    # V is connected
    if len(E) != len(V):
        return 0
    ret = 0
    E.sort()
    get = make_get_pattern(V)
    den1,den2 = 1,1
    dp1 = {x:0 for x in V}
    dp2 = {x:0 for x in V}
    for x,y in E:
        if get[(x,y)] == 0:
            k1 = dp1[x] + 1; k2 = dp2[x] + 1
        elif get[(x,y)] == 1:
            k1 = dp1[y] + 1; k2 = dp2[y] + 1
        elif get[(x,y)] == 2:
            k1 = dp1[x] + 1; k2 = dp2[y] + 1
        else:
            k1 = dp1[y] + 1; k2 = dp2[x] + 1
        dp1[x] += k1; dp1[y] += k1
        dp2[x] += k2; dp2[y] += k2
        den1 *= k1; den2...


Solve in Python:
There are 32 letters in the Polish alphabet: 9 vowels and 23 consonants.

Your task is to change the letters with diacritics:

```
ą -> a,
ć -> c,
ę -> e,
ł -> l,
ń -> n,
ó -> o,
ś -> s,
ź -> z,
ż -> z
```
and print out the string without the use of the Polish letters.

For example:
```
"Jędrzej Błądziński"  -->  "Jedrzej Bladzinski"
```

def correct_polish_letters(st):
    dic = {
        "ą":'a',
        "ć":'c',
        "ę":'e',
        "ł":'l',
        'ń':'n',
        'ó':'o',
        'ś':'s',
        'ź':'z',
        'ż': 'z'
    }
    for i in dic:
        st = st.replace(i,dic[i])
    return st


Solve in Python:
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:

In each step, you will choose any 3 piles of coins (not necessarily consecutive).
Of your choice, Alice will pick the pile with the maximum number of coins.
You will pick the next pile with maximum number of coins.
Your friend Bob will pick the last pile.
Repeat until there are no more piles of coins.

Given an array of integers piles where piles[i] is the number of coins in the ith pile.
Return the maximum number of coins which you can have.

Example 1:
Input: piles = [2,4,1,2,7,8]
Output: 9
Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.
Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.
The maximum number of coins which you can have are: 7 + 2 = 9.
On the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.

Example 2:
Input: piles = [2,4,5]
Output: 4

Example 3:
Input: piles = [9,8,7,6,5,1,2,3,4]
Output: 18

Constraints:

3 <= piles.length <= 10^5
piles.length % 3 == 0
1 <= piles[i] <= 10^4

class Solution(object):
    def maxCoins(self, piles):
        piles = collections.deque(sorted(piles)[::-1])
        s = 0
        while len(piles) > 0:
            piles.popleft()
            x = piles.popleft()
            piles.pop()

            s += x

        return s


Solve in Python:
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:

If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
Otherwise, it becomes vacant.

(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)

Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]

Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]

Note:

cells.length == 8
cells[i] is in {0, 1}
1 <= N <= 10^9

# class Solution:
#     def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
#         n = N
#         currCells = cells[:]
#         while n > 0:
#             for i in range(len(cells)):
#                 if i == 0 or i == len(cells)-1:
#                     currCells[i] = 0
#                 elif cells[i-1] == cells[i+1]:
#                     currCells[i] = 1
#                 else:
#                     currCells[i] = 0
#             cells = currCells[:]
#             n -= 1
#         return cells

class Solution:
    def prisonAfterNDays(self, cells, N):

        seen = {}
        while N:
            seen.setdefault(str(cells), N)
            print(seen)
            N -= 1
            cells = [0] + [cells[i - 1] ^ cells[i + 1] ^ 1 for i in range(1, 7)] + [0]
            if str(cells) in seen:
                N %= seen[str(cells)] - N
        return cells


Solve in Python:
There are K nuclear reactor chambers labelled from 0 to K-1. Particles are bombarded onto chamber 0. The particles keep collecting in the chamber 0. However if at any time, there are more than N particles in a chamber, a reaction will cause 1 particle to move to the immediate next chamber(if current chamber is 0, then to chamber number 1), and all the particles in the current    chamber will be be destroyed and same continues till no chamber has number of particles greater than N. Given K,N and the total number of particles bombarded (A), find the final distribution of particles in the K chambers. Particles are bombarded one at a time. After one particle is bombarded, the set of reactions, as described, take place. After all reactions are over, the next particle is bombarded. If a particle is going out from the last chamber, it has nowhere to go and is lost.

-----Input-----

The input will consist of one line containing three numbers A,N and K separated by spaces.
A will be between 0 and 1000000000 inclusive.
N will be between 0 and 100 inclusive.
K will be between 1 and 100 inclusive.
All chambers start off with zero particles initially.

-----Output-----

Consists of K numbers on one line followed by a newline. The first number is the number of particles in chamber 0, the second number is the number of particles in chamber 1 and so on.

-----Example-----
Input:
3 1 3
Output:
1 1 0
Explanation
Total of 3 particles are bombarded. After particle 1 is bombarded, the chambers have particle distribution as
"1 0 0". After second particle is bombarded, number of particles in chamber 0 becomes 2 which is greater
than 1. So, num of particles in chamber 0 becomes 0 and in chamber 1 becomes 1. So now distribution is
"0 1 0". After the 3rd particle is bombarded, chamber 0 gets 1 particle and so distribution is "1 1 0" after all
particles are bombarded one by one.

def __starting_point():
 a, n, k = list(map(int, input().split()))
 s, i = [], 0
 if(n == 0):
  print(*([0]*k))
 else:
  while(a > 0):
   s.append(a%(n+1))
   a = a//(n+1)
   i += 1
  s = s+[0]*(k-i)
  if(len(s) <= k):
   print(*s)
  else:
   print(*(s[:k]))

__starting_point()


Solve in Python:
There are M chairs arranged in a line. The coordinate of the i-th chair (1 ≤ i ≤ M) is i.
N people of the Takahashi clan played too much games, and they are all suffering from backaches. They need to sit in chairs and rest, but they are particular about which chairs they sit in. Specifically, the i-th person wishes to sit in a chair whose coordinate is not greater than L_i, or not less than R_i. Naturally, only one person can sit in the same chair.
It may not be possible for all of them to sit in their favorite chairs, if nothing is done.
Aoki, who cares for the health of the people of the Takahashi clan, decides to provide additional chairs so that all of them can sit in chairs at their favorite positions.
Additional chairs can be placed at arbitrary real coordinates. Find the minimum required number of additional chairs.

-----Constraints-----
 - 1 ≤ N,M ≤ 2 × 10^5
 - 0 ≤ L_i < R_i ≤ M + 1(1 ≤ i ≤ N)
 - All input values are integers.

-----Input-----
Input is given from Standard Input in the following format:
N M
L_1 R_1
:
L_N R_N

-----Output-----
Print the minimum required number of additional chairs.

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

-----Sample Output-----
0

The four people can sit in chairs at the coordinates 3, 2, 1 and 4, respectively, and no more chair is needed.

from operator import itemgetter
from heapq import heappush, heappop
N, M = list(map(int, input().split()))
LR = [list(map(int, input().split())) for _ in range(N)]
LR.sort(key=itemgetter(1))
A = []
ans_left = 0
idx = 1
for _, r in LR:
    if r==M+1 or idx==M+1:
        break
    ans_left += 1
    idx = max(idx+1, r+1)

idx_LR = 0
q = []
for i in range(M+1-ans_left, M+1):
    while idx_LR<N and LR[idx_LR][1]<=i:
        l, _ = LR[idx_LR]
        heappush(q, l)
        idx_LR += 1
    heappop(q)
while idx_LR<N:
    l, _ = LR[idx_LR]
    q.append(l)
    idx_LR += 1

q.sort(reverse=True)
ans_right = 0
idx = M
for l in q:
    if l==0 or idx==0 or ans_right+ans_left==M:
        break
    ans_right += 1
    idx = min(l-1, idx-1)
ans = N - ans_left - ans_right
print(ans)


Solve in Python:
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

 -  When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.
For example, 3~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.
We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

-----Constraints-----
 - All values in input are integers.
 - 2 \leq N \leq 200000
 - N is even.
 - 0 \leq a_i \leq 10^9
 - There exists a combination of integers on the scarfs that is consistent with the given information.

-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N

-----Output-----
Print a line containing N integers separated with space.
The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.
If there are multiple possible solutions, you may print any of them.

-----Sample Input-----
4
20 11 9 24

-----Sample Output-----
26 5 7 22

 - 5~\textrm{xor}~7~\textrm{xor}~22 = 20
 - 26~\textrm{xor}~7~\textrm{xor}~22 = 11
 - 26~\textrm{xor}~5~\textrm{xor}~22 = 9
 - 26~\textrm{xor}~5~\textrm{xor}~7 = 24
Thus, this output is consistent with the given information.

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

cnt=0
for i in range(N):
    cnt=cnt^a[i]

B=[]*N
for i in range(N):
    ans=cnt^a[i]
    B.append(str(ans))

print(' '.join(B))


Solve in Python:
There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.
For each of these bags, you will paint one of the balls red, and paint the other blue.
Afterwards, the 2N balls will be classified according to color.
Then, we will define the following:
 - R_{max}: the maximum integer written on a ball painted in red
 - R_{min}: the minimum integer written on a ball painted in red
 - B_{max}: the maximum integer written on a ball painted in blue
 - B_{min}: the minimum integer written on a ball painted in blue
Find the minimum possible value of (R_{max} - R_{min}) \times (B_{max} - B_{min}).

-----Constraints-----
 - 1 ≤ N ≤ 200,000
 - 1 ≤ x_i, y_i ≤ 10^9

-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N

-----Output-----
Print the minimum possible value.

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

-----Sample Output-----
15

The optimal solution is to paint the balls with x_1, x_2, y_3 red, and paint the balls with y_1, y_2, x_3 blue.

from collections import deque
N=int(input())
Ball=deque([])
m,M=float("inf"),0
for i in range(N):
  a,b=list(map(int,input().split()))
  if a>b:
    a,b=b,a
  if a<m:
    m=a
    mp=i
  if b>M:
    M=b
    Mp=i
  Ball.append((a,b))
s=max([a[0] for a in Ball])
t=min([a[1] for a in Ball])
ans=(s-m)*(M-t)
if mp==Mp:
  print(ans)
  return
l=min(Ball[mp][1],Ball[Mp][0])
r=max(Ball[mp][1],Ball[Mp][0])
for i in range(2*N):
  if Ball:
    a,b=Ball.popleft()
    if l<=a<=r or l<=b<=r:
      pass
    elif a>r:
      r=a
    elif b<l:
      l=b
    elif a<l and b>r:
      Ball.append((a,b))
  else:
    break
if Ball:
  Ball=sorted(list(Ball),key=lambda x:(x[0],-x[1]))
  Max=[r]
  for i in range(len(Ball)):
    Max.append(max(Max[-1],Ball[i][1]))
  for i in range(len(Ball)):
    ans=min(ans,(M-m)*(Max[i]-Ball[i][0]))
  ans=min(ans,(M-m)*(Max[len(Ball)]-l))
else:ans=min(ans,(M-m)*(r-l))
print(ans)


Solve in Python:
There are N barbecue restaurants along a street.
The restaurants are numbered 1 through N from west to east, and the distance between restaurant i and restaurant i+1 is A_i.
Joisino has M tickets, numbered 1 through M.
Every barbecue restaurant offers barbecue meals in exchange for these tickets.
Restaurant i offers a meal of deliciousness B_{i,j} in exchange for ticket j.
Each ticket can only be used once, but any number of tickets can be used at a restaurant.
Joisino wants to have M barbecue meals by starting from a restaurant of her choice, then repeatedly traveling to another barbecue restaurant and using unused tickets at the restaurant at her current location.
Her eventual happiness is calculated by the following formula: "(The total deliciousness of the meals eaten) - (The total distance traveled)".
Find her maximum possible eventual happiness.

-----Constraints-----
 - All input values are integers.
 - 2≤N≤5×10^3
 - 1≤M≤200
 - 1≤A_i≤10^9
 - 1≤B_{i,j}≤10^9

-----Input-----
The input is given from Standard Input in the following format:
N M
A_1 A_2 ... A_{N-1}
B_{1,1} B_{1,2} ... B_{1,M}
B_{2,1} B_{2,2} ... B_{2,M}
:
B_{N,1} B_{N,2} ... B_{N,M}

-----Output-----
Print Joisino's maximum possible eventual happiness.

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

-----Sample Output-----
11

The eventual happiness can be maximized by the following strategy: start from restaurant 1 and use tickets 1 and 3, then move to restaurant 2 and use tickets 2 and 4.

import sys
readline = sys.stdin.readline

N, M = map(int, readline().split())
A = [0] + list(map(int, readline().split()))
for i in range(1, N):
    A[i] += A[i-1]

INF = 10**9+7
B = [list(map(int, readline().split())) for _ in range(N)] + [[INF]*M] + [[0]*M]
right = [[0]*M for _ in range(N)]

for m in range(M):
    L = list(range(N))
    L.sort(key = lambda x: B[x][m])
    RR = list(range(1, N+3))
    LL = list(range(-1, N+1))
    for vn in L:
        vn += 1
        right[vn-1][m] = RR[vn]-1
        RR[LL[vn]] = RR[vn]
        LL[RR[vn]] = LL[vn]

diff = [0]*(N+1)
for m in range(M):
    diff[0] += B[0][m]
    pre = B[0][m]
    for i in range(1, N):
        if B[i][m] > pre:
            diff[i] += B[i][m]-pre
            pre = B[i][m]

offset = 0
ans = 0
for l in range(N):
    offset += diff[l]
    for m in range(M):
        if B[l][m] < B[l-1][m]:
            oldr = right[l-1][m]
            diff[oldr] -= B[oldr][m] - B[l-1][m]
            offset += B[l][m] - B[l-1][m]
            cnt = l
            while cnt < N and right[cnt][m] <= oldr:
                rcm = right[cnt][m]
                diff[rcm] += B[rcm][m] - B[cnt][m]
                cnt = rcm
    ans = max(ans, offset)
    roff = offset
    for r in range(l+1, N):
        roff += diff[r]
        ans = max(ans, roff - (A[r]-A[l]))
        #print(l, r, roff - (A[r] - A[l]))

print(ans)


Solve in Python:
There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

       Each child must have at least one candy.
       Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.

class Solution:
     def candy(self, ratings):
         """
         :type ratings: List[int]
         :rtype: int
         """
         candies = [0] * len(ratings)

         from_left = [1] * len(ratings)
         cur_less_than = 1
         for idx in range(1, len(ratings)):
             if ratings[idx-1] < ratings[idx]:
                 cur_less_than += 1
             else:
                 cur_less_than = 1
             from_left[idx] = cur_less_than

         from_right = [1] * len(ratings)
         cur_less_than = 1
         idx = len(ratings)-2
         while idx >= 0:
             if ratings[idx+1] < ratings[idx]:
                 cur_less_than += 1
             else:
                 cur_less_than = 1
             from_right[idx] = cur_less_than
             idx -= 1

         for idx in range(0, len(ratings)):
             candies[idx] = max(from_left[idx], from_right[idx])

         return sum(candies)


Solve in Python:
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Note:

       If there exists a solution, it is guaranteed to be unique.
       Both input arrays are non-empty and have the same length.
       Each element in the input arrays is a non-negative integer.

Example 1:

Input:
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Output: 3

Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.

Example 2:

Input:
gas  = [2,3,4]
cost = [3,4,3]

Output: -1

Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.

class Solution:
     def canCompleteCircuit(self, gas, cost):
         """
         :type gas: List[int]
         :type cost: List[int]
         :rtype: int
         """
         n = len(gas)

         i = 0
         while i < n:
             total_gas = 0
             j = 0
             while j < n and total_gas >= 0:
                 index = (i + j) % n
                 total_gas += gas[index] - cost[index]
                 j += 1
             if total_gas >= 0:
                 return i
             while i < n and gas[i] - cost[i] >= 0:
                 i += 1
             i += 1

         return -1


Solve in Python:
There are N hills in a row numbered 1 through N from left to right. Each hill has a height; for each valid i, the height of the i-th hill is Hi. Chef is initially on the leftmost hill (hill number 1). He can make an arbitrary number of jumps (including zero) as long as the following conditions are satisfied:

- Chef can only jump from each hill to the next hill, i.e. from the i-th hill, he can jump to the i+1-th hill (if it exists).
- It's always possible to jump to a hill with the same height as the current hill.
- It's possible to jump to a taller hill if it's higher than the current hill by no more than U.
- It's possible to jump to a lower hill if it's lower than the current hill by no more than D.
- Chef can use a parachute and jump to a lower hill regardless of its height (as long as it's lower than the current hill). This jump can only be performed at most once.

Chef would like to move as far right as possible. Determine the index of the rightmost hill Chef can reach.

-----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 three space-separated integers N, U and D.
- The second line contains N space-separated integers H1, H2, ..., HN.

-----Output-----
For each test case, print a single line containing one integer — the index of the rightmost reachable hill.

-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- 1 ≤ U, D ≤ 1,000,000
- 1 ≤ Hi ≤ 1,000,000 for each valid i

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

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

3
5 3 2
2 5 2 6 3
5 2 3
4 4 4 4 4
5 2 7
1 4 3 2 1

Output:

3
5
1

-----Explanation-----
Example case 1: Chef can jump to second hill because it's higher by no more than U=3 than first hill, to jump to third hill Chef has to use parachute
because it's lower than second hill by 3 which is more than D=2, Chef can't jump to fourth hill because it's higher than third hill by 4 which is more than U=3
Example case...

# cook your dish here
for _ in range(int(input())):
 n,u,d = map(int,input().split())
 h = list(map(int,input().split()))
 b = 0
 for i in range(n):
  if i==n-1:
   break
  if h[i+1]>h[i]:
   if h[i+1]-h[i]>u:
    break
  elif h[i+1]<h[i]:
   if h[i]-h[i+1]>d:
    if b==0:
     b=1
    else:
     break
 print(i+1)


Solve in Python:
There are N islands in the sea, enumerated from 1 to N. Each of them is so small that we can consider them as points on a plane. You are given the Cartesian coordinates of all islands. X-axis is directed towards East and Y-axis is directed towards North.
You need to illuminate all the islands. To do this, you can place lighthouses on some of the islands. You can't place more than one lighthouse on any single island. Each lighthouse can light only one of the 4 quadrants: North-Western, North-Eastern, South-Western or South-Eastern. If some island is located on the border of an illuminated quadrant, it is considered to be illuminated as well. Note that this means that a lighthouse always illuminates it's own island as well.
Find the smallest possible number of lighthouses required to illuminate all the islands (say L). Describe their configurations — positions and quadrants illuminated — as well.

-----Input-----
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of islands.
The ith of the following N lines contains two integers Xi and Yi denoting the coordinates of the ith island.

-----Output-----
For each test case, first line of output must contain minimum number of lighthouses required to illuminate all islands, L.
Following L lines must describe configuration of the lighthouses, one configuration per line. Description of a lighthouse configuration consists of the number of the island where the lighthouse is placed, and the direction of the quadrant (NW for North-Western, NE for North-Eastern, SW for South-Western, SE for South-Eastern) illuminated by it, separated by a single space.
If there are many possible placements, output any one of them.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 105
- The sum of N over all test cases doesn't exceed 5*105
- Absolute value of each coordinate doesn't exceed 109
- No two given islands...

class island:
 'number, x, y'
 def __init__(self,x,y,number):
  self.x = x
  self.y = y
  self.number = number

def lighthouses(islands):
 low = high = left = right = islands[0]

 left = min(islands, key = lambda a : a.x)
 right= max(islands, key = lambda a : a.x)
 low = min(islands, key = lambda a : a.y)
 high = max(islands, key = lambda a : a.y)

 if left == low:
  print(1)
  print(str(left.number) + ' NE')
 elif left == high:
  print(1)
  print(str(left.number) + ' SE')
 elif right == low:
  print(1)
  print(str(right.number) + ' NW')
 elif right == high:
  print(1)
  print(str(right.number) + ' SW')
 else:
  islands.remove(left)
  nextleft = min(islands, key = lambda a : a.x)

  if left.y < nextleft.y:
   print(2)
   print(str(left.number) + ' NE')
   print(str(nextleft.number) + ' SE')
  else:
   print(2)
   print(str(left.number) + ' SE')
   print(str(nextleft.number) + ' NE')

T = int(input())
for i in range(T):
 N = int(input())
 islands = []
 for j in range(N):
  x, y = list(map(int, input().split()))
  islands.append(island(x,y,j+1))
 lighthouses(islands)


Solve in Python:
There are N people, conveniently numbered 1 through N.
We want to divide them into some number of groups, under the following two conditions:
 - Every group contains between A and B people, inclusive.
 - Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups.
Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways.
Since the number of these ways can be extremely large, print the count modulo 10^9+7.

-----Constraints-----
 - 1≤N≤10^3
 - 1≤A≤B≤N
 - 1≤C≤D≤N

-----Input-----
The input is given from Standard Input in the following format:
N A B C D

-----Output-----
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.

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

-----Sample Output-----
4

There are four ways to divide the people:
 - (1,2),(3)
 - (1,3),(2)
 - (2,3),(1)
 - (1,2,3)
The following way to divide the people does not count: (1),(2),(3). This is because it only satisfies the first condition and not the second.

mod = 10**9+7

NN = 10**4 # 使うデータによって変える
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, NN + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

N, A, B, C, D = list(map(int, input().split()))

Map = [[] for _ in range(N+1)]
for n in range(1, N+1):
    a = 1
    for _ in range(N+1):
        Map[n].append(a)
        a = a * g2[n] % mod

L = [[] for _ in range(N+1)]
for n in range(A, B+1):
    for c in range(C, D+1):
        if n*c > N:
            continue
        L[n].append(c)

dp = [0]*(N+1)
dp[0] = 1
for n in range(1, N+1):
    for i, c in enumerate(L[n]):
        if i == 0:
            dp2 = dp[:]
        for nn in range(N+1-n*c):
            dp2[nn+n*c] = (dp2[nn+n*c] + dp[nn] * Map[n][c] % mod * Map[c][1] % mod) % mod
        if i == len(L[n])-1:
            dp = dp2

ans = dp[N] * g1[N] % mod
print(ans)


Solve in Python:
There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile.  If it is impossible, return -1.

Example 1:
Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.

Example 2:
Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore.  So the task is impossible.

Example 3:
Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.

Note:

1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100

from functools import lru_cache
import itertools

class Solution:
    def mergeStones(self, stones: List[int], K: int) -> int:
        # dp[i][j] means the minimum cost needed to merge stones[i] ~ stones[j].
        # Time  complexity: O(N^3 / K)
        # Space complexity: O(KN^2)
        n = len(stones)
        if (n - 1) % (K - 1): return -1
        prefix = [0] * (n + 1)
        for i in range(n):
            prefix[i + 1] = prefix[i] + stones[i]

        @lru_cache(None)
        def dp(i, j):
            if j - i + 1 < K: return 0

            res = min(dp(i, mid) + dp(mid + 1, j) for mid in range(i, j, K - 1))

            if (j - i) % (K - 1) == 0:
                res += prefix[j + 1] - prefix[i]

            return res

        return dp(0, n - 1)


Solve in Python:
There are N pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i).
We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|).
You have a peculiar pair of compasses, called Manhattan Compass.
This instrument always points at two of the pinholes.
The two legs of the compass are indistinguishable, thus we do not distinguish the following two states: the state where the compass points at the p-th and q-th pinholes, and the state where it points at the q-th and p-th pinholes.
When the compass points at the p-th and q-th pinholes and d(p,q)=d(p,r), one of the legs can be moved so that the compass will point at the p-th and r-th pinholes.
Initially, the compass points at the a-th and b-th pinholes.
Find the number of the pairs of pinholes that can be pointed by the compass.

-----Constraints-----
 - 2≦N≦10^5
 - 1≦x_i, y_i≦10^9
 - 1≦a < b≦N
 - When i ≠ j, (x_i, y_i) ≠ (x_j, y_j)
 - x_i and y_i are integers.

-----Input-----
The input is given from Standard Input in the following format:
N a b
x_1 y_1
:
x_N y_N

-----Output-----
Print the number of the pairs of pinholes that can be pointed by the compass.

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

-----Sample Output-----
4

Initially, the compass points at the first and second pinholes.
Since d(1,2) = d(1,3), the compass can be moved so that it will point at the first and third pinholes.
Since d(1,3) = d(3,4), the compass can also point at the third and fourth pinholes.
Since d(1,2) = d(2,5), the compass can also point at the second and fifth pinholes.
No other pairs of pinholes can be pointed by the compass, thus the answer is 4.

N, a, b = list(map(int, input().split())); a -= 1; b -= 1
P = []
Q = []
for i in range(N):
    x, y = list(map(int, input().split()))
    P.append((x-y, x+y, i))
    Q.append((x+y, x-y, i))

d = max(abs(P[a][0] - P[b][0]), abs(P[a][1] - P[b][1]))

*parent, = list(range(N))
def root(x):
    if x == parent[x]:
        return x
    y = parent[x] = root(parent[x])
    return y
def unite(x, y):
    px = root(x); py = root(y)
    if px < py:
        parent[py] = px
    else:
        parent[px] = py
C = [0]*N
D = [0]*N

def check(P0, i0, j0):
    return abs(P0[i0][0] - P0[j0][0]) == abs(P0[i0][1] - P0[j0][1])

def solve(P0):
    P = P0[:]
    P.sort()

    s = t = 0; prev = -1
    for i in range(N):
        x, y, i0 = P[i]
        while t < N and P[t][0] < x-d or (P[t][0] == x-d and P[t][1] <= y+d): t += 1
        while s < N and (P[s][0] < x-d or (P[s][0] == x-d and P[s][1] < y-d)): s += 1
        if s < t:
            j0 = P[s][2]
            unite(i0, j0)
            if check(P0, i0, j0):
                D[i0] += 1
            else:
                C[i0] += 1
            if s < t-1:
                j0 = P[t-1][2]
                if check(P0, i0, j0):
                    D[i0] += 1
                    C[i0] += t-s-2
                else:
                    C[i0] += t-s-1
            for j in range(max(prev, s), t-1):
                unite(P[j][2], P[j+1][2])
            prev = t-1
solve(P)
solve(Q)

S = T = 0
r = root(a)
for i in range(N):
    if root(i) == r:
        S += C[i]; T += D[i]
print((S + T//2))


Solve in Python:
There are N robots and M exits on a number line.
The N + M coordinates of these are all integers and all distinct.
For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i.
Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j.
Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously:
 - Increment the coordinates of all the robots on the number line by 1.
 - Decrement the coordinates of all the robots on the number line by 1.
Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit.
Snuke will continue performing operations until all the robots disappear.
When all the robots disappear, how many combinations of exits can be used by the robots?
Find the count modulo 10^9 + 7.
Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations.

-----Constraints-----
 - 1 \leq N, M \leq 10^5
 - 1 \leq x_1 < x_2 < ... < x_N \leq 10^9
 - 1 \leq y_1 < y_2 < ... < y_M \leq 10^9
 - All given coordinates are integers.
 - All given coordinates are distinct.

-----Input-----
Input is given from Standard Input in the following format:
N M
x_1 x_2 ... x_N
y_1 y_2 ... y_M

-----Output-----
Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7.

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

-----Sample Output-----
3

The i-th robot from the left will be called Robot i, and the j-th exit from the left will be called Exit j.
There are three possible combinations of exits (the exit used by Robot 1, the exit used by Robot 2) as follows:
 - (Exit 1, Exit 1)
 - (Exit 1, Exit 2)
 - (Exit 2, Exit 2)

from bisect import bisect
from collections import defaultdict

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
        self.depth = n.bit_length()

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

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

    def debug_print(self):
        for i in range(1, self.size + 1):
            j = (i & -i).bit_length()
            print(('  ' * j, self.tree[i]))

    def lower_bound(self, x):
        sum_ = 0
        pos = 0
        for i in range(self.depth, -1, -1):
            k = pos + (1 << i)
            if k <= self.size and sum_ + self.tree[k] < x:
                sum_ += self.tree[k]
                pos += 1 << i
        return pos + 1, sum_

n, m = list(map(int, input().split()))
xxx = list(map(int, input().split()))
yyy = list(map(int, input().split()))
ab = defaultdict(set)
coordinates = set()

for x in xxx:
    if x < yyy[0] or yyy[-1] < x:
        continue
    i = bisect(yyy, x)
    a = x - yyy[i - 1]
    b = yyy[i] - x
    ab[a].add(b)
    coordinates.add(b)

# Bitのindexは1から始まるように作っているが、"0"を取れるようにするため、全体を1ずらす
cor_dict = {b: i for i, b in enumerate(sorted(coordinates), start=2)}
cdg = cor_dict.get
bit = Bit(len(coordinates) + 1)
bit.add(1, 1)

for a in sorted(ab):
    bbb = sorted(map(cdg, ab[a]), reverse=True)
    for b in bbb:
        bit.add(b, bit.sum(b - 1))

print((bit.sum(bit.size) % (10 ** 9 + 7)))


Solve in Python:
There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j] = v opens the room with number v.
Initially, all the rooms start locked (except for room 0).
You can walk back and forth between rooms freely.
Return true if and only if you can enter every room.

Example 1:
Input: [[1],[2],[3],[]]
Output: true
Explanation:
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3.  Since we were able to go to every room, we return true.

Example 2:
Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.

Note:

1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
The number of keys in all rooms combined is at most 3000.

import numpy as np
class Solution(object):
    def canVisitAllRooms(self, rooms):
        seenRooms = np.zeros(len(rooms), dtype = bool)
        stackKeys = [0]
        while(len(stackKeys)!=0):
            curr = stackKeys.pop()
            if not seenRooms[curr]:
                seenRooms[curr] = True
                for key in rooms[curr]:
                    stackKeys.append(key)
        return True if all(seenRooms) else False


Solve in Python:
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:

Input:
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2.

Example 2:

Input:
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.

Note:

N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.

class Solution:
     def findCircleNum(self, M):
         """
         :type M: List[List[int]]
         :rtype: int
         """
         N = len(M)
         seen = set()

         def dfs(i):
             for j, flag in enumerate(M[i]):
                 if flag and j not in seen:
                     seen.add(j)
                     dfs(j)

         ans = 0
         for i in range(N):
             if i not in seen:
                 dfs(i)
                 ans += 1
         return ans


Solve in Python:
There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.
Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:
 - Move: When at town i (i < N), move to town i + 1.
 - Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.
For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)
During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.
Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.
Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

-----Constraints-----
 - 1 ≦ N ≦ 10^5
 - 1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)
 - A_i are distinct.
 - 2 ≦ T ≦ 10^9
 - In the initial state, Takahashi's expected profit is at least 1 yen.

-----Input-----
The input is given...

#!/usr/bin/env pypy3

import collections

INF = 10 ** 10

def solve(n, t, xs):
    trades = collections.Counter()
    maxs = [INF for _ in range(n)]
    maxs[n - 1] = xs[n - 1]
    for i in range(n - 1)[::-1]:
        maxs[i] = max(xs[i], maxs[i + 1])
    for i in range(n):
        delta = maxs[i] - xs[i]
        if delta > 0:
            trades[delta] += 1
    max_delta = max(trades.keys())
    return trades[max_delta]

def main():
    n, t = list(map(int, input().split()))
    xs = list(map(int, input().split()))
    print((solve(n, t, xs)))

def __starting_point():
    main()

__starting_point()


Solve in Python:
There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:
 - Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.
 - Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.
Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

-----Constraints-----
 - All input values are integers.
 - 2≤N≤10^5
 - 1≤X_i≤10^9
 - For all i(1≤i≤N-1), X_i<X_{i+1}.
 - 1≤A≤10^9
 - 1≤B≤10^9

-----Input-----
The input is given from Standard Input in the following format:
N A B
X_1 X_2 ... X_N

-----Output-----
Print the minimum possible total increase of your fatigue level when you visit all the towns.

-----Sample Input-----
4 2 5
1 2 5 7

-----Sample Output-----
11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

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

ans = 0
for i in range(n-1):
    ans += min((xlist[i+1]-xlist[i])*a, b)

print(ans)


Solve in Python:
There are N workers.  The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group.  When hiring a group of K workers, we must pay them according to the following rules:

Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
Every worker in the paid group must be paid at least their minimum wage expectation.

Return the least amount of money needed to form a paid group satisfying the above conditions.

Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.

Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.

Note:

1 <= K <= N <= 10000, where N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
Answers within 10^-5 of the correct answer will be considered correct.

import heapq
class Solution:
    def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
        n_workers = len(wage)
        pairs = [None]*n_workers # (quality, ratio)
        for i in range(n_workers):
            pairs[i] = (quality[i], wage[i]/quality[i])

        pairs = sorted(pairs, key=lambda x: (x[1])) # sort dec by ratio

        # ...incorrect solution...
        # max_q = pairs[i:i+K]
        # for i in range(n_workers-K+1):
            # min_cost = min(min_cost, self.cost(pairs[i:i+K]))

        sum_q = sum([p[0] for p in pairs[0:K]])
        maxheap_q = [-p[0] for p in pairs[0:K]] # use minus to create max heap
        heapq.heapify(maxheap_q)
        min_cost = sum_q * pairs[K-1][1]

        for i in range(K, n_workers):
            sum_q = sum_q - (-heapq.heappop(maxheap_q)) + pairs[i][0]
            min_cost = min(min_cost, sum_q * pairs[i][1])
            heapq.heappush(maxheap_q, -pairs[i][0]) # push minus value to max heap

        return min_cost


Solve in Python:
There are a **n** balls numbered from 0 to **n-1** (0,1,2,3,etc). Most of them have the same weight, but one is heavier. Your task is to find it.

Your function will receive two arguments - a `scales` object, and a ball count. The `scales` object has only one method:

```python
    get_weight(left, right)
```

where `left` and `right` are arrays of numbers of balls to put on left and right pan respectively.

If the method returns `-1` - left pan is heavier

If the method returns `1` - right pan is heavier

If the method returns `0` - both pans weigh the same

So what makes this the "ubermaster" version of this kata? First, it's not restricted to 8 balls as in the previous versions - your solution has to work for 8-500 balls.

Second, you can't use the scale any more than mathematically necessary. Here's a chart:

    ball count | uses
    -----------------
           0-9 |    2
         10-27 |    3
         28-81 |    4
        82-243 |    5
       244-500 |    6

Too hard? Try lower levels by [tiriana](http://www.codewars.com/users/tiriana):

* [novice](http://www.codewars.com/kata/544047f0cf362503e000036e)
* [conqueror](http://www.codewars.com/kata/54404a06cf36258b08000364)
* [master](http://www.codewars.com/kata/find-heavy-ball-level-master)

def split(scales,next):
    if len(next)==1:
        return next[0]
    elif len(next) ==2:
        w = scales.get_weight([next[0]],[next[1]])
        if w==1:
            return next[1]
        else:
            return next[0]
    elif len(next)==3:
        w = scales.get_weight([next[0]],[next[1]])
        if w==0:
            return next[2]
        elif w==-1:
            return next[0]
        else:
            return next[1]

    lock_size = (len(next)+1)//3

    l  =next[:lock_size]
    r = next[lock_size:lock_size+ lock_size]
    f = next[lock_size+ lock_size:]

    return find(scales,f,l,r)

def find(scales,free,first,second):

    w = scales.get_weight(first,second)

    if w ==0:
        return split(scales,free)
    elif w==-1:
        return split(scales,first)
    elif w==1:
        return split(scales,second)

def find_ball(scales, ball_count):
    next = list(range(ball_count))
    return split(scales,next)


Solve in Python:
There are a lot of problems related to the shortest paths. Nevertheless, there are not much problems, related to the shortest paths in average.
Consider a directed graph G, consisting of N nodes and M edges. Consider a walk from the node A to the node B in this graph. The average length of this walk will be total sum of weight of its' edges divided by number of edges. Every edge counts as many times as it appears in this path.
Now, your problem is quite simple. For the given graph and two given nodes, find out the shortest average length of the walk between these nodes. Please note, that the length of the walk need not to be finite, but average walk length will be.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a pair of space-separated integers N and M denoting the number of nodes and the number of edges in the graph.
Each of the following M lines contains a triple of space-separated integers Xi Yi Zi, denoting the arc, connecting the node Xi to the node Yi (but not vice-versa!) having the weight of Zi.
The next line contains a pair of space separated integers A and B, denoting the first and the last node of the path.

-----Output-----
For each test case, output a single line containing the length of the shortest path in average.
If there is no path at all, output just -1 on the corresponding line of the output.

-----Constraints-----
- 1 ≤ N ≤ 500
- 1 ≤ M ≤ 1000
- A is not equal to B
- 1 ≤ A, B, Xi, Yi ≤ N
- 1 ≤ Zi ≤ 100
- There are no self-loops and multiple edges in the graph.
- 1 ≤ sum of N over all test cases ≤ 10000
- 1 ≤ sum of M over all test cases ≤ 20000

-----Subtasks-----
- Subtask #1 (45 points): 1 ≤ N ≤ 10, 1 ≤ M ≤ 20; Your answer will be considered correct in case it has an absolute or relative error of no more than 10-2.
- Subtask #2 (55 points): no additional constraints; Your answer will be considered correct in case it has an absolute or relative error...

from collections import defaultdict
import copy
#def dfs(l,r,dct):
def dfs(l,r,dct):
 visit=[0 for i in range(n+1)]
 arr=[l]
 while(arr):
  node=arr.pop()
  if node==r:return True
  visit[node]=1
  for lnk in dct[node]:
   if not visit[lnk]:
    arr.append(lnk)
 return False

def ok(mid,cst):
 for i,j in edges:
  cst[i][j]-=mid

 d=[10**9]*(n+1)
 d[l]=0
 for _ in range(n-1):
  for i,j in edges:
   d[j]=min(d[j],d[i]+cst[i][j])

 if d[r]<=0:return 1
 for i,j in edges:
  if d[j]>d[i]+cst[i][j] and dfs(l,i,dct) and dfs(j,r,dct):
   return 1
 return 0

for _ in range(int(input())):
 n,m=map(int,input().split())
 dct=defaultdict(list)

 cost=[[1000 for i in range(n+1)] for j in range(n+1)]
 edges=[]
 for i in range(m):
  a,b,w=map(int,input().split())
  edges.append([a,b])
  dct[a].append(b)
  cost[a][b]=min(cost[a][b],w)

 l,r=map(int,input().split())
 if not dfs(l,r,dct):
  print(-1)
  continue
 #print(cost)
 lo=1
 hi=101
 for i in range(100):
  cst=copy.deepcopy(cost)
  mid=(lo+hi)/2
  if ok(mid,cst):hi=mid-1
  else:lo=mid+1
 print("%.7f"%mid)


Solve in Python:
There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example 1:

Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
             course 0. So the correct course order is [0,1] .

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both
             courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
             So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .

Note:

       The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
       You may assume that there are no duplicate edges in the input prerequisites.

class Solution:
     def findOrder(self, numCourses, prerequisites):
         """
         :type numCourses: int
         :type prerequisites: List[List[int]]
         :rtype: List[int]
         """
         nums = [[] for _ in range(numCourses)]
         du = [0] * numCourses
         for end, start in prerequisites:
             nums[start].append(end)
             du[end] += 1
         result = []
         def dfs(idx):
             du[idx] -= 1
             result.append(idx)
             for i in nums[idx]:
                 du[i] -= 1
                 if du[i] == 0:
                     dfs(i)
         for i in range(numCourses):
             if du[i] == 0:
                 dfs(i)
         if len(result) == numCourses:
             return result
         return []


Solve in Python:
There are just some things you can't do on television. In this case, you've just come back from having a "delicious" Barth burger and you're set to give an interview. The Barth burger has made you queezy, and you've forgotten some of the import rules of the "You Can't Do That on Television" set.

If you say any of the following words a large bucket of "water" will be dumped on you:
"water", "wet", "wash"
This is true for any form of those words, like "washing", "watered", etc.

If you say any of the following phrases you will be doused in "slime":
"I don't know", "slime"

If you say both in one sentence, a combination of water and slime, "sludge", will be dumped on you.

Write a function, bucketOf(str), that takes a string and determines what will be dumped on your head. If you haven't said anything you shouldn't have, the bucket should be filled with "air". The words should be tested regardless of case.

Examples:

Check out my other 80's Kids Katas:

80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9: Down in Fraggle Rock
80's Kids #10: Captain Planet

import re
bucket_of = lambda said: \
    ({ 0: 'air', 1: 'water', 2: 'slime', 3: 'sludge' }) \
    [bool(re.search('(?i)(water|wet|wash)', said)) + bool(re.search('(?i)(I don\'t know|slime)', said)) * 2]


Solve in Python:
There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (x_{i}, y_{i}). All sensors are located at distinct points strictly inside the rectangle.

Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.

At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of $\sqrt{2}$ meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start.

When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.

For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print  - 1 for such sensors.

-----Input-----

The first line of the input contains three integers n, m and k (2 ≤ n, m ≤ 100 000, 1 ≤ k ≤ 100 000) — lengths of the room's walls and the number of sensors.

Each of the following k lines contains two integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n - 1, 1 ≤ y_{i} ≤ m - 1) — coordinates of the sensors. It's guaranteed that no two sensors are located at the same point.

-----Output-----

Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or  - 1 if this will never happen.

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

Output
1
-1
-1
2

Input
3 4 6
1 1
2 1
1 2
2 2
1 3
2 3

Output
1
-1
-1
2
5
-1

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

Output
13
2
9
5
-1

-----Note-----

In the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds. [Image]

In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2,...

n, m, k = list(map(int,input().split()))
dm, dp = {}, {}
vis = {}
sensors = []
border = set()
for el in [(0, m), (n, 0), (0, 0), (n, m)]:
    border.add(el)

for _ in range(k):
    x, y = list(map(int, input().split()))
    if not (x - y) in dm:
        dm[x - y] = []
    dm[x - y].append((x, y))
    if not (x + y) in dp:
        dp[x + y] = []
    dp[x + y].append((x, y))
    vis[(x, y)] = -1
    sensors.append((x,y))

x, y = 0, 0
time = 0
move = (1,1)
while True:
    if move == (1,1):
        v = min(n - x, m - y)
        nxt = (x + v, y + v)
        if nxt[0] == n:
            move = (-1, 1)
        else:
            move = (1, -1)
        if (x - y) in dm:
            for sensor in dm[x - y]:
                if vis[sensor] == -1:
                    #print('doing', sensor)
                    vis[sensor] = time + sensor[0] - x
        time += v

    elif move == (-1,-1):
        v = min(x, y)
        nxt = (x - v, y - v)
        if nxt[0] == 0:
            move = (1, -1)
        else:
            move = (-1, 1)
        if (x - y) in dm:
            for sensor in dm[x - y]:
                if vis[sensor] == -1:
                    #print('doing', sensor)
                    vis[sensor] = time + x - sensor[0]
        time += v

    elif move == (-1,1):
        v = min(x, m - y)
        nxt = (x - v, y + v)
        if nxt[0] == 0:
            move = (1, 1)
        else:
            move = (-1, -1)
        if (x + y) in dp:
            for sensor in dp[x + y]:
                if vis[sensor] == -1:
                    #print('doing', sensor)
                    vis[sensor] = time + x - sensor[0]
        time += v

    else:
        v = min(n - x, y)
        nxt = (x + v, y - v)
        if nxt[0] == n:
            move = (-1, -1)
        else:
            move = (1, 1)
        if (x + y) in dp:
            for sensor in dp[x + y]:
                if vis[sensor] == -1:
                    #print('doing', sensor)
                    vis[sensor] = time + sensor[0] - x
        time += v

    if nxt in border:
     ...


Solve in Python:
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.

Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that:   this list contains all Jinotega's flights in this year (in arbitrary order),  Jinotega has only flown from his hometown to a snooker contest and back,  after each competition Jinotega flies back home (though they may attend a competition in one place several times),  and finally, at the beginning of the year Jinotega was at home.

Please help them to determine Jinotega's location!

-----Input-----

In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≤ n ≤ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport.

It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement.

-----Output-----

If Jinotega is now at home, print "home" (without quotes), otherwise print "contest".

-----Examples-----
Input
4
SVO
SVO->CDG
LHR->SVO
SVO->LHR
CDG->SVO

Output
home

Input
3
SVO
SVO->HKT
HKT->SVO
SVO->RAP

Output
contest

-----Note-----

In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list.

n = int(input())
s = input()

departures, arrivals = 0, 0

for _ in range(n):
    s1, s2 = input().split('->')
    if s1 == s:
        departures += 1
    if s2 == s:
        arrivals += 1

if departures != arrivals:
    print("contest")
else:
    print("home")


Solve in Python:
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).

You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).

You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.

-----Input-----

The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000).

The next m lines will contain the description of the known relationships. The i-th line will contain three integers a_{i}, b_{i}, c_{i}. If c_{i} is 1, then a_{i} and b_{i} are in love, otherwise, they hate each other (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}, $c_{i} \in \{0,1 \}$).

Each pair of people will be described no more than once.

-----Output-----

Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.

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

Output
4

Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0

Output
1

Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1

Output
0

-----Note-----

In the first sample, the four ways are to:   Make everyone love each other  Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).

In the...

class DisjointSet(object):
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
        self.num = n  # number of disjoint sets

    def union(self, x, y):
        self._link(self.find_set(x), self.find_set(y))

    def _link(self, x, y):
        if x == y:
            return
        self.num -= 1
        if self.rank[x] > self.rank[y]:
            self.parent[y] = x
        else:
            self.parent[x] = y
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

    def find_set(self, x):
        xp = self.parent[x]
        if xp != x:
            self.parent[x] = self.find_set(xp)
        return self.parent[x]

def solve():
    n, m = list(map(int, input().split()))
    ds = DisjointSet(n * 2)
    for i in range(m):
        a, b, c = list(map(int, input().split()))
        a -= 1
        b -= 1
        aA = a * 2
        aB = aA + 1
        bA = b * 2
        bB = bA + 1
        if c == 0:
            if ds.find_set(aA) == ds.find_set(bA):
                return 0
            ds.union(aA, bB)
            ds.union(aB, bA)
        else:
            if ds.find_set(aA) == ds.find_set(bB):
                return 0
            ds.union(aA, bA)
            ds.union(aB, bB)
    return pow(2, (ds.num // 2) - 1, 10**9 + 7)

print(solve())