I found an interesting problem on https://codeforces.com/problemset/problem/645/A:
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below: $\rightarrow$

In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.

-----Input-----

The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.

-----Output-----

Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).

-----Examples-----
Input
AB
XC
XB
AC

Output
YES

Input
AB
XC
AC
BX

Output
NO

-----Note-----

The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.

In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...

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

s1 = input() + input()[::-1]
s2 = input() + input()[::-1]
s1 = s1[:s1.find('X')] + s1[s1.find('X') + 1:]
s2 = s2[:s2.find('X')] + s2[s2.find('X') + 1:]

flag = False

for i in range(3):
    if s1 == s2:
        flag = True
        break
    s1 = s1[-1] + s1[:-1]

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


I found an interesting problem on https://codeforces.com/problemset/problem/645/B:
It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his k minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making no more than one swap each minute.

Being the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the k minutes that they have. We denote as p_{i} the label of the cow in the i-th stall. The messiness of an arrangement of cows is defined as the number of pairs (i, j) such that i < j and p_{i} > p_{j}.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ n, k ≤ 100 000) — the number of cows and the length of Farmer John's nap, respectively.

-----Output-----

Output a single integer, the maximum messiness that the Mischievous Mess Makers can achieve by performing no more than k swaps.

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

Output
10

Input
1 10

Output
0

-----Note-----

In the first sample, the Mischievous Mess Makers can swap the cows in the stalls 1 and 5 during the first minute, then the cows in stalls 2 and 4 during the second minute. This reverses the arrangement of cows, giving us a total messiness of 10.

In the second sample, there is only one cow, so the maximum possible messiness is 0.

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/645/C:
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.

Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.

-----Input-----

The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John.

The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.

-----Output-----

Print the minimum possible distance between Farmer John's room and his farthest cow.

-----Examples-----
Input
7 2
0100100

Output
2

Input
5 1
01010

Output
2

Input
3 2
000

Output
1

-----Note-----

In the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.

In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.

In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.

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

import sys
input = sys.stdin.readline

def judge(i, x):
    return acc[min(n, i+x+1)]-acc[max(0, i-x)]>=k+1

def binary_search(i):
    l, r = 0, n

    while l<=r:
        mid = (l+r)//2

        if judge(i, mid):
            r = mid-1
        else:
            l = mid+1

    return l

n, k = map(int, input().split())
S = input()[:-1]
acc = [0]

for Si in S:
    acc.append(acc[-1]+(1 if Si=='0' else 0))

ans = n

for i in range(n):
    if S[i]=='0':
        ans = min(ans, binary_search(i))

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/645/D:
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.

Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.

-----Input-----

The first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m ($1 \leq m \leq \operatorname{min}(100000, \frac{n(n - 1)}{2})$).

The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}), indicating that robot u_{i} beat robot v_{i} in the i-th rap battle. No two rap battles involve the same pair of robots.

It is guaranteed that at least one ordering of the robots satisfies all m relations.

-----Output-----

Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.

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

Output
4

Input
3 2
1 2
3 2

Output
-1

-----Note-----

In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.

In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to...

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

from heapq import heappop,heappush

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

C = [[] for _ in range(n)]
indeg = [0]*n

def toposort():
    S = [i for i in range(n) if indeg[i] == 0]
    nparent = indeg[:]
    topo = []
    while S:
        cur = S.pop()
        topo.append(cur)
        for neigh,_ in C[cur]:
            nparent[neigh] -= 1
            if nparent[neigh] == 0:
                S.append(neigh)
    return topo

def solve():
    topo = toposort()

    D = [(0,0)]*n
    for cur in topo:
        for neigh,t in C[cur]:
            cd,ct = D[cur]
            nd,_ = D[neigh]
            if nd <= cd + 1:
                D[neigh] = cd + 1, max(ct,t)

    d,t = max(D)
    return t+1 if d == n-1 else -1

for _ in range(m):
    a,b = list(map(int,input().split()))
    C[a-1].append((b-1, _))
    indeg[b-1] += 1

print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/646/A:
Три брата договорились о встрече. Пронумеруем братьев следующим образом: пусть старший брат имеет номер 1, средний брат имеет номер 2, а младший брат — номер 3.

Когда пришло время встречи, один из братьев опоздал. По заданным номерам двух братьев, которые пришли вовремя, вам предстоит определить номер опоздавшего брата.

-----Входные данные-----

В первой строке входных данных следуют два различных целых числа a и b (1 ≤ a, b ≤ 3, a ≠ b) — номера братьев, которые пришли на встречу вовремя. Номера даны в произвольном порядке.

-----Выходные данные-----

Выведите единственное целое число — номер брата, который опоздал на встречу.

-----Пример-----
Входные данные
3 1

Выходные данные
2

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

a,b=input().split()
a=int(a)
b=int(b)
c=None
if a==1 and b==2:
    c=3
    print(c)
if a==2 and b==1:
    c=3
    print(c)
if a==3 and b==2:
    c=1
    print(c)
if a==2 and b==3:
    c=1
    print(c)
if a==1 and b==3:
    c=2
    print(c)
if a==3 and b==1:
    c=2
    print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/646/B:
В Берляндском государственном университете локальная сеть между серверами не всегда работает без ошибок. При передаче двух одинаковых сообщений подряд возможна ошибка, в результате которой эти два сообщения сливаются в одно. При таком слиянии конец первого сообщения совмещается с началом второго. Конечно, совмещение может происходить только по одинаковым символам. Длина совмещения должна быть положительным числом, меньшим длины текста сообщения.

Например, при передаче двух сообщений «abrakadabra» подряд возможно, что оно будет передано с ошибкой описанного вида, и тогда будет получено сообщение вида «abrakadabrabrakadabra» или «abrakadabrakadabra» (в первом случае совмещение произошло по одному символу, а во втором — по четырем).

По полученному сообщению t определите, возможно ли, что это результат ошибки описанного вида работы локальной сети, и если возможно, определите возможное значение s.

Не следует считать ошибкой ситуацию полного наложения друга на друга двух сообщений. К примеру, если получено сообщение «abcd», следует считать, что в нём ошибки нет. Аналогично, простое дописывание одного сообщения вслед за другим не является признаком ошибки. Например, если получено сообщение «abcabc», следует считать, что в нём ошибки нет.

-----Входные данные-----

В единственной строке выходных данных следует непустая строка t, состоящая из строчных букв латинского алфавита. Длина строки t не превосходит 100 символов.

-----Выходные данные-----

Если сообщение t не может содержать ошибки, выведите «NO» (без кавычек) в единственную строку выходных данных.

В противном случае в первой строке выведите «YES» (без кавычек), а в следующей строке выведите строку s — возможное сообщение, которое могло привести к ошибке. Если возможных ответов несколько, разрешается вывести любой из них.

-----Примеры-----
Входные данные
abrakadabrabrakadabra

Выходные данные
YES
abrakadabra

Входные данные
acacacaca

Выходные данные
YES
acaca

Входные данные
abcabc

Выходные данные
NO

Входные данные
abababab

Выходные...

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

s = input()

l= len(s)//2
o = 0
if len(s) % 2 != 0:
	o = 1
for i in range(1,l):
	# print(i)
	# print(s[:i+l], s[l-i:])
	if s[:l + i] == s[o+l-i:]:
		print("YES")
		print(s[:i+l])
		break
else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/647/A:
Родители Васи хотят, чтобы он как можно лучше учился. Поэтому если он получает подряд три положительные оценки («четвёрки» или «пятёрки»), они дарят ему подарок. Соответственно, оценки «единица», «двойка» и «тройка» родители Васи считают плохими. Когда Вася получает подряд три хорошие оценки, ему сразу вручают подарок, но для того, чтобы получить ещё один подарок, ему вновь надо получить подряд ещё три хорошие оценки.

Например, если Вася получит подряд пять «четвёрок» оценок, а потом «двойку», то ему дадут только один подарок, а вот если бы «четвёрок» было уже шесть, то подарков было бы два.

За месяц Вася получил n оценок. Вам предстоит посчитать количество подарков, которые получил Вася. Оценки будут даны именно в том порядке, в котором Вася их получал.

-----Входные данные-----

В первой строке входных данных следует целое положительное число n (3 ≤ n ≤ 1000) — количество оценок, полученных Васей.

Во второй строке входных данных следует последовательность из n чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 5) — оценки, полученные Васей. Оценки заданы в том порядке, в котором Вася их получил.

-----Выходные данные-----

Выведите одно целое число — количество подарков, полученных Васей.

-----Примеры-----
Входные данные
6
4 5 4 5 4 4

Выходные данные
2

Входные данные
14
1 5 4 5 2 4 4 5 5 4 3 4 5 5

Выходные данные
3

-----Примечание-----

В первом примере Вася получит два подарка — за первые три положительные оценки и за следующую тройку положительных оценок соответственно.

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

input()
round_counter = 0
counter = 0
for x in [int(y) for y in input().split(" ") if y in "12345"]:
	if x > 3:
		round_counter += 1
		if round_counter == 3:
			counter+=1
			round_counter = 0
	if (round_counter < 3) and x<=3:
		round_counter = 0
print(counter)


I found an interesting problem on https://codeforces.com/problemset/problem/647/B:
Карта звёздного неба представляет собой прямоугольное поле, состоящее из n строк по m символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда).

Новое издание карты звёздного неба будет напечатано на квадратных листах, поэтому требуется найти минимально возможную сторону квадрата, в который могут поместиться все звезды. Границы искомого квадрата должны быть параллельны сторонам заданного прямоугольного поля.

-----Входные данные-----

В первой строке входных данных записаны два числа n и m (1 ≤ n, m ≤ 1000) — количество строк и столбцов на карте звездного неба.

В следующих n строках задано по m символов. Каждый символ — это либо «.» (пустой участок неба), либо «*» (звезда).

Гарантируется, что на небе есть хотя бы одна звезда.

-----Выходные данные-----

Выведите одно число — минимально возможную сторону квадрата, которым можно накрыть все звезды.

-----Примеры-----
Входные данные
4 4
....
..*.
...*
..**

Выходные данные
3

Входные данные
1 3
*.*

Выходные данные
3

Входные данные
2 1
.
*

Выходные данные
1

-----Примечание-----

Один из возможных ответов на первый тестовый пример:

 [Image]

Один из возможных ответов на второй тестовый пример (обратите внимание, что покрывающий квадрат выходит за пределы карты звездного неба):

 [Image]

Ответ на третий тестовый пример:

 [Image]

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/648/A:
Профиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».  ...........

.........*.

.*.......*.

**.......*.

**..*...**.

***********   Пример изображения горного хребта.

Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправо — в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце.

Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины:  наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма),  наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска).

-----Входные данные-----

В первой строке входных данных записаны два целых числа n и m (1 ≤ n, m ≤ 100) — количество строк и столбцов в схематичном изображении соответственно.

Далее следуют n строк по m символов в каждой — схематичное изображение горного хребта. Каждый символ схематичного изображения — это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*».

-----Выходные данные-----

Выведите через пробел два целых числа:  величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма),  величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска).

-----Примеры-----
Входные данные
6 11
...........
.........*.
.*.......*.
**.......*.
**..*...**.
***********

Выходные данные
3 4

Входные данные
5...

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

n,m = list(map(int,input().split()))
A = [list(input()) for i in range(n)]
p = 0
s = 0
b = 0
B =[]
for i in range(m):
    for j in range(n):
        if A[j][i] == '*':
            b += 1
    B.append(b)
    b = 0
for i in range(m-1):
    if B[i] > B[i+1] and (B[i] - B[i+1]) > s:
        s = B[i] - B[i+1]
    elif B[i] < B[i+1] and (B[i+1] - B[i]) > p:
        p = B[i+1] - B[i]
print(p,s)


I found an interesting problem on https://codeforces.com/problemset/problem/648/B:
Вася купил стол, у которого n ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке.

Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.

-----Входные данные-----

В первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей.

Во второй строке следует последовательность из 2n целых положительных чисел a_1, a_2, ..., a_2n (1 ≤ a_{i} ≤ 100 000) — длины частей ножек стола в произвольном порядке.

-----Выходные данные-----

Выведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.

-----Примеры-----
Входные данные
3
1 3 2 4 5 3

Выходные данные
1 5
2 4
3 3

Входные данные
3
1 1 1 2 2 2

Выходные данные
1 2
2 1
1 2

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

from collections import deque
n = int(input())
h = sorted(list(map(int, input().split())))
data = deque(h)
for i in range(n):
    print(data[0], data[-1])
    data.pop()
    data.popleft()


I found an interesting problem on https://codeforces.com/problemset/problem/648/C:
Вам задано прямоугольное клетчатое поле, состоящее из n строк и m столбцов. Поле содержит цикл из символов «*», такой что:  цикл можно обойти, посетив каждую его клетку ровно один раз, перемещаясь каждый раз вверх/вниз/вправо/влево на одну клетку;  цикл не содержит самопересечений и самокасаний, то есть две клетки цикла соседствуют по стороне тогда и только тогда, когда они соседние при перемещении вдоль цикла (самокасание по углу тоже запрещено).

Ниже изображены несколько примеров допустимых циклов: [Image]

Все клетки поля, отличные от цикла, содержат символ «.». Цикл на поле ровно один. Посещать клетки, отличные от цикла, Роботу нельзя.

В одной из клеток цикла находится Робот. Эта клетка помечена символом «S». Найдите последовательность команд для Робота, чтобы обойти цикл. Каждая из четырёх возможных команд кодируется буквой и обозначает перемещение Робота на одну клетку:  «U» — сдвинуться на клетку вверх,  «R» — сдвинуться на клетку вправо,  «D» — сдвинуться на клетку вниз,  «L» — сдвинуться на клетку влево.

Робот должен обойти цикл, побывав в каждой его клетке ровно один раз (кроме стартовой точки — в ней он начинает и заканчивает свой путь).

Найдите искомую последовательность команд, допускается любое направление обхода цикла.

-----Входные данные-----

В первой строке входных данных записаны два целых числа n и m (3 ≤ n, m ≤ 100) — количество строк и столбцов прямоугольного клетчатого поля соответственно.

В следующих n строках записаны по m символов, каждый из которых — «.», «*» или «S». Гарантируется, что отличные от «.» символы образуют цикл без самопересечений и самокасаний. Также гарантируется, что на поле ровно одна клетка содержит «S» и что она принадлежит циклу. Робот не может посещать клетки, помеченные символом «.».

-----Выходные данные-----

В первую строку выходных данных выведите искомую последовательность команд для Робота. Направление обхода цикла Роботом может быть любым.

-----Примеры-----
Входные данные
3 3
***
*.*
*S*

Выходные данные
LUURRDDL

Входные данные
6...

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/649/A:
Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2.

По заданной последовательности целых положительных чисел a_1, a_2, ..., a_{n} требуется найти r — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел a_{i}, которые делятся на r.

-----Входные данные-----

В первой строке записано целое число n (1 ≤ n ≤ 100) — длина последовательности a.

Во второй строке записана последовательность целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).

-----Выходные данные-----

Выведите два числа:

  r — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности,  количество элементов последовательности, которые делятся на r.

-----Примеры-----
Входные данные
5
80 7 16 4 48

Выходные данные
16 3

Входные данные
4
21 5 3 33

Выходные данные
1 4

-----Примечание-----

В первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 2^4, на неё делятся числа 80, 16 и 48.

Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 2^0. Это и будет максимальной степенью двойки для данного примера.

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

from math import log2
def c(a, b):
    for i in a:
        if i % b == 0:
            return True
    return False
def cnt(a, b):
    ans = 0
    for i in a:
        if i % b == 0:
            ans += 1
    return ans
input()
a = [int(i) for i in input().split()]
b = 2
while c(a, b):
    b *= 2
print(b // 2, cnt(a, b // 2))


I found an interesting problem on https://codeforces.com/problemset/problem/649/B:
Есть n-подъездный дом, в каждом подъезде по m этажей, и на каждом этаже каждого подъезда ровно k квартир. Таким образом, в доме всего n·m·k квартир. Они пронумерованы естественным образом от 1 до n·m·k, то есть первая квартира на первом этаже в первом подъезде имеет номер 1, первая квартира на втором этаже первого подъезда имеет номер k + 1 и так далее. Особенность этого дома состоит в том, что он круглый. То есть если обходить его по часовой стрелке, то после подъезда номер 1 следует подъезд номер 2, затем подъезд номер 3 и так далее до подъезда номер n. После подъезда номер n снова идёт подъезд номер 1.

Эдвард живёт в квартире номер a, а Наташа — в квартире номер b. Переход на 1 этаж вверх или вниз по лестнице занимает 5 секунд, переход от двери подъезда к двери соседнего подъезда — 15 секунд, а переход в пределах одного этажа одного подъезда происходит мгновенно. Также в каждом подъезде дома есть лифт. Он устроен следующим образом: он всегда приезжает ровно через 10 секунд после вызова, а чтобы переместить пассажира на один этаж вверх или вниз, лифт тратит ровно 1 секунду. Посадка и высадка происходят мгновенно.

Помогите Эдварду найти минимальное время, за которое он сможет добраться до квартиры Наташи. Считайте, что Эдвард может выйти из подъезда только с первого этажа соответствующего подъезда (это происходит мгновенно). Если Эдвард стоит перед дверью какого-то подъезда, он может зайти в него и сразу окажется на первом этаже этого подъезда (это также происходит мгновенно). Эдвард может выбирать, в каком направлении идти вокруг дома.

-----Входные данные-----

В первой строке входных данных следуют три числа n, m, k (1 ≤ n, m, k ≤ 1000) — количество подъездов в доме, количество этажей в каждом подъезде и количество квартир на каждом этаже каждого подъезда соответственно.

Во второй строке входных данных записаны два числа a и b (1 ≤ a, b ≤ n·m·k) — номера квартир, в которых живут Эдвард и Наташа, соответственно. Гарантируется, что эти номера различны.

-----Выходные данные-----

Выведите единственное...

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

read = lambda: list(map(int, input().split()))
n, m, k = read()
a, b = read()
pa = (a - 1) // (m * k) + 1
fa = ((a - 1) % (m * k)) // k + 1
pb = (b - 1) // (m * k) + 1
fb = ((b - 1) % (m * k)) // k + 1
Tp = min(abs(pa - pb), abs(pa - pb + n), abs(pb - pa + n)) * 15
if pa == pb:
    Tf = min(abs(fa - fb) * 5, abs(fa - fb) + 10)
else:
    cnt1 = min((fa - 1) * 5, (fa - 1) + 10)
    cnt2 = min((fb - 1) * 5, (fb - 1) + 10)
    Tf = cnt1 + cnt2
ans = Tp + Tf
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/649/C:
На тренировку по подготовке к соревнованиям по программированию пришли n команд. Тренер для каждой команды подобрал тренировку, комплект задач для i-й команды занимает a_{i} страниц. В распоряжении тренера есть x листов бумаги, у которых обе стороны чистые, и y листов, у которых только одна сторона чистая. При печати условия на листе первого типа можно напечатать две страницы из условий задач, а при печати на листе второго типа — только одну. Конечно, на листе нельзя печатать условия из двух разных комплектов задач. Обратите внимание, что при использовании листов, у которых обе стороны чистые, не обязательно печатать условие на обеих сторонах, одна из них может остаться чистой.

Вам предстоит определить максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.

-----Входные данные-----

В первой строке входных данных следуют три целых числа n, x и y (1 ≤ n ≤ 200 000, 0 ≤ x, y ≤ 10^9) — количество команд, количество листов бумаги с двумя чистыми сторонами и количество листов бумаги с одной чистой стороной.

Во второй строке входных данных следует последовательность из n целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10 000), где i-е число равно количеству страниц в комплекте задач для i-й команды.

-----Выходные данные-----

Выведите единственное целое число — максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.

-----Примеры-----
Входные данные
2 3 5
4 6

Выходные данные
2

Входные данные
2 3 5
4 7

Выходные данные
2

Входные данные
6 3 5
12 11 12 11 12 11

Выходные данные
1

-----Примечание-----

В первом тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать весь первый комплект задач на листах с одной чистой стороной (после этого останется 3 листа с двумя чистыми сторонами и 1 лист с одной чистой стороной), а второй комплект напечатать на трех листах с двумя чистыми сторонами.

Во втором тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать первый комплект...

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

xy = [0, 0]

def check(k):
    nonlocal xy
    x, y = xy
    got = True
    if y * 2 > k:
        y -= k // 2
        if k % 2 != 0:
            if x != 0:
                x -= 1
            elif y != 0:
                y -= 1
            else:
                got = False
    else:
        k -= y * 2
        y = 0
        if k <= x:
            x -= k
        else:
            got = False
    xy = [x, y]
    return got

n, y, x = map(int, input().split())
k = sorted(map(int, input().split()))
cnt = 0
xy = [x, y]
while cnt < n and check(k[cnt]):
    cnt += 1
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/649/D:
Память компьютера состоит из n ячеек, которые выстроены в ряд. Пронумеруем ячейки от 1 до n слева направо. Про каждую ячейку известно, свободна она или принадлежит какому-либо процессу (в таком случае известен процесс, которому она принадлежит).

Для каждого процесса известно, что принадлежащие ему ячейки занимают в памяти непрерывный участок. С помощью операций вида «переписать данные из занятой ячейки в свободную, а занятую теперь считать свободной» требуется расположить все принадлежащие процессам ячейки в начале памяти компьютера. Другими словами, любая свободная ячейка должна располагаться правее (иметь больший номер) любой занятой.

Вам необходимо найти минимальное количество операций переписывания данных из одной ячейки в другую, с помощью которых можно достичь описанных условий. Допустимо, что относительный порядок ячеек в памяти для каждого из процессов изменится после дефрагментации, но относительный порядок самих процессов должен остаться без изменений. Это значит, что если все ячейки, принадлежащие процессу i, находились в памяти раньше всех ячеек процесса j, то и после перемещений это условие должно выполняться.

Считайте, что номера всех процессов уникальны, хотя бы одна ячейка памяти занята каким-либо процессом.

-----Входные данные-----

В первой строке входных данных записано число n (1 ≤ n ≤ 200 000) — количество ячеек в памяти компьютера.

Во второй строке входных данных следуют n целых чисел a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n), где a_{i} равно либо 0 (это означает, что i-я ячейка памяти свободна), либо номеру процесса, которому принадлежит i-я ячейка памяти. Гарантируется, что хотя бы одно значение a_{i} не равно 0.

Процессы пронумерованы целыми числами от 1 до n в произвольном порядке. При этом процессы не обязательно пронумерованы последовательными числами.

-----Выходные данные-----

Выведите одно целое число — минимальное количество операций, которое нужно сделать для дефрагментации памяти.

-----Примеры-----
Входные данные
4
0 2 2 1

Выходные данные
2

Входные данные
8
0 8 8 8 0...

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

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

proc_data = {p: (-1, -1) for p in memory}

for i, c in enumerate(memory):
    d1, d2 = proc_data[c]
    if d1 == -1: d1 = i
    d2 = i
    proc_data[c] = (d1, d2)

try: del proc_data[0]
except KeyError:
    print("0")
    return

data = list(proc_data.values())
data.sort()

ans = 0

first_free = 0

for a, b in data:
    c = a - first_free
    ans += min(c, b-a+1)
    b -= c
    first_free = b + 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/651/A:
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a_1 percent and second one is charged at a_2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).

Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.

Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent.

-----Input-----

The first line of the input contains two positive integers a_1 and a_2 (1 ≤ a_1, a_2 ≤ 100), the initial charge level of first and second joystick respectively.

-----Output-----

Output the only integer, the maximum number of minutes that the game can last. Game continues until some joystick is discharged.

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

Output
6

Input
4 4

Output
5

-----Note-----

In the first sample game lasts for 6 minute by using the following algorithm:  at the beginning of the first minute connect first joystick to the charger, by the end of this minute first joystick is at 4%, second is at 3%;  continue the game without changing charger, by the end of the second minute the first joystick is at 5%, second is at 1%;  at the beginning of the third minute connect second joystick to the charger, after this minute the first joystick is at 3%, the second one is at 2%;  continue the game without changing charger, by the end of the fourth minute first joystick is at 1%, second one is at 3%;  at the beginning of the fifth minute connect first joystick to the charger, after this minute the first joystick...

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

a, b = list(map(int, input().split()))
cnt = 0
while a > 0 and b > 0:
    cnt += 1
    if a < b:
        a += 1
        b -= 2
    else:
        a -= 2
        b += 1
if a < 0 or b < 0:
    cnt -= 1
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/651/B:
There are n pictures delivered for the new exhibition. The i-th painting has beauty a_{i}. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.

We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≤ i ≤ n - 1), such that a_{i} + 1 > a_{i}.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of painting.

The second line contains the sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000), where a_{i} means the beauty of the i-th painting.

-----Output-----

Print one integer — the maximum possible number of neighbouring pairs, such that a_{i} + 1 > a_{i}, after the optimal rearrangement.

-----Examples-----
Input
5
20 30 10 50 40

Output
4

Input
4
200 100 100 200

Output
2

-----Note-----

In the first sample, the optimal order is: 10, 20, 30, 40, 50.

In the second sample, the optimal order is: 100, 200, 100, 200.

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

n=int(input())
x=[int(z) for z in input().split()]
x.sort()
y=[]
cur=x[0]
curs=1
i=1
y=[]
while i<n:
    r=x[i]
    if r==cur:
        curs+=1
    else:
        d=[cur]*curs
        y+=[d]
        curs=1
        cur=r
    i+=1
y+=[[cur]*curs]
res=0

while len(y)>1:
    u=[]
    for h in y:
        h.pop()
        if h!=[]:
            u+=[h]
    res+=len(y)-1
    y=u[:]
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/652/A:
The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h_1 cm from the ground. On the height h_2 cm (h_2 > h_1) on the same tree hung an apple and the caterpillar was crawling to the apple.

Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night.

In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm.

Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple.

-----Input-----

The first line contains two integers h_1, h_2 (1 ≤ h_1 < h_2 ≤ 10^5) — the heights of the position of the caterpillar and the apple in centimeters.

The second line contains two integers a, b (1 ≤ a, b ≤ 10^5) — the distance the caterpillar goes up by day and slips down by night, in centimeters per hour.

-----Output-----

Print the only integer k — the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple.

If the caterpillar can't get the apple print the only integer  - 1.

-----Examples-----
Input
10 30
2 1

Output
1

Input
10 13
1 1

Output
0

Input
10 19
1 2

Output
-1

Input
1 50
5 4

Output
1

-----Note-----

In the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple.

Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day.

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

x=input().split()
y=input().split()
dif=int(x[1])-int(x[0])
cnt=0

if dif-int(y[0])*8<=0:
	print(0)
elif int(y[0])-int(y[1])>0:
	dif=dif-int(y[0])*8+int(y[1])*12
	while dif>0:
		dif-=int(y[0])*12
		if dif<=0:
			cnt+=1
			break
		else :
			cnt+=1
			dif+=int(y[1])*12
	print(cnt)
else: print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/652/B:
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:

  a_{i} ≥ a_{i} - 1 for all even i,  a_{i} ≤ a_{i} - 1 for all odd i > 1.

For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.

Can you make the array z-sorted?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of the array a.

-----Output-----

If it's possible to make the array a z-sorted print n space separated integers a_{i} — the elements after z-sort. Otherwise print the only word "Impossible".

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

Output
1 2 1 2

Input
5
1 3 2 2 5

Output
1 5 2 3 2

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

n = int(input())
m = list(map(int, input().split()))
a = []
m.sort()
i = 0
j = len(m) - 1
while len(m) != len(a):
    if len(a) % 2 != 0:
        a.append(m[j])
        j -= 1
    else:
        a.append(m[i])
        i += 1
print(*a)


I found an interesting problem on https://codeforces.com/problemset/problem/652/C:
You are given a permutation p of length n. Also you are given m foe pairs (a_{i}, b_{i}) (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}).

Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).

Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair (3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 3·10^5) — the length of the permutation p and the number of foe pairs.

The second line contains n distinct integers p_{i} (1 ≤ p_{i} ≤ n) — the elements of the permutation p.

Each of the next m lines contains two integers (a_{i}, b_{i}) (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}) — the i-th foe pair. Note a foe pair can appear multiple times in the given list.

-----Output-----

Print the only integer c — the number of different intervals (x, y) that does not contain any foe pairs.

Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

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

Output
5

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

Output
20

-----Note-----

In the first example the intervals from the answer are (1, 1), (1, 2), (2, 2), (3, 3) and (4, 4).

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

from sys import stdin

def main():
    n, k = list(map(int, stdin.readline().split()))
    ar = list(map(int, stdin.readline().split()))
    lk = {ar[i] - 1: i for i in range(n)}
    pair = [-1 for _ in range(n)]
    for _ in range(k):
        x, y = list(map(int, stdin.readline().split()))
        if lk[y - 1] > lk[x - 1]:
            pair[y - 1] = max(pair[y - 1], lk[x - 1])
        else:
            pair[x - 1] = max(pair[x - 1], lk[y - 1])
    start = 0
    end = 0
    ok = True
    ans = 0
    while end < n:
        while end < n and ok:
            curr = ar[end] - 1
            if start <= pair[curr]:
                ok = False
            else:
                end += 1
        if end < n:
            while start <= pair[ar[end] - 1]:
                ans += end - start
                start += 1
        else:
            ans += (end - start + 1) * (end - start) // 2
        ok = True
    print(ans)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/653/A:
Limak is a little polar bear. He has n balls, the i-th ball has size t_{i}.

Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:  No two friends can get balls of the same size.  No two friends can get balls of sizes that differ by more than 2.

For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).

Your task is to check whether Limak can choose three balls that satisfy conditions above.

-----Input-----

The first line of the input contains one integer n (3 ≤ n ≤ 50) — the number of balls Limak has.

The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 1000) where t_{i} denotes the size of the i-th ball.

-----Output-----

Print "YES" (without quotes) if Limak can choose three balls of distinct sizes, such that any two of them differ by no more than 2. Otherwise, print "NO" (without quotes).

-----Examples-----
Input
4
18 55 16 17

Output
YES

Input
6
40 41 43 44 44 44

Output
NO

Input
8
5 972 3 4 1 4 970 971

Output
YES

-----Note-----

In the first sample, there are 4 balls and Limak is able to choose three of them to satisfy the rules. He must must choose balls with sizes 18, 16 and 17.

In the second sample, there is no way to give gifts to three friends without breaking the rules.

In the third sample, there is even more than one way to choose balls:  Choose balls with sizes 3, 4 and 5.  Choose balls with sizes 972, 970, 971.

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

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time

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

start = time.time()

a   = sorted(list(set(a)))
ans = 'NO'

for i in range(len(a)-2):
    if a[i+2] - a[i] <= 2:
        ans = 'YES'
        break

print(ans)
finish = time.time()
#print(finish - start)


I found an interesting problem on https://codeforces.com/problemset/problem/653/B:
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.

You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string a_{i} of length two and a string b_{i} of length one. No two of q possible operations have the same string a_{i}.

When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string a_{i}. Performing the i-th operation removes first two letters of s and inserts there a string b_{i}. See the notes section for further clarification.

You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any a_{i}.

Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.

-----Input-----

The first line contains two integers n and q (2 ≤ n ≤ 6, 1 ≤ q ≤ 36) — the length of the initial string and the number of available operations.

The next q lines describe the possible operations. The i-th of them contains two strings a_{i} and b_{i} (|a_{i}| = 2, |b_{i}| = 1). It's guaranteed that a_{i} ≠ a_{j} for i ≠ j and that all a_{i} and b_{i} consist of only first six lowercase English letters.

-----Output-----

Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.

-----Examples-----
Input
3 5
ab a
cc c
ca a
ee c
ff d

Output
4

Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c

Output
1

Input
6 2
bb a
ba...

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

n,q = map(int,input().split())
ops = dict()
for _ in range(q):
	a,b = input().split()
	ops[a] = b
from itertools import product
count = 0
for t in product('abcdef', repeat=n):
	s = ''.join(t)
	while len(s) > 1:
		s = ops.get(s[:2], 'g') + s[2:]
	count += s == 'a'
print(count)


I found an interesting problem on https://codeforces.com/problemset/problem/656/A:
-----Input-----

The input contains a single integer a (0 ≤ a ≤ 35).

-----Output-----

Output a single integer.

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

Output
8

Input
10

Output
1024

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/656/B:
Btoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt dya is zreo), adn yuo wsah teh diehss on dya D if adn olny if terhe etsixs an iednx i scuh taht D mod M[i] = R[i], otwsehrie yuor rmootmae deos it. Yuo lkie teh cncepot, btu yuor rmotaome's cuinnng simle meaks yuo ssecupt sthnoemig, so yuo itennd to vefriy teh fnerisas of teh aemnrgeet.

Yuo aer geivn ayarrs M adn R. Cuaclatle teh pceanregte of dyas on wchih yuo edn up dnoig teh wisahng. Amsuse taht yuo hvae iiiftlneny mnay dyas aehad of yuo.

-----Input-----

The first line of input contains a single integer N (1 ≤ N ≤ 16).

The second and third lines of input contain N integers each, all between 0 and 16, inclusive, and represent arrays M and R, respectively. All M[i] are positive, for each i R[i] < M[i].

-----Output-----

Output a single real number. The answer is considered to be correct if its absolute or relative error does not exceed 10^{ - 4}.

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

Output
0.500000

Input
2
2 3
1 0

Output
0.666667

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

def gcd(a, b):
    while b != 0:
        c = a % b
        a = b
        b = c
    return a

input()
m = list(map(int, input().split()))
r = list(map(int, input().split()))
result = 1
for mod in m:
    result = result * mod // gcd(result, mod)
good = 0
for i in range(result):
    for mod, car in zip(m, r):
        if i % mod == car:
            good += 1
            break
print(good / result)


n = int(input())
a = 0
while n:
    if n % 8 == 1:
        a += 1
    n //= 8

print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/656/E:
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.

-----Input-----

The first line of the input contains a single integer N (3 ≤ N ≤ 10).

The following N lines each contain N space-separated integers. jth integer in ith line a_{ij} is the length of the edge that connects vertices i and j. a_{ij} = a_{ji}, a_{ii} = 0, 1 ≤ a_{ij} ≤ 100 for i ≠ j.

-----Output-----

Output the maximum length of the shortest path between any pair of vertices in the graph.

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

Output
2

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

Output
5

-----Note-----

You're running short of keywords, so you can't use some of them:define

do

for

foreach

while

repeat

until

if

then

else

elif

elsif

elseif

case

switch

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/656/F:
-----Input-----

The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid").

-----Output-----

Output a single integer.

-----Examples-----
Input
A221033

Output
21

Input
A223635

Output
22

Input
A232726

Output
23

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

s = input()[1:]
print(1+sum(int(x) for x in s)+9*s.count('0'))


I found an interesting problem on https://codeforces.com/problemset/problem/656/G:
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.

You are given user's friends' opinions about a list of items. You are also given a threshold T — the minimal number of "likes" necessary for an item to be recommended to the user.

Output the number of items in the list liked by at least T of user's friends.

-----Input-----

The first line of the input will contain three space-separated integers: the number of friends F (1 ≤ F ≤ 10), the number of items I (1 ≤ I ≤ 10) and the threshold T (1 ≤ T ≤ F).

The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.

-----Output-----

Output an integer — the number of items liked by at least T of user's friends.

-----Examples-----
Input
3 3 2
YYY
NNN
YNY

Output
2

Input
4 4 1
NNNY
NNYN
NYNN
YNNN

Output
4

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

kitten,I,T=map(int,input().split())
s=[];
for i in range(kitten):
    s.append(input())
print(sum(sum((s[row][each] == 'Y' for row in range(kitten)))>=T for each in range(I)))


I found an interesting problem on https://codeforces.com/problemset/problem/658/A:
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.

There will be n problems. The i-th problem has initial score p_{i} and it takes exactly t_{i} minutes to solve it. Problems are sorted by difficulty — it's guaranteed that p_{i} < p_{i} + 1 and t_{i} < t_{i} + 1.

A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0,  p_{i} - c·x) points.

Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by p_{i}). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by p_{i}). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.

You may assume that the duration of the competition is greater or equal than the sum of all t_{i}. That means both Limak and Radewoosh will accept all n problems.

-----Input-----

The first line contains two integers n and c (1 ≤ n ≤ 50, 1 ≤ c ≤ 1000) — the number of problems and the constant representing the speed of loosing points.

The second line contains n integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1000, p_{i} < p_{i} + 1) — initial scores.

The third line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 1000, t_{i} < t_{i} + 1) where t_{i} denotes the number of minutes one needs to solve the i-th problem.

-----Output-----

Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.

-----Examples-----
Input
3 2
50 85 250
10 15 25

Output
Limak

Input
3 6
50 85 250
10 15 25

Output
Radewoosh

Input
8 1
10 20 30 40 50 60 70 80
8 10 58 63 71 72 75 76

Output
Tie

-----Note-----

In the first sample, there are 3 problems. Limak...

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

n,c=list(map(int,input().split()))
in1=list(map(int,input().split()))
in2=list(map(int,input().split()))
t1,t2,op1,op2=0,0,0,0
for i in range(0,n):
	t1+=in2[i]
	op1+=(in1[i]-c*t1 if(in1[i]-c*t1)>0 else 0)
	t2+=in2[n-i-1]
	op2+=(in1[n-i-1]-c*t2 if(in1[n-i-1]-c*t2)>0 else 0)
if(op1==op2):
	print("Tie")
else:
	print("Limak" if op1>op2 else "Radewoosh")


I found an interesting problem on https://codeforces.com/problemset/problem/659/A:
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.

Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direction of increasing numbers (in this order entrance n should be followed by entrance 1). The negative value of b corresponds to moving |b| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance n). If b = 0, then Vasya prefers to walk beside his entrance. [Image] Illustration for n = 6, a = 2, b =  - 5.

Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.

-----Input-----

The single line of the input contains three space-separated integers n, a and b (1 ≤ n ≤ 100, 1 ≤ a ≤ n,  - 100 ≤ b ≤ 100) — the number of entrances at Vasya's place, the number of his entrance and the length of his walk, respectively.

-----Output-----

Print a single integer k (1 ≤ k ≤ n) — the number of the entrance where Vasya will be at the end of his walk.

-----Examples-----
Input
6 2 -5

Output
3

Input
5 1 3

Output
4

Input
3 2 7

Output
3

-----Note-----

The first example is illustrated by the picture in the statements.

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

__author__ = 'User'
n, a, b = map(int, input().split())
a -= 1
a = (a + b) % n
a += 1
print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/659/B:
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.

The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.

Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

-----Input-----

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland.

Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive).

It is guaranteed that all surnames of all the participants are distinct and at least two people participated...

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

n,m = list(map(int, input().split()))
l = [[] for i in range(m)]
for i in range(n):
    l1 = input().split()
    team = int(l1[1])-1
    l[team].append([int(l1[2]),l1[0]])

for i in range(m):
    a = list(sorted(l[i]))[::-1]
    if len(a) == 2:
        print(a[0][1],a[1][1])
    elif a[1][0]==a[2][0]:
        print("?")
    else:
        print(a[0][1],a[1][1])


I found an interesting problem on https://codeforces.com/problemset/problem/659/C:
In Berland recently a new collection of toys went on sale. This collection consists of 10^9 types of toys, numbered with integers from 1 to 10^9. A toy from the new collection of the i-th type costs i bourles.

Tania has managed to collect n different types of toys a_1, a_2, ..., a_{n} from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.

Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

-----Input-----

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 10^9) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys.

The next line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the types of toys that Tanya already has.

-----Output-----

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m.

In the second line print k distinct space-separated integers t_1, t_2, ..., t_{k} (1 ≤ t_{i} ≤ 10^9) — the types of toys that Tanya should choose.

If there are multiple answers, you may print any of them. Values of t_{i} can be printed in any order.

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

Output
2
2 5

Input
4 14
4 6 12 8

Output
4
7 2 3 1

-----Note-----

In the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

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

n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
s = 0
count = 1
i = 0
answer = []
while i < len(a) and s <= m:
    if a[i] == count:
        i += 1
        count += 1
    else:
        s += count
        answer.append(count)
        count += 1
if s > m:
    s = s - count + 1
    print(len(answer) - 1)
    for i in range(len(answer) - 1):
        print(answer[i], end = ' ')
elif s == m:
    print(len(answer))
    for i in range(len(answer)):
        print(answer[i], end = ' ')
else:
    while s <= m:
        s += count
        answer.append(count)
        count += 1
    if s == m:
        print(len(answer))
        for i in range(len(answer)):
            print(answer[i], end = ' ')
    else:
        s = s - count + 1
        print(len(answer) - 1)
        for i in range(len(answer) - 1):
            print(answer[i], end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/659/D:
Maria participates in a bicycle race.

The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.

Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).

Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.

Help Maria get ready for the competition — determine the number of dangerous turns on the track.

-----Input-----

The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track.

The following (n + 1)-th line contains pairs of integers (x_{i}, y_{i}) ( - 10 000 ≤ x_{i}, y_{i} ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (x_{i}, y_{i}) and ends at the point (x_{i} + 1, y_{i} + 1).

It is guaranteed that:

  the first straight section is directed to the north;  the southernmost (and if there are several, then the most western of among them) point of the track is the first point;  the last point coincides with the first one (i.e., the start position);  any pair of straight sections of the track has no shared points (except...

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

#!/usr/bin/env python3

try:
    while True:
        n = int(input())
        prev_x, prev_y = list(map(int, input().split()))
        prev_d = 0
        result = 0
        for i in range(n):
            x, y = list(map(int, input().split()))
            if y > prev_y:
                d = 0
            elif x > prev_x:
                d = 1
            elif y < prev_y:
                d = 2
            else:
                d = 3
            if ((d + 1) & 0x3) == prev_d:
                result += 1
            prev_x, prev_y = x, y
            prev_d = d
        print(result)

except EOFError:
    pass


I found an interesting problem on https://codeforces.com/problemset/problem/659/E:
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.

The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).

In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.

Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.

-----Input-----

The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).

Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), where x_{i} and y_{i} are the numbers of the cities connected by the i-th road.

It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.

-----Output-----

Print a single integer — the minimum number of separated cities after the reform.

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

Output
1

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

Output
0

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

Output
1

-----Note-----

In the first sample the following road orientation is allowed: $1 \rightarrow 2$, $1 \rightarrow 3$, $3 \rightarrow 4$.

The second sample: $1 \rightarrow 2$, $3 \rightarrow 1$, $2 \rightarrow 3$, $2 \rightarrow 5$, $3 \rightarrow 4$.

The third sample: $1 \rightarrow 2$, $2 \rightarrow 3$, $4 \rightarrow 5$, $5 \rightarrow 6$, $6 \rightarrow 4$.

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

n,m=map(int,input().split())
E=[[] for i in range(n+1)]
for _ in range(m):
    x,y=map(int,input().split())
    E[x]+=[y]
    E[y]+=[x]
f=[0]*(n+1)
def bfs(nom):
    l=[(nom,0)]
    f[nom]=1
    k=1
    while len(l):
        nom,pre=l.pop()
        for x in E[nom]:
            if x!=pre:
                if f[x]: k=0
                else:
                    f[x]=1
                    l+=[(x,nom)]
    return k
ans=0
for i in range(1,n+1):
    if f[i]==0: ans+=bfs(i)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/659/G:
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is h_{i}.

Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).

You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.

As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (10^9 + 7).

-----Input-----

The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.

The second line contains n space-separated numbers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9), where h_{i} equals the height of the i-th board to the left.

-----Output-----

Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.

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

Output
0

Input
3
3 4 2

Output
13

-----Note-----

From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.

All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):  [Image]

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

mod = 10 ** 9 + 7
n = int(input())
h = list([int(x) - 1 for x in input().split()])
ans = x = 0
for i in range(n):
    ans += h[i] + min(h[i], h[i - 1]) * x
    if i < n - 1:
        x *= min(h[i - 1], h[i], h[i + 1])
        x += min(h[i], h[i + 1])
    ans %= mod
    x %= mod
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/660/A:
You are given an array of n elements, you must make it a co-prime array in as few moves as possible.

In each move you can insert any positive integral number you want not greater than 10^9 in any place in the array.

An array is co-prime if any two adjacent numbers of it are co-prime.

In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 1000) — the number of elements in the given array.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of the array a.

-----Output-----

Print integer k on the first line — the least number of elements needed to add to the array a to make it co-prime.

The second line should contain n + k integers a_{j} — the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it.

If there are multiple answers you can print any one of them.

-----Example-----
Input
3
2 7 28

Output
1
2 7 9 28

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

from math import sqrt
n=int(input())
a=[int(i) for i in input().split()]
insert=[0]*n
ans=[]
cnt=0

def is_co_prime(A,B) :
    t=A%B
    if t==0 :
        return B==1,B
    while True :
        A,B=B,t
        if A%B :
            t=A%B
        else :
            C=B
            break
    return C==1,C

for i in range(n-1) :
    check=is_co_prime(a[i],a[i+1])
    if check[0] : continue
    else :
        T=int(sqrt(check[1]))
        while True:
            if is_co_prime(a[i],T)[0] and is_co_prime(T,a[i+1])[0] :
                break
            T+=1
        insert[i]=T
        cnt+=1

for i in range(n):
    ans.append(a[i])
    if insert[i] :
        ans.append(insert[i])

print(cnt)
print(" ".join(map(str,ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/660/B:
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.

Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:

1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.

After occupying all the window seats (for m > 2n) the non-window seats are occupied:

1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.

All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.

1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. [Image] The seating for n = 9 and m = 36.

You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.

-----Input-----

The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers.

-----Output-----

Print m distinct integers from 1 to m — the order in which the passengers will get off the bus.

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

Output
5 1 6 2 7 3 4

Input
9 36

Output
19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18

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

def solve():
    N, M = list(map(int, input().split()))

    ans = []

    def app(x):
        if x < M:
            ans.append(str(x + 1))

    for i in range(0, N * 2, 2):
        app(N * 2 + i)
        app(i)
        app(N * 2 + i + 1)
        app(i + 1)

    print(' '.join(ans))

def __starting_point():
    solve()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/660/C:
You are given an array a with n elements. Each element of a is either 0 or 1.

Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 3·10^5, 0 ≤ k ≤ n) — the number of elements in a and the parameter k.

The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 1) — the elements of a.

-----Output-----

On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones.

On the second line print n integers a_{j} — the elements of the array a after the changes.

If there are multiple answers, you can print any one of them.

-----Examples-----
Input
7 1
1 0 0 1 1 0 1

Output
4
1 0 0 1 1 1 1

Input
10 2
1 0 0 1 0 1 0 1 0 1

Output
5
1 0 0 1 1 1 1 1 0 1

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

n,k=map(int,input().split())
ara=list(map(int,input().split()))
max=0
zero=0
value=0
end=0
for i in range(0,n):
    if ara[i]==0:
        zero+=1
    if zero<=k:
        max+=1
        end=i
    else:
        if ara[value]==0 :
            zero-= 1
        value+= 1
print(max)
for i in range(end-max+1,end+1):
    ara[i]=1
print(" ".join(map(str,ara)))


I found an interesting problem on https://codeforces.com/problemset/problem/660/D:
You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points.

Each of the next n lines contains two integers (x_{i}, y_{i}) (0 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th point.

-----Output-----

Print the only integer c — the number of parallelograms with the vertices at the given points.

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

Output
1

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

from collections import defaultdict

n=int(input())
C=[]
cnt=0
D=defaultdict(int)

for i in range(n) :
    C.append([int(i) for i in input().split()])

for i0 in range(n) :
    x0=C[i0][0]
    y0=C[i0][1]
    for Dots in C[i0+1:] :
        x=Dots[0]-x0
        y=Dots[1]-y0
        if x<0 :
            x,y=-x,-y
        elif x==0 :
            if y<0 :
                y=-y
        cnt+=D[x,y]
        D[x,y]+=1

print(int(cnt/2))


I found an interesting problem on https://codeforces.com/problemset/problem/660/E:
For a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence).

You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo 10^9 + 7.

-----Input-----

The only line contains two integers n and m (1 ≤ n, m ≤ 10^6) — the number of elements in arrays and the upper bound for elements.

-----Output-----

Print the only integer c — the desired sum modulo 10^9 + 7.

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

Output
6

Input
2 2

Output
14

Input
3 3

Output
174

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/662/B:
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.

Find the minimum possible number of moves required to make the colors of all edges equal.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively.

The following m lines provide the description of the edges, as the i-th of them contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the indices of the vertices connected by the i-th edge, and a character c_{i} ($c_{i} \in \{B, R \}$) providing the initial color of this edge. If c_{i} equals 'R', then this edge is initially colored red. Otherwise, c_{i} is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.

-----Output-----

If there is no way to make the colors of all edges equal output  - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a_1, a_2, ..., a_{k}, where a_{i} is equal to the index of the vertex that should be used at the i-th move.

If there are multiple optimal sequences of moves, output any of them.

-----Examples-----
Input
3 3
1 2 B
3 1 R
3 2 B

Output
1
2

Input
6 5
1 3 R
2 3 R
3 4 B
4 5 R
4 6 R

Output
2
3 4

Input
4 5
1 2 R
1 3 R
2 3 B
3 4 B
1 4 B

Output
-1

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

from collections import deque

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

visited = S = T = None

def bfs(i, k):
    q = deque([(i, 0)])
    while q:
        u, p = q.pop()

        if visited[u] >= 0:
            if visited[u] == p: continue
            else: return False

        visited[u] = p
        if p: S.append(u)
        else: T.append(u)

        for v, c in adj[u]:
            nxt = p if c == k else p^1
            q.appendleft((v, nxt))

    return True

def solve(k):
    nonlocal visited, S, T
    visited = [-1]*n
    res = []
    for i in range(n):
        if visited[i] < 0:
            S, T = [], []
            if not bfs(i, k):
                return [0]*(n+1)
            else:
                res.extend(S if len(S) < len(T) else T)
    return res

res1 = solve("R")
res2 = solve("B")

if min(len(res1), len(res2)) > n:
    print(-1)
else:
    print(min(len(res1), len(res2)))
    print(" ".join([str(x+1) for x in res1 if len(res1) < len(res2) else res2]))


I found an interesting problem on https://codeforces.com/problemset/problem/662/D:
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.

For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.

You are given a list of abbreviations. For each of them determine the year it stands for.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.

Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

-----Output-----

For each abbreviation given in the input, find the year of the corresponding Olympiad.

-----Examples-----
Input
5
IAO'15
IAO'2015
IAO'1
IAO'9
IAO'0

Output
2015
12015
1991
1989
1990

Input
4
IAO'9
IAO'99
IAO'999
IAO'9999

Output
1989
1999
2999
9999

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

def main():
    l = []
    for i in range(int(input())):
        y, n, m = 1989, 0, 1
        for d in input()[-1:3:-1]:
            n += (ord(d) - 48) * m
            m *= 10
            t = n - y % m
            y += (m + t if t < 0 else t) + m
        l.append(y - m)
    print('\n'.join(map(str, l)))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/663/A:
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.

-----Input-----

The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.

-----Output-----

The first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise.

If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.

-----Examples-----
Input
? + ? - ? + ? + ? = 42

Output
Possible
9 + 13 - 39 + 28 + 31 = 42

Input
? - ? = 1

Output
Impossible

Input
? = 1000000

Output
Possible
1000000 = 1000000

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

def max(a, b):
	if(a>=b):
		return a
	else:
		return b

####################################

s=input().split()
length=len(s)
n=int(s[length-1])

plus=1
minus=0

for i in s:
	if(i== '+'):
		plus+=1
	if(i== '-'):
		minus+=1

if(plus*n - minus < n or plus - n*minus > n):
	print('Impossible')
	return
else:
	print('Possible')

for i in range(0, length-1, 2): #initializing all placeholders with 1
	s[i]='1'

# if(minus==0):
# 	s[0]= repr(n-plus+1)

# else:

# 	diff=plus-1-minus

# 	if(diff>0):
# 		s[0]=repr(n-diff)
# 		for i in range(2, length-1, 2):
# 			s[i]='1'

# 	flag=0
# 	if(diff<=0):
# 		s[0]=repr(n)
# 		for i in range(2, length-1, 2):
# 			s[i]='1'
# 			if(flag==0 and s[i-1] == '+'):
# 				flag=1
# 				s[i]=repr(1-diff)

res=n-plus+minus
for i in range(0, length-1, 2):
	if((i==0 or s[i-1]=='+' ) and res>0):
		val=int(s[i])
		if(res>n-val):
			res-=(n-val)
			s[i]=repr(n)
		else:
			val+=res
			s[i]=repr(val)
			res=0
	elif(s[i-1]=='-' and res<0):
		val=int(s[i])
		if(res<val-n):
			res+=(n-val)
			s[i]=repr(n)
		else:
			val-=res
			s[i]=repr(val)
			res=0

print(' '.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/664/A:
Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm.

Formally, find the biggest integer d, such that all integers a, a + 1, a + 2, ..., b are divisible by d. To make the problem even more complicated we allow a and b to be up to googol, 10^100 — such number do not fit even in 64-bit integer type!

-----Input-----

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10^100).

-----Output-----

Output one integer — greatest common divisor of all integers from a to b inclusive.

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

Output
1

Input
61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576

Output
61803398874989484820458683436563811772030917980576

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

n,m=list(map(int,input().split()))
if n!=m:
    print(1)
else:
    print(n)


I found an interesting problem on https://codeforces.com/problemset/problem/665/A:
Buses run between the cities A and B, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city A departs every a minutes and arrives to the city B in a t_{a} minutes, and a bus from the city B departs every b minutes and arrives to the city A in a t_{b} minutes.

The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.

You know the time when Simion departed from the city A to the city B. Calculate the number of buses Simion will meet to be sure in his counting.

-----Input-----

The first line contains two integers a, t_{a} (1 ≤ a, t_{a} ≤ 120) — the frequency of the buses from the city A to the city B and the travel time. Both values are given in minutes.

The second line contains two integers b, t_{b} (1 ≤ b, t_{b} ≤ 120) — the frequency of the buses from the city B to the city A and the travel time. Both values are given in minutes.

The last line contains the departure time of Simion from the city A in the format hh:mm. It is guaranteed that there are a bus from the city A at that time. Note that the hours and the minutes are given with exactly two digits.

-----Output-----

Print the only integer z — the number of buses Simion will meet on the way. Note that you should not count the encounters in cities A and B.

-----Examples-----
Input
10 30
10 35
05:20

Output
5

Input
60 120
24 100
13:00

Output
9

-----Note-----

In the first example Simion departs form the city A at 05:20 AM and arrives to the city B at 05:50 AM. He will meet the first 5 buses from the city B that departed in the period [05:00 AM - 05:40 AM]. Also Simion will meet a bus in the city B at 05:50 AM, but he will not count it.

Also note that the first encounter will be between 05:26 AM and 05:27 AM (if we suggest that the buses are go with the sustained speed).

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

a, t_a = list(map(int, input().split()))
b, t_b = list(map(int, input().split()))
h, m = list(map(int, input().split(':')))

time = h * 60 + m

start = time
end = time + t_a - 1
start_time = 300
end_time = start_time + t_b - 1

intersections = 0

while start_time <= 1439:
    if end >= start_time and end_time >= start:
        intersections += 1

    start_time += b
    end_time = start_time + t_b - 1

print(intersections)


I found an interesting problem on https://codeforces.com/problemset/problem/665/B:
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online.

The store contains k items. n customers have already used the above service. Each user paid for m items. Let a_{ij} denote the j-th item in the i-th person's order.

Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items a_{ij} (1 ≤ j ≤ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(a_{i}1) + pos(a_{i}2) + ... + pos(a_{im}) for the i-th customer.

When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.

Your task is to calculate the total time it takes for Ayush to process all the orders.

You can assume that the market has endless stock.

-----Input-----

The first line contains three integers n, m and k (1 ≤ n, k ≤ 100, 1 ≤ m ≤ k) — the number of users, the number of items each user wants to buy and the total number of items at the market.

The next line contains k distinct integers p_{l} (1 ≤ p_{l} ≤ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k.

Each of the next n lines contains m distinct integers a_{ij} (1 ≤ a_{ij} ≤ k) — the order of the i-th person.

-----Output-----

Print the only integer t — the total time needed for Ayush to process all the orders.

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

Output
14

-----Note-----

Customer 1 wants the items 1 and 5.

pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5].

pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2].

Time taken for the first customer is 3 + 5 = 8.

Customer 2 wants the items 3 and 1.

pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2].

pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2].

Time taken for the second customer is 3 + 3 =...

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

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

time = 0

for i in range(n):
    c = list(map(int, input().split()))
    for j in c:
        for k in range(len(a)):
            if a[k] == j:
                p = k
                break
        time += p + 1
        a = [j] + a[:k] + a[k + 1:]

print(time)


I found an interesting problem on https://codeforces.com/problemset/problem/665/D:
A tuple of positive integers {x_1, x_2, ..., x_{k}} is called simple if for all pairs of positive integers (i,  j) (1  ≤ i  <  j ≤ k), x_{i}  +  x_{j} is a prime.

You are given an array a with n positive integers a_1,  a_2,  ...,  a_{n} (not necessary distinct). You want to find a simple subset of the array a with the maximum size.

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 1000) — the number of integers in the array a.

The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6) — the elements of the array a.

-----Output-----

On the first line print integer m — the maximum possible size of simple subset of a.

On the second line print m integers b_{l} — the elements of the simple subset of the array a with the maximum size.

If there is more than one solution you can print any of them. You can print the elements of the subset in any order.

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

Output
2
3 2

Input
2
2 2

Output
1
2

Input
3
2 1 1

Output
3
1 1 2

Input
2
83 14

Output
2
14 83

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

n = int(input())
L = list(map(int, input().split()))
P = [-1 for _ in range(2000001)]

def premier(n):
    if P[n] >= 0:
        return P[n]
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            P[n] = False
            return False
    P[n] = True
    return True

e = L.count(1)
if n == 1:
    print(1)
    print(L[0])
elif e > 1:
    L.sort()
    i = 1
    while i < n and L[i] == 1:
        i += 1
    u = i
    ok = 0
    while i < n:
        if premier(L[i]+1):
            print(u+1)
            for j in range(u):
                print(1,end=" ")
            print(L[i])
            ok = 1
            break
        i += 1
    if ok == 0:
        print(u)
        for i in range(u):
            print(1,end=" ")
else:
    ok = 0
    for i in range(n-1):
        for j in range(i+1,n):
            t = premier(L[i]+L[j])
            if t:
                print(2)
                print(str(L[i])+" "+str(L[j]))
                ok = 1
                break
        if ok:
            break
    if ok == 0:
        print(1)
        print(L[0])


I found an interesting problem on https://codeforces.com/problemset/problem/666/A:
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.

For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction —  it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).

Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.

Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.

Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: [Image], where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.

-----Input-----

The only line contains a string s (5 ≤ |s| ≤ 10^4) consisting of lowercase English letters.

-----Output-----

On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes.

Print suffixes in lexicographical (alphabetical) order.

-----Examples-----
Input
abacabaca

Output
3
aca
ba
ca

Input
abaca

Output
0

-----Note-----

The first test was analysed in the problem statement.

In the second example the...

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

t = input()

s, d = set(), set()

p = {(len(t), 2)}

while p:

    m, x = p.pop()

    r = m + x

    for y in [x, 5 - x]:

        l = m - y

        q = (l, y)

        if q in d or l < 5 or t[l:m] == t[m:r]: continue

        s.add(t[l:m])

        d.add(q)

        p.add(q)

print(len(s))

print('\n'.join(sorted(s)))

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/667/B:
[Image]

As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.

A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.

Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length l_{i}.

The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle $180^{\circ}$.

Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.

Help sculptor!

-----Input-----

The first line contains an integer n (3 ≤ n ≤ 10^5) — a number of rod-blanks.

The second line contains n integers l_{i} (1 ≤ l_{i} ≤ 10^9) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.

-----Output-----

Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the...

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

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

xs.sort(reverse=True)

a = xs[0]
b = xs[1]

for i in xs[2:]:
    if a + i - b > b + i - a:
        b += i
    else:
        a += i

print(abs(a - b) + 1)