I found an interesting problem on https://codeforces.com/problemset/problem/734/E:
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.

There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).

To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree [Image]

and apply operation paint(3) to get the following: [Image]

Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.

The second line contains n integers color_{i} (0 ≤ color_{i} ≤ 1) — colors of the vertices. color_{i} = 0 means that the i-th vertex is initially painted white, while color_{i} = 1 means it's initially painted black.

Then follow n - 1 line, each of them contains a pair of integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (u_{i}, v_{i}) are distinct, i.e. there are no multiple edges.

-----Output-----

Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.

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

Output
2

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

Output
0

-----Note-----

In the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.

In the second sample, the tree is already white, so there is no need to apply any...

I tried it in Python, but could not do it. Can you solve it?

f = lambda: map(int, input().split())
s, n = 0, int(input())

g = [set() for i in range(n + 1)]
c = [0] + list(f())
d = [0] * (n + 1)

for j in range(n - 1):
    a, b = f()
    g[a].add(b)
    g[b].add(a)

p = [q for q, t in enumerate(g) if len(t) == 1]
while p:
    a = p.pop()
    if not g[a]: break
    b = g[a].pop()
    g[b].remove(a)
    if c[a] - c[b]: d[a] += 1
    s = max(s, d[b] + d[a])
    d[b] = max(d[b], d[a])
    if len(g[b]) == 1: p.append(b)

print(s + 1 >> 1)


I found an interesting problem on https://codeforces.com/problemset/problem/735/A:
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.

Ostap knows that grasshopper is able to jump to any empty cell that is exactly k cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if k = 1 the grasshopper can jump to a neighboring cell only, and if k = 2 the grasshopper can jump over a single cell.

Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.

-----Input-----

The first line of the input contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1) — the number of cells in the line and the length of one grasshopper's jump.

The second line contains a string of length n consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once.

-----Output-----

If there exists a sequence of jumps (each jump of length k), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes).

-----Examples-----
Input
5 2
#G#T#

Output
YES

Input
6 1
T....G

Output
YES

Input
7 3
T..#..G

Output
NO

Input
6 2
..GT..

Output
NO

-----Note-----

In the first sample, the grasshopper can make one jump to the right in...

I tried it in Python, but could not do it. Can you solve it?

def main():
    n, k = list(map(int, input().split()))
    a = input()
    l = 0
    r = 0
    for i in range(n):
        if (a[i] == 'G'):
            l = i
        elif (a[i] == 'T'):
            r = i
    if (l < r):
        if ((r - l) % k == 0):
            for i in range(l, r + 1, k):
                if (a[i] == '#'):
                    print("NO")
                    return
            print("YES")
        else:
            print("NO")
    else:
        if ((r - l) % k == 0):
            for i in range(r, l + 1, k):
                if (a[i] == '#'):
                    print("NO")
                    return
            print("YES")
        else:
            print("NO")
main()


I found an interesting problem on https://codeforces.com/problemset/problem/735/B:
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to a_{i}. Authorities plan to build two cities, first for n_1 people and second for n_2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n_1 settle in the first city and then some subset of size n_2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.

To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth a_{i} among all its residents divided by the number of them (n_1 or n_2 depending on the city). The division should be done in real numbers without any rounding.

Please, help authorities find the optimal way to pick residents for two cities.

-----Input-----

The first line of the input contains three integers n, n_1 and n_2 (1 ≤ n, n_1, n_2 ≤ 100 000, n_1 + n_2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.

-----Output-----

Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq...

I tried it in Python, but could not do it. Can you solve it?

from sys import stdin

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

a = sorted(map(int, stdin.readline().split()), key=lambda x: -x)

mn = min(n1, n2)
mx = max(n1, n2)

# print(mn, mx)
# print(a)
# print(sum(a[:mn]) / mn, sum(a[mn:mn+mx]) / mx)
print((sum(a[:mn]) / mn) + (sum(a[mn:mn+mx]) / mx))


I found an interesting problem on https://codeforces.com/problemset/problem/735/C:
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.

Organizers are still arranging tournament grid (i.e. the order games will happen and who is going to play with whom) but they have already fixed one rule: two players can play against each other only if the number of games one of them has already played differs by no more than one from the number of games the other one has already played. Of course, both players had to win all their games in order to continue participating in the tournament.

Tournament hasn't started yet so the audience is a bit bored. Ostap decided to find out what is the maximum number of games the winner of the tournament can take part in (assuming the rule above is used). However, it is unlikely he can deal with this problem without your help.

-----Input-----

The only line of the input contains a single integer n (2 ≤ n ≤ 10^18) — the number of players to participate in the tournament.

-----Output-----

Print the maximum number of games in which the winner of the tournament can take part.

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

Output
1

Input
3

Output
2

Input
4

Output
2

Input
10

Output
4

-----Note-----

In all samples we consider that player number 1 is the winner.

In the first sample, there would be only one game so the answer is 1.

In the second sample, player 1 can consequently beat players 2 and 3.

In the third sample, player 1 can't play with each other player as after he plays with players 2 and 3 he can't play against player 4, as he has 0 games played, while player 1 already played 2. Thus, the answer is 2 and to achieve we make pairs (1, 2) and (3, 4) and then clash the winners.

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/735/D:
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he needs to pay 5 and if n = 2 he pays only 1 burle.

As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial n in several parts n_1 + n_2 + ... + n_{k} = n (here k is arbitrary, even k = 1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition n_{i} ≥ 2 should hold for all i from 1 to k.

Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split n in parts.

-----Input-----

The first line of the input contains a single integer n (2 ≤ n ≤ 2·10^9) — the total year income of mr. Funt.

-----Output-----

Print one integer — minimum possible number of burles that mr. Funt has to pay as a tax.

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

Output
2

Input
27

Output
3

I tried it in Python, but could not do it. Can you solve it?

import math

def isprime(n):
    if n == 2:
        return True

    sq = math.ceil(n ** 0.5) + 1
    for i in range(2, sq):
        if n % i == 0:
            return False
    return True

def solve(n):
    if isprime(n):
        return 1
    if n%2 == 0:
        return 2
    if isprime(n - 2):
        return 2
    return 3

n = int(input())
print(solve(n))


I found an interesting problem on https://codeforces.com/problemset/problem/735/E:
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.

Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.

As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 10^9 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ min(20, n - 1)) — the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.

Each of the next n - 1 lines contain two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.

-----Output-----

Print one integer — the remainder of division of the number of ways to paint the tree by 1 000 000 007 (10^9 + 7).

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

Output
1

Input
2 1
1 2

Output
3

Input
4 1
1 2
2 3
3 4

Output
9

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

Output
91

-----Note-----

In the first sample, Ostap has to paint both vertices black.

In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.

In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}.

I tried it in Python, but could not do it. Can you solve it?

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

edge_to = [0 for i in range(n*2+1)]
edge_next = [0 for i in range(n*2+1)]
son = [0 for i in range(n+1)]

def add_edge(u,v):
    nonlocal  edge_next,edge_to,son,tot;
    tot += 1;   edge_to[tot] = v;  edge_next[tot] = son[u];  son[u] = tot;
tot = 0;    MOD = 10**9+7
dp = [[0]*(m*2+2) for i in range(n+1)]

def dp_tree(x,fa):
    nonlocal  edge_next,edge_to,m,son,dp;
    dp[x][0]= 1;    dp[x][m+1] = 1;
    f = [0 for i in range(m*2+2)]
    i = son[x]
    while (i):
        f = [0 for w in range(m*2+2)]
        to = edge_to[i]
        i = edge_next[i]
        if (to == fa): continue;
        dp_tree(to,x)
        for j in range(2*m+2):
            for k in range(2*m+1):
                if (j+k <= 2*m):    f[min(j,k+1)] += (dp[x][j]*dp[to][k])%MOD; f[min(j,k+1)] %= MOD;
                else : f[max(j,k+1)] += (dp[x][j]*dp[to][k])%MOD;   f[max(j,k+1)] %= MOD;
        dp[x] = f

for i in range(n-1):
    u,v = map(int,input().split())
    add_edge(u,v);  add_edge(v,u);

dp_tree(1,-1)
res = 0
for i in range(m+1):
    res += dp[1][i];
    res %= MOD;
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/739/A:
Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special.

Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers l_{i} and r_{i}, and its elements are a[l_{i}], a[l_{i} + 1], ..., a[r_{i}].

Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible.

You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.

The mex of a set S is a minimum possible non-negative integer that is not in S.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5).

The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n), that describe the subarray a[l_{i}], a[l_{i} + 1], ..., a[r_{i}].

-----Output-----

In the first line print single integer — the maximum possible minimum mex.

In the second line print n integers — the array a. All the elements in a should be between 0 and 10^9.

It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 10^9.

If there are multiple solutions, print any of them.

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

Output
2
1 0 2 1 0

Input
4 2
1 4
2 4

Output
3
5 2 0 1

-----Note-----

The first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2.

I tried it in Python, but could not do it. Can you solve it?

f=lambda : list(map(int,input().split()))
n,m=f()
lr=lambda x: x[1]-x[0]+1
sq=min(lr(f()) for _ in range(m))
print(sq)
x=' '.join([str(i%sq) for i in range(n)])
print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/739/B:
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote a_{i}. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).

Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.

The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ a_{u}.

Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 2·10^5).

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the integers written in the vertices.

The next (n - 1) lines contain two integers each. The i-th of these lines contains integers p_{i} and w_{i} (1 ≤ p_{i} ≤ n, 1 ≤ w_{i} ≤ 10^9) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between p_{i} and (i + 1).

It is guaranteed that the given graph is a tree.

-----Output-----

Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.

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

Output
1 0 1 0 0

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

Output
4 3 2 1 0

-----Note-----

In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).

I tried it in Python, but could not do it. Can you solve it?

import sys
import threading
from bisect import bisect_left

n   = int(input())
a   = list(map(int, input().split()))
e   = {}
g   = [[] for i in range(n)]
d   = [0]*(n+5)
ans = [0]*n
p   = [0]*(n+5)

for i in range(n-1):
        c, w = map(int, input().split())
        c-= 1
        g[c].append(i+1)
        e[i+1] = w

def dfs(i, h):
    nonlocal ans, a, e, g, d, p
    p[h]=0
    for j in g[i]:
        d[h+1] = d[h]+e[j]
        dfs(j, h+1)
    x = bisect_left(d, d[h]-a[i], 0, h+1)
    #print(x-1, i, h, d[h], d[h], a[i])
    if x>=0:
        p[x-1]-=1
    p[h-1]+=p[h]+1
    ans[i]=p[h]

def solve():
    nonlocal ans
    dfs(0, 0)
    print(' '.join(map(str, ans)))

max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()


I found an interesting problem on https://codeforces.com/problemset/problem/740/A:
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of three copybooks for c rubles. Alyona already has n copybooks.

What is the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.

-----Input-----

The only line contains 4 integers n, a, b, c (1 ≤ n, a, b, c ≤ 10^9).

-----Output-----

Print the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4.

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

Output
3

Input
6 2 1 1

Output
1

Input
4 4 4 4

Output
0

Input
999999999 1000000000 1000000000 1000000000

Output
1000000000

-----Note-----

In the first example Alyona can buy 3 packs of 1 copybook for 3a = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.

In the second example Alyuna can buy a pack of 2 copybooks for b = 1 ruble. She will have 8 copybooks in total.

In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.

In the fourth example Alyona should buy one pack of one copybook.

I tried it in Python, but could not do it. Can you solve it?

from math import *
from sys import *
from queue import *
from decimal import *

n,a,b,c=(int(z) for z in input().split())
if(n%4==0):
  print(0)
elif(n%4==1):
  print(min(3*a,a+b,c))
elif(n%4==2):
  print(min(2*a,b,2*c))
else:
  print(min(a,3*c,b+c))


I found an interesting problem on https://codeforces.com/problemset/problem/740/B:
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is a_{i}. The mood can be positive, zero or negative.

Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.

For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,  - 2, 1, 3,  - 4. Suppose the mother suggested subarrays (1,  - 2), (3,  - 4), (1, 3), (1,  - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:   the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,  the second flower adds ( - 2)·1 =  - 2, because he is in one of chosen subarrays,  the third flower adds 1·2 = 2, because he is in two of chosen subarrays,  the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,  the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays.

Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!

Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother.

The second line contains the flowers moods — n integers a_1, a_2, ..., a_{n} ( - 100 ≤ a_{i} ≤ 100).

The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) denoting the subarray a[l_{i}], a[l_{i} + 1], ..., a[r_{i}].

Each subarray can encounter more than...

I tried it in Python, but could not do it. Can you solve it?

n, m = list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
pr = [0 for i in range(len(a))]
for i in range(1, len(a)):
    pr[i] = pr[i - 1] + a[i]

ans = 0
for i in range(m):
    l, r = list(map(int, input().split()))
    cur = pr[r] - pr[l - 1]
    if cur >= 0:
        ans += cur

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/741/A:
As you have noticed, there are lovely girls in Arpa’s land.

People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crush_{i}. [Image]

Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.

The game consists of rounds. Assume person x wants to start a round, he calls crush_{x} and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crush_{x} calls crush_{crush}_{x} and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.

Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.

Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crush_{i} = i).

-----Input-----

The first line of input contains integer n (1 ≤ n ≤ 100) — the number of people in Arpa's land.

The second line contains n integers, i-th of them is crush_{i} (1 ≤ crush_{i} ≤ n) — the number of i-th person's crush.

-----Output-----

If there is no t satisfying the condition, print -1. Otherwise print such smallest t.

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

Output
3

Input
4
4 4 4 4

Output
-1

Input
4
2 1 4 3

Output
1

-----Note-----

In the first sample suppose t = 3.

If the first person starts some round:

The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.

The process is...

I tried it in Python, but could not do it. Can you solve it?

def lcm(a, b):
    sum = a + b
    large = a if a > b else b
    small = sum - large
    for i in range(1, small + 1):
        if (large * i) % small == 0:
          return large * i
    return None
            # dfs

n = int(input())
crush = list(map(int, input().split(" ")))
# crush = input().split(" ")
visited = [False] * n
graph_len = []

if sum(crush) != (n * (n + 1)) / 2:
    # not all nodes have incoming edges
    print('-1')
else:
    for i in range(n):
        if visited[i]:
            # visited nodes
            # print('visited already', i)
            continue
        idx = i
        len1 = 0
        while not visited[idx]:
            # not visited nodes
            # print('idx visiting', idx, crush[idx] - 1)
            visited[idx] = True
            idx = crush[idx] - 1  # convert values to zero index
            len1 += 1  # self loops 1. two node loop check
        len1 = (int)(len1/2) if len1%2 == 0 else len1
        if len1 not in graph_len:
            # we ll go for lcm. no point in having duplicates
            graph_len.append(len1)

# find lcm of elements in graph_len
    # print(graph_len)
    n1 = graph_len[0]
    for i in range(1, len(graph_len)):
        n2 = graph_len[i]
        n1 = lcm(n1, n2)
        # print('n1->', n1)
    print(n1)


I found an interesting problem on https://codeforces.com/problemset/problem/741/C:
Note that girls in Arpa’s land are really attractive.

Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the a_{i}-th chair, and his girlfriend, sitting on the b_{i}-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.

 [Image]

There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:   Each person had exactly one type of food,  No boy had the same type of food as his girlfriend,  Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive.

Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.

-----Input-----

The first line contains an integer n (1  ≤  n  ≤  10^5) — the number of pairs of guests.

The i-th of the next n lines contains a pair of integers a_{i} and b_{i} (1  ≤ a_{i}, b_{i} ≤  2n) — the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.

-----Output-----

If there is no solution, print -1.

Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.

If there are multiple solutions, print any of them.

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

Output
1 2
2 1
1 2

I tried it in Python, but could not do it. Can you solve it?

import sys

def solve():
    n = int(input())
    partner = [0]*(2*n)
    pacani = []
    for line in sys.stdin:
        pacan, telka = [int(x) - 1 for x in line.split()]
        partner[pacan] = telka
        partner[telka] = pacan
        pacani.append(pacan)

    khavka = [None]*(2*n)
    for i in range(2*n):
        while khavka[i] is None:
            khavka[i] = 1
            khavka[i^1] = 2
            i = partner[i^1]

    for pacan in pacani:
        print(khavka[pacan], khavka[partner[pacan]])

solve()


I found an interesting problem on https://codeforces.com/problemset/problem/742/A:
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.

Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378^{n}.

 [Image]

Mehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.

-----Input-----

The single line of input contains one integer n (0  ≤  n  ≤  10^9).

-----Output-----

Print single integer — the last digit of 1378^{n}.

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

Output
8
Input
2

Output
4

-----Note-----

In the first example, last digit of 1378^1 = 1378 is 8.

In the second example, last digit of 1378^2 = 1378·1378 = 1898884 is 4.

I tried it in Python, but could not do it. Can you solve it?

def __starting_point():
	n, = map(int, input().split())
	if n == 0:
		print(1)
	elif n % 4 == 0:
		print(6)
	elif n % 4 == 1:
		print(8)
	elif n % 4 == 2:
		print(4)
	else:
		print(2)
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/742/B:
There are some beautiful girls in Arpa’s land as mentioned before.

Once Arpa came up with an obvious problem:

Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that $a_{i} \oplus a_{j} = x$, where $\oplus$ is bitwise xor operation (see notes for explanation).

 [Image]

Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

-----Input-----

First line contains two integers n and x (1 ≤ n ≤ 10^5, 0 ≤ x ≤ 10^5) — the number of elements in the array and the integer x.

Second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the elements of the array.

-----Output-----

Print a single integer: the answer to the problem.

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

Output
1
Input
6 1
5 1 2 3 4 1

Output
2

-----Note-----

In the first sample there is only one pair of i = 1 and j = 2. $a_{1} \oplus a_{2} = 3 = x$ so the answer is 1.

In the second sample the only two pairs are i = 3, j = 4 (since $2 \oplus 3 = 1$) and i = 1, j = 5 (since $5 \oplus 4 = 1$).

A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

I tried it in Python, but could not do it. Can you solve it?

n, x=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]

ax=[i^x for i in a]
a.sort()
ax.sort()
pos=0
posx=0
c=1
cx=1
total=0
while pos<n and posx<n:
	if a[pos]==ax[posx]:
		if pos<n-1 and a[pos+1]==a[pos]:
			pos+=1
			c+=1
		elif posx<n-1 and ax[posx+1]==ax[posx]:
			posx+=1
			cx+=1
		else:
			#print(c, cx, pos, posx)
			total+=c*cx
			c=1
			cx=1
			pos+=1
			posx+=1
	elif a[pos]>ax[posx]:
		posx+=1
	else:
		pos+=1
#print(total, a, ax)
if x>0:
	print(total//2)
else:
	print((total-n)//2)


I found an interesting problem on https://codeforces.com/problemset/problem/743/A:
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.

Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport.

To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.

Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.

Print the minimum cost Vladik has to pay to get to the olympiad.

-----Input-----

The first line contains three integers n, a, and b (1 ≤ n ≤ 10^5, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach.

The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.

-----Output-----

Print single integer — the minimum cost Vladik has to pay to get to the olympiad.

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

Output
1
Input
5 5 2
10110

Output
0

-----Note-----

In the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1.

In the second...

I tried it in Python, but could not do it. Can you solve it?

n, a, b = map(int, input().split())
lst = input()
if (lst[a - 1] == lst[b - 1]):
    print(0)
else:
    print(1)


I found an interesting problem on https://codeforces.com/problemset/problem/743/B:
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.

Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.

The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.

Please help Chloe to solve the problem!

-----Input-----

The only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2^{n} - 1).

-----Output-----

Print single integer — the integer at the k-th position in the obtained sequence.

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

Output
2
Input
4 8

Output
4

-----Note-----

In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.

In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.

I tried it in Python, but could not do it. Can you solve it?

import math

n, k = list(map(int, input().split()))
arr = reversed([int(math.pow(2, i)) for i in range(50)])

for index, num in enumerate(arr):
	if k % num == 0:
		print(50 - index)
		break


I found an interesting problem on https://codeforces.com/problemset/problem/743/D:
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes.

They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer a_{i} — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.

The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.

Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.

Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of gifts.

The next line contains n integers...

I tried it in Python, but could not do it. Can you solve it?

import sys
input = sys.stdin.readline

oo = 10**20
n = int(input())
a = list(map(int, input().split()))
adj = [[] for _ in range(n)]
for _ in range(n-1):
    u, v = [int(i) - 1 for i in input().split()]
    adj[u].append(v)
    adj[v].append(u)
sm = [0] * n
mx = [-oo] * n
best = [-oo] * n

def dfs(start):
    stack = [(start, -1)]
    visit = [False] * n
    while stack:
        u, p = stack[-1]
        if not visit[u]:
            for v in adj[u]:
                if v != p:
                    stack.append((v, u))
            visit[u] = True
        else:
            x = [-oo] * 3
            for v in adj[u]:
                if v != p:
                    sm[u] += sm[v]
                    mx[u] = max(mx[u], mx[v])
                    best[u] = max(best[u], best[v])
                    x[0] = mx[v]
                    x.sort()
            sm[u] += a[u]
            mx[u] = max(mx[u], sm[u])
            if x[1] > -oo and x[2] > -oo:
                cur = x[1] + x[2]
                best[u] = max(best[u], cur)
            stack.pop()

dfs(0)
ans = max(best)
if ans <= -oo:
    print('Impossible')
else:
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/743/E:
Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:

  the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are c_{k} cards with number k on them in the subsequence, than for all pairs of integers $i \in [ 1,8 ], j \in [ 1,8 ]$ the condition |c_{i} - c_{j}| ≤ 1 must hold.  if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition.

Please help Vladik to find the length of the longest subsequence that satisfies both conditions.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence.

The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.

-----Output-----

Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.

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

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

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

Output
17

-----Note-----

In the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.

I tried it in Python, but could not do it. Can you solve it?

import copy

def solve():
    n = int(input())
    a = [int(c)-1 for c in input().split(' ')]

    nextcard = [[-1 for i in range(8)] for j in range(n)]
    for i in range(n-2, -1, -1):
        nextcard[i] = copy.copy(nextcard[i+1])
        nextcard[i][a[i+1]] = i+1

    jump = [[-1 for i in range(n+1)] for j in range(n)]
    for i in range(n):
        card = a[i]
        cpos = i
        j = 1

        while cpos != -1:
            jump[i][j] = cpos
            j+=1
            cpos = nextcard[cpos][card]

    #Find dp solution for range (val, val+1)
    def getLen(val):
        dp = [[-1 for i in range(1<<8)] for j in range(n+1)]
        dp[0][0] = 0

        for i in range(n):
            card = a[i]
            for comb in range(1<<8):
                if (comb & (1<<card)) == 0 and dp[i][comb] != -1:
                    ncomb = comb + (1<<card)

                    if jump[i][val] != -1:
                        j = jump[i][val]+1
                        dp[j][ncomb] = max(dp[j][ncomb], dp[i][comb] + val)

                    if jump[i][val+1] != -1:
                        j = jump[i][val+1]+1
                        dp[j][ncomb] = max(dp[j][ncomb], dp[i][comb] + val + 1)

                dp[i+1][comb] = max(dp[i+1][comb], dp[i][comb])

        return dp[n][(1<<8)-1]

    appear = [False for i in range(8)]
    for c in a:
        appear[c] = True

    result = 0
    for c in appear:
        result += int(c)

    #Finally binary search to find the result

    cur = 0
    for lev in range(9, -1, -1):
        tpow = (1<<lev)
        if cur + tpow < n:
            ret = getLen(cur + tpow)

            if(ret != -1):
                result = max(result, ret)
                cur += tpow

    return result

print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/744/A:
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.

The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.

There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.

Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.

-----Input-----

The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.

The next line of input will contain k integers c_1, c_2, ..., c_{k} (1 ≤ c_{i} ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.

The following m lines of input will contain two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n). This denotes an undirected edge between nodes u_{i} and v_{i}.

It is guaranteed that the graph described by the input is stable.

-----Output-----

Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.

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

Output
2

Input
3 3 1
2
1 2
1 3
2 3

Output
0

-----Note-----

For the first sample test, the graph looks like this:  [Image]  Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.

For the second sample test, the graph looks like this:  $\infty$  We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must...

I tried it in Python, but could not do it. Can you solve it?

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

root = [p for p in range(n+1)]

def par(p):
	if p != root[p]:
		root[p] = par(root[p])
	return root[p]

for i in range(m):
	u,v = list(map(par, list(map(int, input().split()))))
	root[v] = u

sz = [0 for i in range(n+1)]

for i in range(n+1):
	sz[par(i)] += 1

leftover = n
ans = 0
largest = 0

for x in special:
	d = par(x)
	largest = max(largest, sz[d])
	ans += sz[d] * (sz[d] - 1) // 2
	leftover -= sz[d]

ans -= largest * (largest - 1) // 2
ans += (largest+leftover) * ((largest+leftover) - 1) // 2
ans -= m

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/745/A:
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.

Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.

Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.

-----Input-----

The first line of input will be a single string s (1 ≤ |s| ≤ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'–'z').

-----Output-----

Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.

-----Examples-----
Input
abcd

Output
4

Input
bbb

Output
1

Input
yzyz

Output
2

-----Note-----

For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".

For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".

For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".

I tried it in Python, but could not do it. Can you solve it?

#!/usr/bin/env python3

def main():
    try:
        while True:
            s = input()
            a = set()
            for i in range(len(s)):
                a.add(s)
                s = s[1:] + s[0]

            print(len(a))

    except EOFError:
        pass

main()


I found an interesting problem on https://codeforces.com/problemset/problem/745/B:
Hongcow likes solving puzzles.

One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.

The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.

You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.

-----Input-----

The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.

The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.

It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.

-----Output-----

Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.

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

Output
YES

Input
2 2
.X
XX

Output
NO

Input
5 5
.....
..X..
.....
.....
.....

Output
YES

-----Note-----

For the first sample, one example of a rectangle we can form is as follows

111222

111222

For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.

In the third sample, we can shift the first tile by one to the right, and...

I tried it in Python, but could not do it. Can you solve it?

h, w = map(int, input().split())

g = [input() for _ in range(h)]

mh = mw = 10000000
Mh = Mw = 0

for i in range(h):
	for j in range(w):
		if(g[i][j] == 'X'):
			mh = min(mh, i)
			Mh = max(Mh, i)
			mw = min(mw, j)
			Mw = max(Mw, j)

r = 'YES'

for i in range(h):
	for j in range(w):
		if (g[i][j] == 'X') != (mh <= i <= Mh and mw <= j <=Mw) :
			r = 'NO'

print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/746/A:
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.

Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.

-----Input-----

The first line contains the positive integer a (1 ≤ a ≤ 1000) — the number of lemons Nikolay has.

The second line contains the positive integer b (1 ≤ b ≤ 1000) — the number of apples Nikolay has.

The third line contains the positive integer c (1 ≤ c ≤ 1000) — the number of pears Nikolay has.

-----Output-----

Print the maximum total number of lemons, apples and pears from which Nikolay can cook the compote.

-----Examples-----
Input
2
5
7

Output
7

Input
4
7
13

Output
21

Input
2
3
2

Output
0

-----Note-----

In the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7.

In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21.

In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0.

I tried it in Python, but could not do it. Can you solve it?

l = int(input())
y = int(input())
g = int(input())
cnt = 0
while l >= 1 and y>=2 and g >=4:
    cnt+=7
    l-=1
    y-=2
    g-=4
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/746/B:
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter.

Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.

You are given an encoding s of some word, your task is to decode it.

-----Input-----

The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word.

The second line contains the string s of length n consisting of lowercase English letters — the encoding.

-----Output-----

Print the word that Polycarp encoded.

-----Examples-----
Input
5
logva

Output
volga

Input
2
no

Output
no

Input
4
abba

Output
baba

-----Note-----

In the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.

In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.

In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1,...

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/746/C:
The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t_1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s.

Igor is at the point x_1. He should reach the point x_2. Igor passes 1 meter per t_2 seconds.

Your task is to determine the minimum time Igor needs to get from the point x_1 to the point x_2, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point x_1.

Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is not obligatory that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than 1 meter per t_2 seconds). He can also stand at some point for some time.

-----Input-----

The first line contains three integers s, x_1 and x_2 (2 ≤ s ≤ 1000, 0 ≤ x_1, x_2 ≤ s, x_1 ≠ x_2) — the maximum coordinate of the point to which the tram goes, the point Igor is at, and the point he should come to.

The second line contains two integers t_1 and t_2 (1 ≤ t_1, t_2 ≤ 1000) — the time in seconds in which the tram passes 1 meter and the time in seconds in which Igor passes 1 meter.

The third line contains two integers p and d (1 ≤ p ≤ s - 1, d is either 1 or $- 1$) — the position of the tram in the moment Igor came to the point x_1 and the direction of the tram at this moment. If $d = - 1$, the tram goes in the direction from the point s to the point 0. If d = 1, the tram goes in the direction from the point 0 to the point s.

-----Output-----

Print the minimum time in seconds which Igor needs to get from the point x_1 to the point x_2.

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

Output
8

Input
5 4 0
1 2
3 1

Output
7

-----Note-----

In the first example it is profitable for Igor to go by foot and not to wait the tram. Thus, he has to...

I tried it in Python, but could not do it. Can you solve it?

s,x1,x2 = map(int, input().split(" "))
t1,t2 = map(int, input().split(" "))
p,d = map(int, input().split(" "))

if x2 > p and d == 1:
  train_dis = x2 - p
if x2 < p and d == 1:
  train_dis = s - p + s - x2
if x2 > p and d == -1:
  train_dis = p + x2
if x2 < p and d == -1:
  train_dis = p - x2

if x1 < x2 and p>x1 and p<x2 and d == 1:
  train_dis += 2 * s
if x1 < x2 and p>x1 and p>x2:
  train_dis += 2 * x2

if x1 > x2 and p > x2 and p < x1 and d == -1:
  train_dis += 2 * s
if x1 > x2 and p < x1 and p < x2:
  train_dis += 2 * (s-x2)

train_time = train_dis * t1

igor_dis  = abs(x2-x1)
igor_time = igor_dis * t2

print(min(igor_time, train_time))


I found an interesting problem on https://codeforces.com/problemset/problem/746/D:
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.

Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.

-----Input-----

The first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 10^5, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.

-----Output-----

If it is impossible to drink n cups of tea, print "NO" (without quotes).

Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black.

If there are multiple answers, print any of them.

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

Output
GBGBG

Input
7 2 2 5

Output
BBGBGBB
Input
4 3 4 0

Output
NO

I tried it in Python, but could not do it. Can you solve it?

n,k,a,b = map(int,input().split())
A = []
per = 0
if a >= b:
    per=0
    while True:
        if b == 0:
            if a <=k:
                A.append('G'*a)
                break
            else:
                per = 1
                break
        else:
            if a-b>=k-1:
                a-=k
                b-=1
                A.append('G'*k + 'B')
            elif a - b > 0:
                A.append((a-b+1) * 'G' + 'B')
                a -= (a-b+1)
                b -= 1
            else:
                A.append('GB' * a)
                break
else:
    a,b=b,a
    per=0
    while True:
        if b == 0:
            if a <=k:
                A.append('B'*a)
                break
            else:
                per = 1
                break
        else:
            if a-b>=k-1:
                a-=k
                b-=1
                A.append('B'*k + 'G')
            elif a - b > 0:
                A.append((a-b+1) * 'B' + 'G')
                a -= (a-b+1)
                b -= 1
            else:
                A.append('BG' * a)
                break
if per == 1:
    print('NO')
else:
    print(''.join(map(str,A)))


I found an interesting problem on https://codeforces.com/problemset/problem/746/E:
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct.

Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on.

A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.

-----Input-----

The first line contains two integers n and m (2 ≤ n ≤ 2·10^5, 1 ≤ m ≤ 10^9) — the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even.

The second line contains a sequence of n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the numbers on Eugeny's cards.

-----Output-----

If there is no answer, print -1.

Otherwise, in the first line print the minimum number of exchanges. In the second line print n integers — Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to.

If there are multiple answers, it is allowed to print any of them.

-----Examples-----
Input
6 2
5 6 7 9 4 5

Output
1
5 6 7 9 4 2

Input
8 6
7 7 7 7 8 8 8 8

Output
6
7 2 4 6 8 1 3 5

Input
4 1
4 2 1 10

Output
-1

I tried it in Python, but could not do it. Can you solve it?

def solve(A, n, m):
    uniq = set(A)
    odd = list([x for x in uniq if x%2])
    even = list([x for x in uniq if x%2 == 0])
    if len(odd) > n//2:
        odd.sort()
        odd = odd[-n//2:]
    if len(even) > n//2:
        even.sort()
        even = even[-n//2:]

    odd_needed = n//2 - len(odd)
    changes = n - len(odd) - len(even)
    k = 1 if odd_needed else 2

    D = {x: True for x in odd + even}
    A1 = A[:]
    for i, a in enumerate(A):
        if a in D and D[a]:
            D[a] = False
        else:
            while k in D:
                k += 2
            if k > m:
                return None
            A1[i] = k
            k += 2
            if odd_needed == 1: k = 2
            if odd_needed >= 1: odd_needed -= 1

    return A1, changes

n, m = list(map(int, input().split()))
A = [int(x) for x in input().split()]
p = solve(A, n, m)
if p is None:
    print(-1)
else:
    print(p[1])
    print(' '.join(map(str, p[0])))


I found an interesting problem on https://codeforces.com/problemset/problem/746/G:
There are n cities in Berland, each of them has a unique id — an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads — there are no roads.

That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cities.

In the construction plan t integers a_1, a_2, ..., a_{t} were stated, where t equals to the distance from the capital to the most distant city, concerning new roads. a_{i} equals the number of cities which should be at the distance i from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another.

Also, it was decided that among all the cities except the capital there should be exactly k cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it.

Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.

-----Input-----

The first line contains three positive numbers n, t and k (2 ≤ n ≤ 2·10^5, 1 ≤ t, k < n) — the distance to the most distant city from the capital and the number of cities which should be dead-ends (the capital in this number is not taken into consideration).

The second line contains a sequence of t integers a_1, a_2, ..., a_{t} (1 ≤ a_{i} < n), the i-th number is the number of cities which should be at the distance i from the capital. It is guaranteed that the sum of all the values a_{i} equals n - 1.

-----Output-----

If it is impossible to built roads which satisfy all conditions, print -1.

Otherwise, in the first line print one integer n — the number of cities in Berland. In the each of the next n - 1 line print two integers — the ids of cities that are connected by a road. Each road should be printed exactly once. You can print the roads and the cities...

I tried it in Python, but could not do it. Can you solve it?

import sys
import math

def main():
    n,t,k = map(int,sys.stdin.readline().split())
    a = list(map(int,sys.stdin.readline().split()))

    g = [[] for i in range(t+1)]
    g[0].append([1,-1,0])
    c = 1
    for i in range(t):
        for j in range(a[i]):
            c+=1
            g[i+1].append([c,0,0])
            g[i][0][2]+=1

    l=0
    for i in range(1,t+1):
        for j in range(len(g[i])):
            if g[i][j][2]==0:
                l+=1
    if l< k:
        print(-1)
        return

    i=0
    j=0
    m = 1
    while l>k and m<t:
        while i< len(g[m]) and g[m][i][2]>0:
            i+=1
        if i>=len(g[m]):
            i=0
            j=0
            m+=1
            continue
        while j<len(g[m+1]) and g[m][g[m+1][j][1]][2]<2:
            j+=1
        if j>=len(g[m+1]):
            i=0
            j=0
            m+=1
            continue
        g[m][i][2]+=1
        g[m][g[m+1][j][1]][2]-=1
        g[m+1][j][1] = i
        l-=1
        i+=1
        j+=1

    if l!=k:
        print(-1)
        return
    print(n)
    for i in range(1,t+1):
        for j in range(len(g[i])):
            print(g[i][j][0], g[i-1][g[i][j][1]][0])

main()


I found an interesting problem on https://codeforces.com/problemset/problem/747/A:
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.

Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:

  there are exactly n pixels on the display;  the number of rows does not exceed the number of columns, it means a ≤ b;  the difference b - a is as small as possible.

-----Input-----

The first line contains the positive integer n (1 ≤ n ≤ 10^6) — the number of pixels display should have.

-----Output-----

Print two integers — the number of rows and columns on the display.

-----Examples-----
Input
8

Output
2 4

Input
64

Output
8 8

Input
5

Output
1 5

Input
999999

Output
999 1001

-----Note-----

In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.

In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.

In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())

for i in range(1,int(n ** .5) + 1):
    if n % i == 0:
        a = i
print(a,n // a)


I found an interesting problem on https://codeforces.com/problemset/problem/747/B:
The process of mammoth's genome decoding in Berland comes to its end!

One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.

It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.

Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

-----Input-----

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome.

The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

-----Output-----

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

-----Examples-----
Input
8
AG?C??CT

Output
AGACGTCT

Input
4
AGCT

Output
AGCT

Input
6
????G?

Output
===

Input
4
AA??

Output
===

-----Note-----

In the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.

In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.

In the third and the fourth examples it is impossible to decode the genom.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
st = input()

if n % 4 != 0:
    print('===')
else:
    ca, cb, cc, cd = 0, 0, 0, 0
    av = n // 4
    for i in range(len(st)):
        if st[i] == 'A':
            ca += 1
        elif st[i] == 'C':
            cb += 1
        elif st[i] == 'G':
            cc += 1
        elif st[i] == 'T':
            cd += 1

    if ca > av or cb > av or cc > av or cd > av:
        print('===')
    else:
        aa, ab, ac, ad = av - ca, av - cb, av - cc, av -cd
        ss = aa * 'A' + ab * 'C' + ac * 'G' + ad * 'T'
        cnt = 0
        for i in range(len(st)):
            if st[i] == '?':
                print(ss[cnt], end='')
                cnt += 1
            else:
                print(st[i], end='')


I found an interesting problem on https://codeforces.com/problemset/problem/747/C:
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.

It is known that during the day q tasks will come, the i-th of them is characterized with three integers: t_{i} — the moment in seconds in which the task will come, k_{i} — the number of servers needed to perform it, and d_{i} — the time needed to perform this task in seconds. All t_{i} are distinct.

To perform the i-th task you need k_{i} servers which are unoccupied in the second t_{i}. After the servers begin to perform the task, each of them will be busy over the next d_{i} seconds. Thus, they will be busy in seconds t_{i}, t_{i} + 1, ..., t_{i} + d_{i} - 1. For performing the task, k_{i} servers with the smallest ids will be chosen from all the unoccupied servers. If in the second t_{i} there are not enough unoccupied servers, the task is ignored.

Write the program that determines which tasks will be performed and which will be ignored.

-----Input-----

The first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 10^5) — the number of servers and the number of tasks.

Next q lines contains three integers each, the i-th line contains integers t_{i}, k_{i} and d_{i} (1 ≤ t_{i} ≤ 10^6, 1 ≤ k_{i} ≤ n, 1 ≤ d_{i} ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds.

-----Output-----

Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.

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

Output
6
-1
10

Input
3 2
3 2 3
5 1 2

Output
3
3

Input
8 6
1 3 20
4 2 1
6 5 5
10 1 1
15 3 6
21 8 8

Output
6
9
30
-1
15
36

-----Note-----

In the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids...

I tried it in Python, but could not do it. Can you solve it?

n, q = [int(i) for i in input().split()]
available = [1 for i in range(n)]
for task in range(q):
    t, k , d = [int(i) for i in input().split()]
    assign = []
    len_assign = 0
    for i in range(n):
        if available[i] <= t:
            assign.append(i)
            len_assign += 1
        if len_assign >= k:
            break
    if len_assign >= k:
        for j in range(k):
            available[assign[j]] = t+d
        print(sum(assign)+k)
    else:
        print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/747/D:
The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day.

Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.

Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative.

Vasya can change summer tires to winter tires and vice versa at the beginning of any day.

Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.

-----Input-----

The first line contains two positive integers n and k (1 ≤ n ≤ 2·10^5, 0 ≤ k ≤ n) — the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total.

The second line contains a sequence of n integers t_1, t_2, ..., t_{n} ( - 20 ≤ t_{i} ≤ 20) — the average air temperature in the i-th winter day.

-----Output-----

Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.

-----Examples-----
Input
4 3
-5 20 -3 0

Output
2

Input
4 2
-5 20 -3 0

Output
4

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

Output
3

-----Note-----

In the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two....

I tried it in Python, but could not do it. Can you solve it?

import math
from collections import Counter, defaultdict
from itertools import accumulate

R = lambda: map(int, input().split())
n, k = R()
ts = list(R()) + [-1]
k -= sum(1 if t < 0 else 0 for t in ts[:n])
res = 0 if ts[0] >= 0 else 1
for i in range(1, n):
    if ts[i - 1] < 0 and ts[i] >= 0 or ts[i - 1] >= 0 and ts[i] < 0:
        res += 1
locs = [i for i, t in enumerate(ts) if t < 0]
ps = sorted((y - x - 1, y) for x, y in zip(locs, locs[1:]) if y - x > 1)
res1 = res
k1 = k
for p in ps:
    if k >= p[0]:
        res -= (2 if p[1] < n else 1)
        k -= p[0]
    if k1 >= p[0] and p[1] < n:
        res1 -= 2
        k1 -= p[0]
res = res if k >= 0 else math.inf
res1 = res1 if k1 >= 0 else math.inf
print(min(res, res1) if min(res, res1) < math.inf else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/747/E:
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.

Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.

When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format:   at first, the text of the comment is written;  after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments);  after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm).  All elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma.

For example, if the comments look like: [Image]

then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format:   at first, print a integer d — the maximum depth of nesting comments;  after that print d lines, the i-th of them corresponds to nesting level i;  for the i-th row print comments of nesting level i in the order of their appearance in the Policarp's comments feed, separated by space.

-----Input-----

The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas.

It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and...

I tried it in Python, but could not do it. Can you solve it?

t = input().split(',')
m = len(t)
p, d, k = [m] * m, [[] for i in range(m)], 0
for i in range(0, m, 2):
    s, n = t[i], int(t[i + 1])
    while p[k] == 0: k -= 1
    p[k] -= 1
    d[k].append(s)
    k += 1
    p[k] = n
while d[k]: k += 1
print(k)
for q in d[:k]: print(*q)


I found an interesting problem on https://codeforces.com/problemset/problem/748/A:
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numbered from 1 to m starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).

The organizers numbered all the working places from 1 to 2nm. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. [Image] The picture illustrates the first and the second samples.

Santa Clause knows that his place has number k. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!

-----Input-----

The only line contains three integers n, m and k (1 ≤ n, m ≤ 10 000, 1 ≤ k ≤ 2nm) — the number of lanes, the number of desks in each lane and the number of Santa Claus' place.

-----Output-----

Print two integers: the number of lane r, the number of desk d, and a character s, which stands for the side of the desk Santa Claus. The character s should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right.

-----Examples-----
Input
4 3 9

Output
2 2 L

Input
4 3 24

Output
4 3 R

Input
2 4 4

Output
1 2 R

-----Note-----

The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example.

In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right.

I tried it in Python, but could not do it. Can you solve it?

N, M, K = list(map(int, input().split()))
row_size = 2 * M
K -= 1
row = K // row_size
K %= row_size
side = 'L' if K % 2 == 0 else 'R'
d = K // 2

print(row + 1, d + 1, side)


I found an interesting problem on https://codeforces.com/problemset/problem/748/B:
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.

In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.

You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.

-----Input-----

The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.

-----Output-----

If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).

Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.

If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.

Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.

-----Examples-----
Input
helloworld
ehoolwlroz

Output
3
h e
l o
d z

Input
hastalavistababy
hastalavistababy

Output
0

Input
merrychristmas
christmasmerry

Output
-1

I tried it in Python, but could not do it. Can you solve it?

def main():
    a = input()
    b = input()
    keyboard = dict()
    for i in range(ord("a"), ord("z") + 1):
        keyboard[chr(i)] = " "
    index = 1
    size = 0
    out = ""
    size = 0

    for i in range(len(a)):
        if a[i] != b[i]:
            if keyboard[a[i]] == " " and keyboard[b[i]] == " ":
                keyboard[a[i]] = b[i]
                keyboard[b[i]] = a[i]
                size += 1
                out += a[i] + " " + b[i] + "\n"
            elif not(keyboard[a[i]] == b[i] and keyboard[b[i]] == a[i]):
                print(-1)
                return 0
        else:
            if keyboard[a[i]] == " ":
                keyboard[a[i]] = a[i]
            elif keyboard[a[i]] != a[i]:
                print(-1)
                return 0

    print(size)
    if size > 0:
        print(out)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/748/C:
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p_1, p_2, ..., p_{m} with integer coordinates, do the following: denote its initial location by p_0. First, the robot will move from p_0 to p_1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p_1, it'll move to p_2, again, choosing one of the shortest ways, then to p_3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.

While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.

-----Input-----

The first line of input contains the only positive integer n (1 ≤ n ≤ 2·10^5) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R — to the right, U — to the top and D — to the bottom. Have a look at the illustrations for better explanation.

-----Output-----

The only line of input should contain the minimum possible length of the sequence.

-----Examples-----
Input
4
RURD

Output
2

Input
6
RRULDD

Output
2

Input
26
RRRULURURUULULLLDLDDRDRDLD

Output
7

Input
3
RLL

Output
2

Input
4
LRLR

Output
4

-----Note-----

The illustrations to the first three tests are given below.

[Image] [Image] [Image]

The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.

I tried it in Python, but could not do it. Can you solve it?

n = int(input())
string = input()
res = []
r = 0
for i in string:
    if i not in res:
        if len(res) == 2 or len(res) == 0:
            res = [i]
            r += 1
        else:
            if (res[0] in ("U", "D") and i in ("L", "R")) or (i in ("U", "D") and res[0] in ("L", "R")):
                res.append(i)
            else:
                res = [i]
                r += 1

print(r)


I found an interesting problem on https://codeforces.com/problemset/problem/748/D:
Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string s_{i} having the same length n. We denote the beauty of the i-th string by a_{i}. It can happen that a_{i} is negative — that means that Santa doesn't find this string beautiful at all.

Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n.

Recall that a palindrome is a string that doesn't change after one reverses it.

Since the empty string is a palindrome too, the answer can't be negative. Even if all a_{i}'s are negative, Santa can obtain the empty string.

-----Input-----

The first line contains two positive integers k and n divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1 ≤ k, n ≤ 100 000; n·k  ≤ 100 000).

k lines follow. The i-th of them contains the string s_{i} and its beauty a_{i} ( - 10 000 ≤ a_{i} ≤ 10 000). The string consists of n lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties.

-----Output-----

In the only line print the required maximum possible beauty.

-----Examples-----
Input
7 3
abb 2
aaa -3
bba -1
zyz -4
abb 5
aaa 7
xyx 4

Output
12

Input
3 1
a 1
a 2
a 3

Output
6

Input
2 5
abcde 10000
abcde 10000

Output
0

-----Note-----

In the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).

I tried it in Python, but could not do it. Can you solve it?

import sys
import math

def solve():
    k, n = list(map(int, input().split()))
    D = {}
    for line in sys.stdin:
        s, a = line.split()
        if s in D:
            D[s].append(int(a))
        else:
            D[s] = [int(a)]

    res = 0
    center = 0
    for s in D:
        revs = s[::-1]
        if not revs in D: continue
        D[revs].sort()
        D[s].sort()

        if s == revs:
            while len(D[s]) > 1 and D[s][-2] + D[s][-1] > 0:
                center = max(center, -D[s][-2])
                res += D[s].pop()
                res += D[s].pop()

            if len(D[s]) > 0:
                center = max(center, D[s][-1])
        else:
            while (len(D[s]) > 0 and len(D[revs]) > 0 and
                   D[s][-1] + D[revs][-1] > 0):
                res += D[s].pop()
                res += D[revs].pop()

    return res + center

print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/749/A:
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.

Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.

-----Input-----

The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).

-----Output-----

The first line of the output contains a single integer k — maximum possible number of primes in representation.

The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.

-----Examples-----
Input
5

Output
2
2 3

Input
6

Output
3
2 2 2

I tried it in Python, but could not do it. Can you solve it?


I found an interesting problem on https://codeforces.com/problemset/problem/749/B:
Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwise traversal.

Alex had very nice test for this problem, but is somehow happened that the last line of the input was lost and now he has only three out of four points of the original parallelogram. He remembers that test was so good that he asks you to restore it given only these three points.

-----Input-----

The input consists of three lines, each containing a pair of integer coordinates x_{i} and y_{i} ( - 1000 ≤ x_{i}, y_{i} ≤ 1000). It's guaranteed that these three points do not lie on the same line and no two of them coincide.

-----Output-----

First print integer k — the number of ways to add one new integer point such that the obtained set defines some parallelogram of positive area. There is no requirement for the points to be arranged in any special order (like traversal), they just define the set of vertices.

Then print k lines, each containing a pair of integer — possible coordinates of the fourth point.

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

Output
3
1 -1
-1 1
1 1

-----Note-----

If you need clarification of what parallelogram is, please check Wikipedia page:

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

I tried it in Python, but could not do it. Can you solve it?

x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())

def mirror(x1, y1, x2, y2, x3, y3):
    x_mid = (x1 + x2) / 2
    if x3 < x_mid:
        x3 += 2 * (x_mid - x3)
    else:
        x3 -= 2 * (x3 - x_mid)
    y_mid = (y1 + y2) / 2
    if y3 < y_mid:
        y3 += 2 * (y_mid - y3)
    else:
        y3 -= 2 * (y3 - y_mid)
    return x3, y3

answer = []
x, y = mirror(x1, y1, x2, y2, x3, y3)
if int(x) == x and int(y) == y:
    answer.append([x, y])
x, y = mirror(x1, y1, x3, y3, x2, y2)
if int(x) == x and int(y) == y:
    answer.append([x, y])
x, y = mirror(x3, y3, x2, y2, x1, y1)
if int(x) == x and int(y) == y:
    answer.append([x, y])
print(len(answer))
for i in answer:
    print(int(i[0]), int(i[1]))


I found an interesting problem on https://codeforces.com/problemset/problem/749/C:
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.

Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:   Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).  When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.  When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.  The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.

You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of employees.

The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.

-----Output-----

Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will...

I tried it in Python, but could not do it. Can you solve it?

#
# Created by Daniil Kozhanov. All rights reserved.
#               december 2016

n = int(input())
s = input()
u = [1] * n
u1 = 0
u2 = 0
c1 = s.count("D")
c2 = s.count("R")

while c1 != 0 and c2 !=0:
    for i in range(n):
        if s[i] == "D":
            if u[i] == 1:
                if u1 > 0:
                    u1 -= 1
                    u[i] -= 1
                    c1 -= 1
                else:
                    u2 += 1
        else:
            if u[i] == 1:
                if u2 > 0:
                    u2 -= 1
                    u[i] -= 1
                    c2 -= 1
                else:
                    u1 += 1

if c2 == 0:
    print("D")
else:
    print("R")


I found an interesting problem on https://codeforces.com/problemset/problem/749/E:
You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally:  Pick a random segment (continuous subsequence) from l to r. All $\frac{n(n + 1)}{2}$ segments are equiprobable.  Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p_1, p_2, ..., p_{k}. All k! permutation are equiprobable.  This permutation is applied to elements of the chosen segment, i.e. permutation a_1, a_2, ..., a_{l} - 1, a_{l}, a_{l} + 1, ..., a_{r} - 1, a_{r}, a_{r} + 1, ..., a_{n} is transformed to a_1, a_2, ..., a_{l} - 1, a_{l} - 1 + p_1, a_{l} - 1 + p_2, ..., a_{l} - 1 + p_{k} - 1, a_{l} - 1 + p_{k}, a_{r} + 1, ..., a_{n}.

Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and a_{i} > a_{j}. Find the expected number of inversions after we apply exactly one operation mentioned above.

-----Input-----

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

The second line contains n distinct integers from 1 to n — elements of the permutation.

-----Output-----

Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 9}.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-9}$.

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

Output
1.916666666666666666666666666667

I tried it in Python, but could not do it. Can you solve it?

# Python3 program to count inversions using
# Binary Indexed Tree

# Returns sum of arr[0..index]. This function
# assumes that the array is preprocessed and
# partial sums of array elements are stored
# in BITree[].
def getSum( BITree, index):
    sum = 0 # Initialize result

    # Traverse ancestors of BITree[index]
    while (index > 0):

        # Add current element of BITree to sum
        sum += BITree[index]

        # Move index to parent node in getSum View
        index -= index & (-index)

    return sum

# Updates a node in Binary Index Tree (BITree)
# at given index in BITree. The given value
# 'val' is added to BITree[i] and all of its
# ancestors in tree.
def updateBIT(BITree, n, index, val):

    # Traverse all ancestors and add 'val'
    while (index <= n):

        # Add 'val' to current node of BI Tree
        BITree[index] += val

        # Update index to that of parent
        # in update View
        index += index & (-index)

# Returns count of inversions of size three
def getInvCount(arr, n):

    invcount = 0 # Initialize result

    # Find maximum element in arrays
    maxElement = max(arr)

    # Create a BIT with size equal to
    # maxElement+1 (Extra one is used
    # so that elements can be directly
    # be used as index)
    BIT = [0] * (maxElement + 1)
    for i in range(1, maxElement + 1):
        BIT[i] = 0
    for i in range(n - 1, -1, -1):
        invcount += getSum(BIT, arr[i] - 1)
        updateBIT(BIT, maxElement, arr[i], 1)
    return invcount

def getInvCountAdv(arr, n):

    invcount = 0 # Initialize result

    # Find maximum element in arrays
    maxElement = max(arr)

    # Create a BIT with size equal to
    # maxElement+1 (Extra one is used
    # so that elements can be directly
    # be used as index)
    BIT = [0] * (maxElement + 1)
    for i in range(1, maxElement + 1):
        BIT[i] = 0
    for i in range(n - 1, -1, -1):
       ...