I found an interesting problem on https://codeforces.com/problemset/problem/873/A:
Luba has to do n chores today. i-th chore takes a_{i} units of time to complete. It is guaranteed that for every $i \in [ 2 . . n ]$ the condition a_{i} ≥ a_{i} - 1 is met, so the sequence is sorted.

Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a_{i} ($x < \operatorname{min}_{i = 1}^{n} a_{i}$).

Luba is very responsible, so she has to do all n chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.

-----Input-----

The first line contains three integers n, k, x (1 ≤ k ≤ n ≤ 100, 1 ≤ x ≤ 99) — the number of chores Luba has to do, the number of chores she can do in x units of time, and the number x itself.

The second line contains n integer numbers a_{i} (2 ≤ a_{i} ≤ 100) — the time Luba has to spend to do i-th chore.

It is guaranteed that $x < \operatorname{min}_{i = 1}^{n} a_{i}$, and for each $i \in [ 2 . . n ]$ a_{i} ≥ a_{i} - 1.

-----Output-----

Print one number — minimum time Luba needs to do all n chores.

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

Output
13

Input
5 2 1
100 100 100 100 100

Output
302

-----Note-----

In the first example the best option would be to do the third and the fourth chore, spending x = 2 time on each instead of a_3 and a_4, respectively. Then the answer is 3 + 6 + 2 + 2 = 13.

In the second example Luba can choose any two chores to spend x time on them instead of a_{i}. So the answer is 100·3 + 2·1 = 302.

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

R=lambda:list(map(int,input().split()))
n,k,x=R()
a=list(reversed(R()))
print(sum(x if i < k else a[i] for i in range(n)))


I found an interesting problem on https://codeforces.com/problemset/problem/873/B:
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string s_{l}s_{l} + 1s_{l} + 2... s_{r}, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.

You have to determine the length of the longest balanced substring of s.

-----Input-----

The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.

The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

-----Output-----

If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

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

Output
4

Input
3
111

Output
0

-----Note-----

In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.

In the second example it's impossible to find a non-empty balanced substring.

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

n = int(input())
x = input()
s = ''.join(['0', x, '1'])
s1 = ''.join(['1', x, '0'])
# s = input()

def get_max(s):
	net_count = 0
	current_max = 0
	mp = {}
	for (i, item) in enumerate(s):
		if item == '0':
			net_count -= 1
		elif item == '1':
			net_count += 1
		if (mp.get(net_count, None) == None):
			mp[net_count] = i
		else:
			dist = i - mp[net_count]
			if dist > current_max:
				current_max = dist
	return current_max

print(min(get_max(s), get_max(s1)))


I found an interesting problem on https://codeforces.com/problemset/problem/873/C:
Ivan is playing a strange game.

He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:

  Initially Ivan's score is 0;  In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that a_{i}, j = 1). If there are no 1's in the column, this column is skipped;  Ivan will look at the next min(k, n - i + 1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score.

Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.

-----Input-----

The first line contains three integer numbers n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100).

Then n lines follow, i-th of them contains m integer numbers — the elements of i-th row of matrix a. Each number is either 0 or 1.

-----Output-----

Print two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.

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

Output
4 1

Input
3 2 1
1 0
0 1
0 0

Output
2 0

-----Note-----

In the first example Ivan will replace the element a_{1, 2}.

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

def main():
  rows, cols, k = map(int, input().split())
  mat = [[0 for j in range(cols)] for i in range(rows)]
  is_one = [[False for j in range(cols)] for i in range(rows)]

  for i in range(rows):
    vals = list(map(int, input().split()))
    for j in range(cols):
      is_one[i][j] = vals[j] == 1
      mat[i][j] += vals[j]
      if i - k >= 0:
        mat[i - k][j] -= vals[j]

  for j in range(cols):
    for i in range(rows - 2, -1, -1):
      mat[i][j] += mat[i + 1][j]

  max_score = 0
  min_moves = 0

  for j in range(cols):
    score = 0
    moves = 0
    best_moves = 0

    for i in range(rows):
      if not is_one[i][j]:
        continue

      if mat[i][j] > score:
        score = mat[i][j]
        best_moves = moves
      moves += 1

    max_score += score
    min_moves += best_moves

  print(max_score, min_moves)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/873/D:
Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows:  If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l ≤ i < r - 1 a[i] ≤ a[i + 1]), then end the function call;  Let $\operatorname{mid} = \lfloor \frac{l + r}{2} \rfloor$;  Call mergesort(a, l, mid);  Call mergesort(a, mid, r);  Merge segments [l, mid) and [mid, r), making the segment [l, r) sorted in non-descending order. The merge algorithm doesn't call any other functions.

The array in this problem is 0-indexed, so to sort the whole array, you need to call mergesort(a, 0, n).

The number of calls of function mergesort is very important, so Ivan has decided to calculate it while sorting the array. For example, if a = {1, 2, 3, 4}, then there will be 1 call of mergesort — mergesort(0, 4), which will check that the array is sorted and then end. If a = {2, 1, 3}, then the number of calls is 3: first of all, you call mergesort(0, 3), which then sets mid = 1 and calls mergesort(0, 1) and mergesort(1, 3), which do not perform any recursive calls because segments (0, 1) and (1, 3) are sorted.

Ivan has implemented the program that counts the number of mergesort calls, but now he needs to test it. To do this, he needs to find an array a such that a is a permutation of size n (that is, the number of elements in a is n, and every integer number from [1, n] can be found in this array), and the number of mergesort calls when sorting the array is exactly k.

Help Ivan to find an array he wants!

-----Input-----

The first line contains two numbers n and k (1 ≤ n ≤ 100000, 1 ≤ k ≤ 200000) — the size of a desired permutation and the number of mergesort calls required to sort it.

-----Output-----

If a permutation of size n such that there will be exactly k calls of mergesort while sorting it doesn't exist, output  - 1. Otherwise output n integer numbers a[0], a[1], ..., a[n - 1] — the elements of a permutation that would...

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

# -*- coding: utf-8 -*-

import math
import collections
import bisect
import heapq
import time
import random

"""
created by shhuan at 2017/10/14 15:30

"""

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

if k & 1 == 0 or k > 2*n-1:
    print(-1)
else:
    a = [0] * n
    gs = (k-1)//2

    def unsort(l, r, v):
        if l == r-1:
            a[l] = v
        else:
            nonlocal gs
            if gs > 0:
                gs -= 1
                mid = (l+r)//2
                unsort(l, mid, v+r-mid)
                unsort(mid, r, v)
            else:
                for i in range(r-l):
                    a[l+i] = v+i

    unsort(0, n, 1)

    print(' '.join([str(x) for x in a]))


I found an interesting problem on https://codeforces.com/problemset/problem/875/C:
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.

Some long and uninteresting story was removed...

The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.

A word x_1, x_2, ..., x_{a} is not lexicographically greater than y_1, y_2, ..., y_{b} if one of the two following conditions holds:   a ≤ b and x_1 = y_1, ..., x_{a} = y_{a}, i.e. the first word is the prefix of the second word;  there is a position 1 ≤ j ≤ min(a, b), such that x_1 = y_1, ..., x_{j} - 1 = y_{j} - 1 and x_{j} < y_{j}, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.

For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.

Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.

Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered,...

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

from collections import defaultdict, deque

def main():
    n,m = map(int, input().split())
    cap = [None]*(m+1)
    same_cap = defaultdict(list)
    q = deque()

    def apply_cap(a, c):
        if cap[a] is not None:
            return cap[a] == c
        q.append((a,c))
        while q:
            b = q.pop()
            if b[1] == c:
                if cap[b[0]] is None:
                    cap[b[0]] = c
                    q.extend(same_cap[b[0]])
                    same_cap[b[0]] = []
                elif cap[b[0]]!=c:
                    return False

        return True

    def same(a,b):
        same_cap[b].append((a,True))
        same_cap[a].append((b,False))

        if cap[a] == False:
            return apply_cap(b, False)

        if cap[b] == True:
            return apply_cap(a, True)

        return True

    def process(p,c):
        lp = p[0]
        lc = c[0]
        for i in range(1, min(lp,lc)+1):
            if p[i]>c[i]:
                return apply_cap(p[i], True) and apply_cap(c[i], False)
            if p[i]<c[i]:
                return same(p[i], c[i])
        return lp<=lc

    p = list(map(int, input().split()))
    for i in range(n-1):
        c = list(map(int, input().split()))
        if not process(p, c):
            print ('No')
            break
        p = c
    else:
        print ('Yes')
        res = []
        for i,b in enumerate(cap):
            if b:
                res.append(i)
        print(len(res))
        print(' '.join(map(str,res)))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/876/A:
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's and Eeyore's house is b meters, between Owl's and Eeyore's house is c meters.

For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal n times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).

Winnie-the-Pooh does not like physical activity. He wants to have a meal n times, traveling minimum possible distance. Help him to find this distance.

-----Input-----

First line contains an integer n (1 ≤ n ≤ 100) — number of visits.

Second line contains an integer a (1 ≤ a ≤ 100) — distance between Rabbit's and Owl's houses.

Third line contains an integer b (1 ≤ b ≤ 100) — distance between Rabbit's and Eeyore's houses.

Fourth line contains an integer c (1 ≤ c ≤ 100) — distance between Owl's and Eeyore's houses.

-----Output-----

Output one number — minimum distance in meters Winnie must go through to have a meal n times.

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

Output
3

Input
1
2
3
5

Output
0

-----Note-----

In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2 + 1 = 3.

In the second test case Winnie...

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

n = int(input())
a = int(input())
b = int(input())
c = int(input())

count = 1
length = 0

x = 1

while count < n:
    count += 1
    if x == 1:
        if a < b:
            x = 2
            length += a
        else:
            x = 3
            length += b
    elif x == 2:
        if a < c:
            x = 1
            length += a
        else:
            x = 3
            length += c
    else:
        if b < c:
            x = 1
            length += b
        else:
            x = 2
            length += c
print(length)


I found an interesting problem on https://codeforces.com/problemset/problem/876/B:
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.

Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.

-----Input-----

First line contains three integers n, k and m (2 ≤ k ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers.

Second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the numbers in the multiset.

-----Output-----

If it is not possible to select k numbers in the desired way, output «No» (without the quotes).

Otherwise, in the first line of output print «Yes» (without the quotes). In the second line print k integers b_1, b_2, ..., b_{k} — the selected numbers. If there are multiple possible solutions, print any of them.

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

Output
Yes
1 4
Input
3 3 3
1 8 4

Output
No
Input
4 3 5
2 7 7 7

Output
Yes
2 7 7

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

n,k,m=map(int,input().split())
a=list(map(int,input().split()))
b=[]
for i in range(m):
    b.append([])
for i in range(len(a)):
    b[a[i]%m].append(a[i])
for i in range(len(b)):
    if len(b[i])>=k:
        j=0
        print('Yes')
        while j<k:
            print(b[i][j],end=' ')
            j+=1
        break
else:
    print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/876/F:
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :)

Rick and Morty like to go to the ridge High Cry for crying loudly — there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them.

Bitwise OR is a binary operation which is determined the following way. Consider representation of numbers x and y in binary numeric system (probably with leading zeroes) x = x_{k}... x_1x_0 and y = y_{k}... y_1y_0. Then z = x | y is defined following way: z = z_{k}... z_1z_0, where z_{i} = 1, if x_{i} = 1 or y_{i} = 1, and z_{i} = 0 otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers 10 = 1010_2 and 9 = 1001_2 equals 11 = 1011_2. In programming languages C/C++/Java/Python this operation is defined as «|», and in Pascal as «or».

Help Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs l and r (1 ≤ l < r ≤ n) such that bitwise OR of heights of all mountains between l and r (inclusive) is larger than the height of any mountain at this interval.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 200 000), the number of mountains in the ridge.

Second line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^9), the heights of mountains in order they are located in the ridge.

-----Output-----

Print the only integer, the number of ways to choose two different mountains.

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

Output
8

Input
4
3...

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

n = int(input())
a = [int(i) for i in input().split()]
l = [i for i in range(len(a))]
r = [i for i in range(len(a))]
for i in range(len(a)):
	while l[i]>=1 and a[i]|a[l[i]-1]<=a[i]:
		l[i] = l[l[i]-1]

for j in range(len(a)):
	i = len(a)-j-1
	while r[i]<len(a)-1 and a[i]|a[r[i]+1]<=a[i] and a[i]>a[r[i]+1]:
		r[i] = r[r[i]+1]

count=0
for i in range(len(a)):
	x = r[i]-i+1
	y = i-l[i]+1
	count+=x*y-1
print((n*(n-1))//2-count)


I found an interesting problem on https://codeforces.com/problemset/problem/877/A:
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.

But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.

It is known, that problem is from this contest if and only if its name contains one of Alex's friends' name exactly once. His friends' names are "Danil", "Olya", "Slava", "Ann" and "Nikita".

Names are case sensitive.

-----Input-----

The only line contains string from lowercase and uppercase letters and "_" symbols of length, not more than 100 — the name of the problem.

-----Output-----

Print "YES", if problem is from this contest, and "NO" otherwise.

-----Examples-----
Input
Alex_and_broken_contest

Output
NO
Input
NikitaAndString

Output
YES
Input
Danil_and_Olya

Output
NO

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

def cnt(string, substr):
    return len(string.split(substr)) - 1

string = input()
x = 0

for i in ['Danil', 'Olya', 'Slava', 'Ann', 'Nikita']:
    x += cnt(string, i)

if (x == 1):
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/877/B:
One day Nikita found the string containing letters "a" and "b" only.

Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".

Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?

-----Input-----

The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".

-----Output-----

Print a single integer — the maximum possible size of beautiful string Nikita can get.

-----Examples-----
Input
abba

Output
4
Input
bab

Output
2

-----Note-----

It the first sample the string is already beautiful.

In the second sample he needs to delete one of "b" to make it beautiful.

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/877/C:
Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map.

Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.

If a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell n can only move to the cell n - 1, a tank in the cell 1 can only move to the cell 2). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.

Help Slava to destroy all tanks using as few bombs as possible.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the size of the map.

-----Output-----

In the first line print m — the minimum number of bombs Slava needs to destroy all tanks.

In the second line print m integers k_1, k_2, ..., k_{m}. The number k_{i} means that the i-th bomb should be dropped at the cell k_{i}.

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

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

Output
3
2 1 2
Input
3

Output
4
2 1 3 2

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

import math;
n = int(input());

m = n + math.floor(n/2);

print(m);
for i in range(2, n+1, 2):
    print(i, end = " ");
for i in range(1, n+1, 2):
    print(i, end = " ");
for i in range(2, n+1, 2):
    print(i, end = " ");


I found an interesting problem on https://codeforces.com/problemset/problem/877/D:
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.

Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans.

Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.

Now Olya needs to get from cell (x_1, y_1) to cell (x_2, y_2). How many seconds will it take her if she moves optimally?

It's guaranteed that cells (x_1, y_1) and (x_2, y_2) are empty. These cells can coincide.

-----Input-----

The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 1000) — the sizes of the room and Olya's speed.

Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.

The last line contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — the coordinates of the first and the last cells.

-----Output-----

Print a single integer — the minimum time it will take Olya to get from (x_1, y_1) to (x_2, y_2).

If it's impossible to get from (x_1, y_1) to (x_2, y_2), print -1.

-----Examples-----
Input
3 4 4
....
###.
....
1 1 3 1

Output
3
Input
3 4 1
....
###.
....
1 1 3 1

Output
8
Input
2 2 1
.#
#.
1 1 2 2

Output
-1

-----Note-----

In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.

In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.

Olya does not recommend drinking energy drinks and generally believes that this is bad.

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

from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
n,m,k=list(map(int,input().split()))
dp=[[float("infinity") for i in range(m)] for i in range(n)]
l=[]
for i in range(n):
	l.append(list(input()))
x1,y1,x2,y2=[int(a)-1 for a in input().split()]
t=[(1,0),(0,1),(0,-1),(-1,0)]
q=deque()
q.append((x1,y1))
dp[x1][y1]=0
while q:
	x,y=q.popleft()
	if x==x2 and y==y2:
		# print(90)
		break
	for a,b in t:
		for i in range(1,k+1):
			e=x+i*a
			f=y+i*b
			if e<0 or e>=n or f>=m or f<0 or l[e][f]!="." or dp[e][f]<dp[x][y]+1:
				# print(e,f)
				break
			else:
				if dp[e][f]>dp[x][y]+1:
					dp[e][f]=dp[x][y]+1
					q.append((e,f))
	# print(q)
ans=dp[x2][y2]
if ans==float("infinity"):
	ans=-1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/879/A:
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.

Doctors have a strange working schedule. The doctor i goes to work on the s_{i}-th day and works every d_{i} day. So, he works on days s_{i}, s_{i} + d_{i}, s_{i} + 2d_{i}, ....

The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

-----Input-----

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).

Next n lines contain two numbers s_{i} and d_{i} (1 ≤ s_{i}, d_{i} ≤ 1000).

-----Output-----

Output a single integer — the minimum day at which Borya can visit the last doctor.

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

Output
4

Input
2
10 1
6 5

Output
11

-----Note-----

In the first sample case, Borya can visit all doctors on days 2, 3 and 4.

In the second sample case, Borya can visit all doctors on days 10 and 11.

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

n = int(input())
ans = 0
for i in range(n):
	s, d = list(map(int, input().split()))
	visit = s
	while visit <= ans:
		visit += d
	ans = visit
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/879/B:
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.

For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.

-----Input-----

The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 10^12) — the number of people and the number of wins.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all a_{i} are distinct.

-----Output-----

Output a single integer — power of the winner.

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

Output
2
Input
4 2
3 1 2 4

Output
3
Input
6 2
6 5 3 1 2 4

Output
6
Input
2 10000000000
2 1

Output
2

-----Note-----

Games in the second sample:

3 plays with 1. 3 wins. 1 goes to the end of the line.

3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.

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

def ii():
    return int(input())
def mi():
    return map(int, input().split())
def li():
    return list(mi())

n, k = mi()
a = li()

from collections import deque
q = deque(a)

c = q.popleft()
w = 0
while 1:
    x = q.popleft()
    if c > x:
        w += 1
        if w >= k or w >= n:
            ans = c
            break
        q.append(x)
    else:
        q.append(c)
        c = x
        w = 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/879/D:
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city a_{i}.

Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a_1, a_2, ..., a_{n} repeated m times).

After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.

Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.

-----Input-----

The first line contains three integers n, k and m (1 ≤ n ≤ 10^5, 2 ≤ k ≤ 10^9, 1 ≤ m ≤ 10^9).

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5), where a_{i} is the number of city, person from which must take seat i in the bus.

-----Output-----

Output the number of remaining participants in the line.

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

Output
12

Input
1 9 10
1

Output
1

Input
3 2 10
1 2 1

Output
0

-----Note-----

In the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.

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

def main():
    _, k, m = [int(x) for x in input().split()]
    a = []
    last = ("-1", 0)
    a.append(last)
    for ai in input().split():
        if last[0] == ai:
            last = (ai, last[1]+1)
            a[-1] = last
        else:
            last = (ai, 1)
            a.append(last)

        if last[1] == k:
            a.pop()
            last = a[-1]
    a.pop(0)

    s1 = 0
    while len(a) > 0 and a[0][0] == a[-1][0]:
        if len(a) == 1:
            s = a[0][1] * m
            r1 = s % k
            if r1 == 0:
                print(s1 % k)
            else:
                print(r1 + s1)
            return
        join = a[0][1] + a[-1][1]

        if join < k:
            break
        elif join % k == 0:
            s1 += join
            a.pop()
            a.pop(0)
        else:
            s1 += (join // k) * k
            a[0] = (a[0][0], join % k)
            a.pop()
            break

    s = 0
    for ai in a:
        s += ai[1]

    print(s*m + s1)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/883/E:
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.

The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).

Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.

At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.

It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.

Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 50) — the length of the hidden word.

The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed.

The third line contains an integer m (1 ≤ m ≤ 1000) — the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves — n-letter strings of lowercase Latin...

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

n = int(input())
s = input()
m = int(input())
l = []
cnt_ = []
cnt = []
for i in range(n):
	if s[i]=='*':
		cnt_.append(i)
	else: cnt.append(i)
for x in range(m):
	flag = True
	st = input()
	for j in cnt_:
		if st[j] in s:
			flag = False
	else:
		for j in cnt:
			if st[j]!=s[j]: flag =False
	if flag:
		l.append(st)
g = [[] for i in range(len(l))]
for i in range(len(l)):
	for j in cnt_:
		g[i].append(l[i][j])
for i in range(len(g)):
	g[i] = list(set(g[i]))
ans = 0
for ch in g[0]:
	for li in g:
		if ch not in li: break
	else: ans = ans+1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/883/G:
Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.

Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:

  to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s;  to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s.

In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans.

Help Vasya find the plans.

-----Input-----

The first line contains three integers n, m and s (2 ≤ n ≤ 3·10^5, 1 ≤ m ≤ 3·10^5, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked.

The following m lines contain information about the graph edges. Each line contains three integers t_{i}, u_{i} and v_{i} (1 ≤ t_{i} ≤ 2, 1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — edge type and vertices connected by the edge. If t_{i} = 1 then the edge is directed and goes from the vertex u_{i} to the vertex v_{i}. If t_{i} = 2 then the edge is undirected and it connects the vertices u_{i} and v_{i}.

It is guaranteed that there is at least one undirected edge in the graph.

-----Output-----

The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices.

A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input.

If there are multiple...

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

import sys
input = sys.stdin.readline

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

def dfs0(x):
  s = [x]
  vis = [0] * n
  ans = ['+'] * m
  vis[x] = 1
  while s:
    i = s.pop()
    for j, k in graph[i]:
      if (vis[j] == 0):
        if (k < 0):
          ans[-k - 1] = '-'
        elif (k > 0):
          ans[k - 1] = '+'

        s.append(j)
        vis[j] = 1

  return ''.join(ans), sum(vis)

def dfs1(x):
  s = [x]
  vis = [0] * n
  ans = ['+'] * m
  vis[x] = 1
  while s:
    i = s.pop()
    for j, k in graph[i]:
      if (vis[j] == 0):
        if (k < 0):
          ans[-k - 1] = '+'
        elif (k > 0):
          ans[k - 1] = '-'
        if (k == 0):
          s.append(j)
          vis[j] = 1

  return ''.join(ans), sum(vis)

n,m,s = put()
graph = [[] for i in range(n)]

k = 1

for _ in range(m):
  z,x,y = put()
  x,y = x - 1, y - 1
  if (z == 1):
    graph[x].append((y, 0))
  else:
    graph[x].append((y, k))
    graph[y].append((x, -k))
    k += 1

m = k - 1
x, y = dfs0(s - 1)
print(y)
print(x)
x, y = dfs1(s - 1)
print(y)
print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/883/H:
Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.

He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.

Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 4·10^5) — the length of string s.

The second line contains a string s of length n consisting of lowercase and uppercase Latin letters and digits.

-----Output-----

Print to the first line an integer k — minimum number of palindromes into which you can cut a given string.

Print to the second line k strings — the palindromes themselves. Separate them by a space. You are allowed to print palindromes in arbitrary order. All of them should have the same length.

-----Examples-----
Input
6
aabaac

Output
2
aba aca
Input
8
0rTrT022

Output
1
02TrrT20
Input
2
aA

Output
2
a A

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

n=int(input())
s=list(input())
lets={}
for i in s:
    try:
        lets[i]+=1
    except:
        lets[i]=1
count=0
centre=[]
rest=[]
for i in lets.keys():
    if(lets[i]%2):
        centre.append(i)
        count+=1
    rest+=[i]*(lets[i]//2)
if(count==0):
    t=''
    for i in lets.keys():
        t=i*(lets[i]//2) + t + i*(lets[i]//2)
    print(1)
    print(t)

else:
    extra=0
    while(n%count!=0 or (n//count)%2==0):
        count+=2
        extra+=1
    for i in range(extra):
        centre+=[rest.pop()]*2
    amt=len(rest)//(count)
    temp=rest.copy()
    rest=''
    for i in temp:
        rest+=i
    print(count)
    print(rest[0:amt] + centre[0] + rest[(1)*(amt)-1::-1],end=' ')
    for i in range(1,count):
        print(rest[i*(amt):(i+1)*amt] + centre[i] + rest[(i+1)*(amt)-1:(i)*amt-1:-1],end=' ')
    print()


I found an interesting problem on https://codeforces.com/problemset/problem/883/K:
Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!

The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time on the street.

The street is split into n equal length parts from left to right, the i-th part is characterized by two integers: width of road s_{i} and width of lawn g_{i}. [Image]

For each of n parts the Mayor should decide the size of lawn to demolish. For the i-th part he can reduce lawn width by integer x_{i} (0 ≤ x_{i} ≤ g_{i}). After it new road width of the i-th part will be equal to s'_{i} = s_{i} + x_{i} and new lawn width will be equal to g'_{i} = g_{i} - x_{i}.

On the one hand, the Mayor wants to demolish as much lawn as possible (and replace it with road). On the other hand, he does not want to create a rapid widening or narrowing of the road, which would lead to car accidents. To avoid that, the Mayor decided that width of the road for consecutive parts should differ by at most 1, i.e. for each i (1 ≤ i < n) the inequation |s'_{i} + 1 - s'_{i}| ≤ 1 should hold. Initially this condition might not be true.

You need to find the the total width of lawns the Mayor will destroy according to his plan.

-----Input-----

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

Each of the following n lines contains two integers s_{i}, g_{i} (1 ≤ s_{i} ≤ 10^6, 0 ≤ g_{i} ≤ 10^6) — current width of road and width of the lawn on the i-th part of the street.

-----Output-----

In the first line print the total width of lawns which will be removed.

In the second line print n integers s'_1, s'_2, ..., s'_{n} (s_{i} ≤ s'_{i} ≤ s_{i} + g_{i}) — new widths of the road starting from the first part and to the last.

If there is no solution, print the only integer -1 in the first line.

-----Examples-----
Input
3
4 5
4 5
4 10

Output
16
9 9 10

Input
4
1 100
100 1
1...

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


I found an interesting problem on https://codeforces.com/problemset/problem/883/M:
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should:

  start the race from some point of a field,  go around the flag,  close cycle returning back to the starting point.

Polycarp knows the coordinates of the starting point (x_1, y_1) and the coordinates of the point where the flag is situated (x_2, y_2). Polycarp’s quadcopter can fly only parallel to the sides of the field each tick changing exactly one coordinate by 1. It means that in one tick the quadcopter can fly from the point (x, y) to any of four points: (x - 1, y), (x + 1, y), (x, y - 1) or (x, y + 1).

Thus the quadcopter path is a closed cycle starting and finishing in (x_1, y_1) and containing the point (x_2, y_2) strictly inside.

 [Image] The picture corresponds to the first example: the starting (and finishing) point is in (1, 5) and the flag is in (5, 2).

What is the minimal length of the quadcopter path?

-----Input-----

The first line contains two integer numbers x_1 and y_1 ( - 100 ≤ x_1, y_1 ≤ 100) — coordinates of the quadcopter starting (and finishing) point.

The second line contains two integer numbers x_2 and y_2 ( - 100 ≤ x_2, y_2 ≤ 100) — coordinates of the flag.

It is guaranteed that the quadcopter starting point and the flag do not coincide.

-----Output-----

Print the length of minimal path of the quadcopter to surround the flag and return back.

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

Output
18

Input
0 1
0 0

Output
8

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

a, b = input().split()
a, b = int(a), int(b)
c, d = input().split()
c, d = int(c), int(d)

if abs(a - c) == 0:
    print(2 * abs(b - d) + 6)
elif abs(b - d) == 0:
    print(2 * abs(a - c) + 6)
else:
    print(2 * abs(a - c) + 2 * abs(b-d) + 4)


I found an interesting problem on https://codeforces.com/problemset/problem/884/A:
Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.

But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is a_{i}. If some free time remains, she can spend it on reading.

Help Luba to determine the minimum number of day when she finishes reading.

It is guaranteed that the answer doesn't exceed n.

Remember that there are 86400 seconds in a day.

-----Input-----

The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 10^6) — the number of days and the time required to read the book.

The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 86400) — the time Luba has to spend on her work during i-th day.

-----Output-----

Print the minimum day Luba can finish reading the book.

It is guaranteed that answer doesn't exceed n.

-----Examples-----
Input
2 2
86400 86398

Output
2

Input
2 86400
0 86400

Output
1

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

n,t = list(map(int,input().split()))
data = list(map(int,input().split()))
s=0
new=[]
for i in data:
    s+=(86400-i)
    new.append(s)
for i in range(n):
    if new[i]>=t:
        print(i+1)
        break
else:
    print(n)


I found an interesting problem on https://codeforces.com/problemset/problem/884/B:
A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and a_{i} is the length of i-th segment. No two segments touch or intersect.

For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array.

Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

-----Input-----

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 10^9) — the number of elements in the encoding and the length of the crossword Mishka picked.

The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10000) — the encoding.

-----Output-----

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

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

Output
NO

Input
3 10
3 3 2

Output
YES

Input
2 10
1 3

Output
NO

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

n,t = list(map(int,input().split()))
data = list(map(int,input().split()))
s=sum(data)
print('YES' if t==n-1+s else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/884/C:
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.

There are n stations in the subway. It was built according to the Bertown Transport Law:

  For each station i there exists exactly one train that goes from this station. Its destination station is p_{i}, possibly p_{i} = i;  For each station i there exists exactly one station j such that p_{j} = i.

The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).

The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of p_{i} for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.

The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.

The second line contains n integer numbers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the current structure of the subway. All these numbers are distinct.

-----Output-----

Print one number — the maximum possible value of convenience.

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

Output
9

Input
5
1 5 4 3 2

Output
17

-----Note-----

In the first example the mayor can change p_2 to 3 and p_3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).

In the second example the mayor can change p_2 to 4 and p_3 to 5.

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

n = int(input())
ps = list(map(lambda x: int(x)-1, input().split()))

sum = 0
maxest_pipe = 0
max_pipe = 0

free_points = set(range(n))
free_points.remove(0)
start_point = 0
current_point = 0
steps = 0
while True:
    steps += 1
    next_point = ps[current_point]
    if next_point in free_points:
        free_points.remove(next_point)
    if next_point == start_point:

        sum += steps * steps
        if steps > maxest_pipe:
            max_pipe = maxest_pipe
            maxest_pipe = steps
        elif steps > max_pipe:
            max_pipe = steps
        steps = 0
        if len(free_points) > 0:
            current_point = free_points.pop()
            start_point = current_point
        else:
            break
    else:
        current_point = next_point

print(sum - max_pipe*max_pipe - maxest_pipe*maxest_pipe + (max_pipe+maxest_pipe)*(max_pipe+maxest_pipe))


I found an interesting problem on https://codeforces.com/problemset/problem/884/D:
Ivan has n different boxes. The first of them contains some balls of n different colors.

Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.

In order to do this, Ivan will make some turns. Each turn he does the following:  Ivan chooses any non-empty box and takes all balls from this box;  Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.

The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.

Help Ivan to determine the minimum possible penalty of the game!

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.

The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the number of balls with color i.

-----Output-----

Print one number — the minimum possible penalty of the game.

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

Output
6

Input
4
2 3 4 5

Output
19

-----Note-----

In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.

In the second example you make two turns:   Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;  Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.

Total penalty is 19.

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

import heapq
n=int(input())
array=input().split()
fin=[]
for i in array:
    fin.append(int(i))
if(len(fin)%2==0):
    fin.append(0)

heapq.heapify(fin)
sums=0
while(len(fin)>1):
    temp=0
    a=heapq.heappop(fin)
    b=heapq.heappop(fin)
    c=heapq.heappop(fin)
    temp=a+b+c
    sums+=temp
    heapq.heappush(fin,temp)
print(sums)


I found an interesting problem on https://codeforces.com/problemset/problem/884/F:
A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) a_{i} ≠ a_{m} - i + 1.

Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as b_{i}, and the beauty of t as the sum of b_{i} among all indices i such that s_{i} = t_{i}.

Help Ivan to determine maximum possible beauty of t he can get.

-----Input-----

The first line contains one integer n (2 ≤ n ≤ 100, n is even) — the number of characters in s.

The second line contains the string s itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string.

The third line contains n integer numbers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the beauty of index i.

-----Output-----

Print one number — the maximum possible beauty of t.

-----Examples-----
Input
8
abacabac
1 1 1 1 1 1 1 1

Output
8

Input
8
abaccaba
1 2 3 4 5 6 7 8

Output
26

Input
8
abacabca
1 2 3 4 4 3 2 1

Output
17

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

from collections import *
n = int(input())
s = input()
b = [int (i) for i in input().split(' ')]
n = n
cnt = defaultdict(int)
multiples = []
biggest = 'a'
ans = 0
for i in range(n//2):
    if(s[i] == s[n-i-1]):
        multiples.append(i)
        cnt[s[i]] += 1
        ans += max(b[i],b[n-i-1])
    else:
        ans += b[i] + b[n-i-1]

for i in range(26):
    if(cnt[chr(ord('a')+i)] > cnt[biggest]):
        biggest = chr(ord('a')+i)
more = max(max(cnt.values())*2-sum(cnt.values()),0)
# print(more)
takes = []
for i in range(n//2):
    if(s[i] != s[n-i-1] and s[i] != biggest and s[n-i-1] != biggest):
        takes.append(min(b[i],b[n-i-1]))

takes = sorted(takes)[:more]
pen = sum(takes)
# print(pen)
# print(takes)
print(ans-pen)


I found an interesting problem on https://codeforces.com/problemset/problem/886/A:
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.

After practice competition, participant number i got a score of a_{i}. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.

-----Input-----

The single line contains six integers a_1, ..., a_6 (0 ≤ a_{i} ≤ 1000) — scores of the participants

-----Output-----

Print "YES" (quotes for clarity), if it is possible to build teams with equal score, and "NO" otherwise.

You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

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

Output
YES

Input
1 1 1 1 1 99

Output
NO

-----Note-----

In the first sample, first team can be composed of 1st, 2nd and 6th participant, second — of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5.

In the second sample, score of participant number 6 is too high: his team score will be definitely greater.

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

arr = list(map(int, input().split()))
flag = 0
s = sum(arr)
for i in range(4):
    for j in range(i + 1, 5):
        for k in range(j + 1, 6):
            h = arr[i] + arr[j] + arr[k]
            if s - h == h:
                print("YES")
                flag = 1
                break
        if flag == 1:
            break
    if flag == 1:
        break
if (flag == 0):
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/886/B:
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.

First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.

-----Input-----

In first line there is one integer n (1 ≤ n ≤ 2·10^5) — number of cafes indices written by Vlad.

In second line, n numbers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 2·10^5) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.

-----Output-----

Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.

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

Output
3

Input
6
2 1 2 2 4 1

Output
2

-----Note-----

In first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer.

In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.

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

def main():
    read = lambda: tuple(map(int, input().split()))
    n = read()[0]
    l = read()
    last = {}
    for i in range(n):
        last[l[i]] = i
    mn = 1e10
    ans = -1
    for k in last:
        if last[k] < mn:
            ans = k
            mn = last[k]
    print(ans)
main()


I found an interesting problem on https://codeforces.com/problemset/problem/886/C:
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.

Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number t_{i}:   If Petya has visited this room before, he writes down the minute he was in this room last time;  Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.

Initially, Petya was in one of the rooms at minute 0, he didn't write down number t_0.

At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — then number of notes in Petya's logbook.

The second line contains n non-negative integers t_1, t_2, ..., t_{n} (0 ≤ t_{i} < i) — notes in the logbook.

-----Output-----

In the only line print a single integer — the minimum possible number of rooms in Paris catacombs.

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

Output
2

Input
5
0 1 0 1 3

Output
3

-----Note-----

In the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2.

In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 1.

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

i = int(input())
ctc = [0] + list(map(int, input().split()))
nm = 1
ptor = {0:1}
for i in range(1, len(ctc)):
    if  ctc[i] in list(ptor.keys()):
        ptor[i] = ptor[ctc[i]]
        del(ptor[ctc[i]])
    else:
        nm+=1
        ptor[i] = nm
print(nm)


I found an interesting problem on https://codeforces.com/problemset/problem/886/D:
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.

You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).

A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.

The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.

String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the number of strings in the set.

Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct.

The total length of the strings doesn't exceed 10^5.

-----Output-----

Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.

-----Examples-----
Input
4
mail
ai
lru
cf

Output
cfmailru

Input
3
kek
preceq
cheburek

Output
NO

-----Note-----

One can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.

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

u, v, d = {}, {}, set()
for i in range(int(input())):
    t = input()
    if len(t) == 1: d.add(t)
    for a, b in zip(t, t[1:]):
        if u.get(a, b) != b or v.get(b, a) != a: print('NO');return
        u[a], v[b] = b, a
x, y = set(u), set(v)
d = d - x - y
for q in x - y:
    while q[-1] in u: q += u.pop(q[-1])
    d.add(q)
if u: print('NO');return
print(''.join(sorted(d)))


I found an interesting problem on https://codeforces.com/problemset/problem/886/F:
You are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines.

Multiset is a set where equal elements are allowed.

Multiset is called symmetric, if there is a point P on the plane such that the multiset is centrally symmetric in respect of point P.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 2000) — the number of points in the set.

Each of the next n lines contains two integers x_{i} and y_{i} ( - 10^6  ≤  x_{i},  y_{i}  ≤  10^6) — the coordinates of the points. It is guaranteed that no two points coincide.

-----Output-----

If there are infinitely many good lines, print -1.

Otherwise, print single integer — the number of good lines.

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

Output
3

Input
2
4 3
1 2

Output
-1

-----Note-----

Picture to the first sample test:

[Image]

In the second sample, any line containing the origin is good.

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

from fractions import Fraction
import time

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def to_tuple(self):
        return (self.x, self.y)

    def __repr__(self):
        return "Point({}, {})".format(self.x, self.y)

    def __eq__(self, other):
        return self.to_tuple() == other.to_tuple()

    def __hash__(self):
        return hash(self.to_tuple())

    def __neg__(self):
        return Point(-self.x, -self.y)

    def __add__(self, other):
        return Point(self.x+other.x, self.y+other.y)

    def __sub__(self, other):
        return self+(-other)

    def scalar_mul(self, mu):
        return Point(mu*self.x, mu*self.y)

    def int_divide(self, den):
        return Point(self.x//den, self.y//den)

class Line:
    def __init__(self, a, b, c):
        # ax+by+c=0
        self.a = a
        self.b = b
        self.c = c

    def __repr__(self):
        return "{}*x + {}*y + {} = 0".format(self.a, self.b, self.c)

    @classmethod
    def between_two_points(cls, P, Q):
        return cls(P.y-Q.y, Q.x-P.x, P.x*Q.y-P.y*Q.x)

    def evaluate(self, P):
        return self.a*P.x+self.b*P.y+self.c

    def direction(self):
        if self.a == 0:
            return (0, 1)
        return (1, Fraction(self.b, self.a))

true_start = time.time()
n = int(input())
points = set()
center = Point(0, 0)
for i in range(n):
    row = input().split(" ")
    cur = Point(int(row[0]), int(row[1])).scalar_mul(2*n)
    center += cur
    points.add(cur)

center = center.int_divide(n)
dcenter = center+center

sym_points_set = set()
for p in points:
    sym_points_set.add(dcenter-p)
nosym = list(points - sym_points_set)

if len(nosym) == 0:
    print(-1)
    return

cnt = 0
p0 = nosym[0]
good_lines = set()
for p in nosym:
    m = (p+p0).int_divide(2)
    line = Line.between_two_points(m, center)
    distances = list(map(line.evaluate, nosym))

    ok = True
    mydict = {}
    for dd in distances:
        dda = abs(dd)
        if dda not in mydict:
            mydict[dda] = 1
 ...


I found an interesting problem on https://codeforces.com/problemset/problem/887/A:
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.

Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.

-----Input-----

In the only line given a non-empty binary string s with length up to 100.

-----Output-----

Print «yes» (without quotes) if it's possible to remove digits required way and «no» otherwise.

-----Examples-----
Input
100010001

Output
yes
Input
100

Output
no

-----Note-----

In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.

You can read more about binary numeral system representation here: https://en.wikipedia.org/wiki/Binary_system

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

# -*- coding: utf-8 -*-

import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys

"""
created by shhuan at 2017/11/4 00:05

"""

S = input()

for i in range(len(S)):
    if S[i] == '1':
        if S[i:].count('0') >= 6:
            print('yes')
            return
print('no')


I found an interesting problem on https://codeforces.com/problemset/problem/887/B:
Absent-minded Masha got set of n cubes for her birthday.

At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x.

To make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number.

The number can't contain leading zeros. It's not required to use all cubes to build a number.

Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations.

-----Input-----

In first line integer n is given (1 ≤ n ≤ 3) — the number of cubes, Masha got for her birthday.

Each of next n lines contains 6 integers a_{i}_{j} (0 ≤ a_{i}_{j} ≤ 9) — number on j-th face of i-th cube.

-----Output-----

Print single integer — maximum number x such Masha can make any integers from 1 to x using her cubes or 0 if Masha can't make even 1.

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

Output
87
Input
3
0 1 3 5 6 8
1 2 4 5 7 8
2 3 4 6 7 9

Output
98

-----Note-----

In the first test case, Masha can build all numbers from 1 to 87, but she can't make 88 because there are no two cubes with digit 8.

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

n = int(input())
cs = []
for i in range(n):
    cs.append([int(x) for x in input().split()])

ans = 0

def can_make(num, cs):
    if num == 0:
        return True
    elif len(cs) == 0:
        return False
    cm = False
    for i in range(len(cs)):
        if num%10 in cs[i]:
            if can_make(num//10, cs[0:i]+cs[i+1:]):
                return True
    return False

for i in range(1,1000):
    if can_make(i, cs):
        ans = i
    else:
        break

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/887/C:
During the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2.

It's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation of one face of the cube in any direction.

To check her answers she wants to use a program which will for some state of cube tell if it's possible to solve it using one rotation, described above.

Cube is called solved if for each face of cube all squares on it has the same color.

https://en.wikipedia.org/wiki/Rubik's_Cube

-----Input-----

In first line given a sequence of 24 integers a_{i} (1 ≤ a_{i} ≤ 6), where a_{i} denotes color of i-th square. There are exactly 4 occurrences of all colors in this sequence.

-----Output-----

Print «YES» (without quotes) if it's possible to solve cube using one rotation and «NO» (without quotes) otherwise.

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

Output
NO
Input
5 3 5 3 2 5 2 5 6 2 6 2 4 4 4 4 1 1 1 1 6 3 6 3

Output
YES

-----Note-----

In first test case cube looks like this: [Image]

In second test case cube looks like this:  [Image]

It's possible to solve cube by rotating face with squares with numbers 13, 14, 15, 16.

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/888/A:
You are given an array a. Some element of this array a_{i} is a local minimum iff it is strictly less than both of its neighbours (that is, a_{i} < a_{i} - 1 and a_{i} < a_{i} + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, a_{i} > a_{i} - 1 and a_{i} > a_{i} + 1). Since a_1 and a_{n} have only one neighbour each, they are neither local minima nor local maxima.

An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.

-----Input-----

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

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000) — the elements of array a.

-----Output-----

Print the number of local extrema in the given array.

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

Output
0

Input
4
1 5 2 5

Output
2

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

n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(1,n-1):
    if (a[i-1] > a[i] and a[i] < a[i+1]) or (a[i-1] < a[i] and a[i] > a[i+1]):
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/888/B:
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform:  U — move from the cell (x, y) to (x, y + 1);  D — move from (x, y) to (x, y - 1);  L — move from (x, y) to (x - 1, y);  R — move from (x, y) to (x + 1, y).

Ivan entered a sequence of n commands, and the robot processed it. After this sequence the robot ended up in the starting cell (0, 0), but Ivan doubts that the sequence is such that after performing it correctly the robot ends up in the same cell. He thinks that some commands were ignored by robot. To acknowledge whether the robot is severely bugged, he needs to calculate the maximum possible number of commands that were performed correctly. Help Ivan to do the calculations!

-----Input-----

The first line contains one number n — the length of sequence of commands entered by Ivan (1 ≤ n ≤ 100).

The second line contains the sequence itself — a string consisting of n characters. Each character can be U, D, L or R.

-----Output-----

Print the maximum possible number of commands from the sequence the robot could perform to end up in the starting cell.

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

Output
4

Input
5
RRRUU

Output
0

Input
6
LLRRRR

Output
4

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

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

count=min(s.count('U'),s.count('D'))+min(s.count('L'),s.count('R'))
print(count*2)


I found an interesting problem on https://codeforces.com/problemset/problem/888/C:
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.

You have to find minimum k such that there exists at least one k-dominant character.

-----Input-----

The first line contains string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 100000).

-----Output-----

Print one number — the minimum value of k such that there exists at least one k-dominant character.

-----Examples-----
Input
abacaba

Output
2

Input
zzzzz

Output
1

Input
abcde

Output
3

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

s = '!' + input()

m = set(s)
d = {}
d1 = {}
for x in range(1, len(s)):
    if not s[x] in d:
        d[s[x]] = x
    else:
        d[s[x]] = max(d[s[x]], x - s[:x].rindex(s[x]))
    d1[s[x]] = x

for (x, y) in list(d.items()):
    d[x] = max(d[x], len(s) - d1[x])

print(min(d.values()))


I found an interesting problem on https://codeforces.com/problemset/problem/888/D:
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.

Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≤ i ≤ n) such that p_{i} = i.

Your task is to count the number of almost identity permutations for given numbers n and k.

-----Input-----

The first line contains two integers n and k (4 ≤ n ≤ 1000, 1 ≤ k ≤ 4).

-----Output-----

Print the number of almost identity permutations for given n and k.

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

Output
1

Input
4 2

Output
7

Input
5 3

Output
31

Input
5 4

Output
76

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

def factorial(k):
    ans = 1
    for i in range(1, k+1):
        ans *= i
    return ans

n, k = list(map(int, input().split()))
ans = 0;
def A(n, m):
    ans = 1
    for x in range(m + 1, n+1):
        ans *= x
    return ans

for i in range(2, k+1):
    si = 0
    for j in range(2, i+1):
        coeff = -1 if j%2 else 1
        si += coeff/factorial(j)
    ans += A(n, n-i)*si

print(int(ans + 1.5))


I found an interesting problem on https://codeforces.com/problemset/problem/888/E:
You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b_1, b_2, ..., b_{k} (1 ≤ b_1 < b_2 < ... < b_{k} ≤ n) in such a way that the value of $\sum_{i = 1}^{k} a_{b_{i}} \operatorname{mod} m$ is maximized. Chosen sequence can be empty.

Print the maximum possible value of $\sum_{i = 1}^{k} a_{b_{i}} \operatorname{mod} m$.

-----Input-----

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

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

-----Output-----

Print the maximum possible value of $\sum_{i = 1}^{k} a_{b_{i}} \operatorname{mod} m$.

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

Output
3

Input
3 20
199 41 299

Output
19

-----Note-----

In the first example you can choose a sequence b = {1, 2}, so the sum $\sum_{i = 1}^{k} a_{b_{i}}$ is equal to 7 (and that's 3 after taking it modulo 4).

In the second example you can choose a sequence b = {3}.

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

n,m=list(map(int,input().split()))
l=[int(i) for i in input().split()]
first=l[:n//2]
sec=l[n//2:]
n1=n//2
n2=n//2+n%2
t1=(1<<n1)
t2=(1<<n2)
s1=[]
for i in range(t1):
    now=0
    for j in range(len(first)):
        if i&(1<<j):
            now+=first[j]
    s1.append(now%m)
s2=[]
for i in range(t2):
    now= 0
    for j in range(len(sec)):
        if i&(1<<j):
            now+=sec[j]
    s2.append(now%m)
s1.sort()
s2.sort()
maxi=0
def check(l,x): #largest number less than x in l  # l is asc
    lo=0
    hi=len(l)-1
    ans=0
    while lo<=hi:
        mi=(lo+hi)>>1
        if l[mi]<x:
            ans=l[mi]
            lo=mi+1
        else:
            hi=mi-1
    return ans
for i in s1:
    req=m-i
    pair=check(s2,req)
    maxi=max(maxi,(i+pair)%m)
print(maxi)


I found an interesting problem on https://codeforces.com/problemset/problem/888/F:
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).

But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).

How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 10^9 + 7.

-----Input-----

The first line contains one number n (3 ≤ n ≤ 500) — the number of marked points.

Then n lines follow, each containing n elements. a_{i}, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise a_{i}, j = 0). It is guaranteed that for any pair of points a_{i}, j = a_{j}, i, and for any point a_{i}, i = 0.

-----Output-----

Print the number of ways to connect points modulo 10^9 + 7.

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

Output
1

Input
4
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

Output
12

Input
3
0 0 0
0 0 1
0 1 0

Output
0

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

import sys
from array import array

n = int(input())
edge = [list(map(int, input().split())) for _ in range(n)]
mod = 10**9 + 7

dp_f = [array('i', [-1])*n for _ in range(n)]
dp_g = [array('i', [-1])*n for _ in range(n)]

for i in range(n):
    dp_f[i][i] = dp_g[i][i] = 1
for i in range(n-1):
    dp_f[i][i+1] = dp_g[i][i+1] = 1 if edge[i][i+1] else 0

def f(l, r):
    if dp_f[l][r] != -1:
        return dp_f[l][r]

    dp_f[l][r] = g(l, r) if edge[l][r] else 0
    for m in range(l+1, r):
        if edge[l][m]:
            dp_f[l][r] = (dp_f[l][r] + g(l, m) * f(m, r)) % mod

    return dp_f[l][r]

def g(l, r):
    if dp_g[l][r] != -1:
        return dp_g[l][r]

    dp_g[l][r] = f(l+1, r)
    for m in range(l+1, r):
        dp_g[l][r] = (dp_g[l][r] + f(l, m) * f(m+1, r)) % mod

    return dp_g[l][r]

print(f(0, n-1))


I found an interesting problem on https://codeforces.com/problemset/problem/891/A:
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.

What is the minimum number of operations you need to make all of the elements equal to 1?

-----Input-----

The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array.

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

-----Output-----

Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.

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

Output
5

Input
4
2 4 6 8

Output
-1

Input
3
2 6 9

Output
4

-----Note-----

In the first sample you can turn all numbers to 1 using the following 5 moves:

  [2, 2, 3, 4, 6].  [2, 1, 3, 4, 6]  [2, 1, 3, 1, 6]  [2, 1, 1, 1, 6]  [1, 1, 1, 1, 6]  [1, 1, 1, 1, 1]

We can prove that in this case it is not possible to make all numbers one using less than 5 moves.

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

from math import gcd

n=int(input())
a=list(map(int,input().split()))
m=a.count(1)
if m>0:
    print(n-m)
    return
ans=-1
for i in range(n):
    d=a[i]
    c=i
    for j in range(i+1,n):
        d=gcd(d,a[j])
        if d==1:
            c=j
            break
    if c>i:
        if ans<0:
            ans=c-i+n-1
        else:
            ans=min(ans,c-i+n-1)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/892/A:
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola a_{i} and can's capacity b_{i} (a_{i}  ≤  b_{i}).

Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!

-----Input-----

The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — volume of remaining cola in cans.

The third line contains n space-separated integers that b_1, b_2, ..., b_{n} (a_{i} ≤ b_{i} ≤ 10^9) — capacities of the cans.

-----Output-----

Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes).

You can print each letter in any case (upper or lower).

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

Output
YES

Input
3
6 8 9
6 10 12

Output
NO

Input
5
0 0 5 0 0
1 1 8 10 5

Output
YES

Input
4
4 1 0 3
5 2 2 3

Output
YES

-----Note-----

In the first sample, there are already 2 cans, so the answer is "YES".

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

n=int(input())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
y.sort()
if sum(x)<=y[-1]+y[-2]:
	print("YES")
else:
	print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/892/B:
Hands that shed innocent blood!

There are n guilty people in a line, the i-th of them holds a claw with length L_{i}. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - L_{i}.

You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of guilty people.

Second line contains n space-separated integers L_1, L_2, ..., L_{n} (0 ≤ L_{i} ≤ 10^9), where L_{i} is the length of the i-th person's claw.

-----Output-----

Print one integer — the total number of alive people after the bell rings.

-----Examples-----
Input
4
0 1 0 10

Output
1

Input
2
0 0

Output
2

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

Output
3

-----Note-----

In first sample the last person kills everyone in front of him.

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

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

alive = 1
kill = kog[n - 1]
for i in range(n - 2, -1, -1):
	if kill == 0:
		alive = alive + 1
	kill = max(kill - 1, kog[i])

print(alive)


I found an interesting problem on https://codeforces.com/problemset/problem/893/A:
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.

So they play with each other according to following rules:  Alex and Bob play the first game, and Carl is spectating;  When the game ends, the one who lost the game becomes the spectator in the next game, and the one who was spectating plays against the winner.

Alex, Bob and Carl play in such a way that there are no draws.

Today they have played n games, and for each of these games they remember who was the winner. They decided to make up a log of games describing who won each game. But now they doubt if the information in the log is correct, and they want to know if the situation described in the log they made up was possible (that is, no game is won by someone who is spectating if Alex, Bob and Carl play according to the rules). Help them to check it!

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 100) — the number of games Alex, Bob and Carl played.

Then n lines follow, describing the game log. i-th line contains one integer a_{i} (1 ≤ a_{i} ≤ 3) which is equal to 1 if Alex won i-th game, to 2 if Bob won i-th game and 3 if Carl won i-th game.

-----Output-----

Print YES if the situation described in the log was possible. Otherwise print NO.

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

Output
YES

Input
2
1
2

Output
NO

-----Note-----

In the first example the possible situation is:  Alex wins, Carl starts playing instead of Bob;  Alex wins, Bob replaces Carl;  Bob wins.

The situation in the second example is impossible because Bob loses the first game, so he cannot win the second one.

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

n = int(input())
ind1, ind2  = 1, 2
indicator = True
for i in range(n):
	a = int(input())
	if a != ind1 and a != ind2:
		indicator = False
		print("NO")
		break
	else:
		ind1, ind2 = a, 6 - (ind1 + ind2)
if indicator:
	print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/893/B:
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.

Some examples of beautiful numbers:   1_2 (1_10);  110_2 (6_10);  1111000_2 (120_10);  111110000_2 (496_10).

More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2^{k} - 1) * (2^{k} - 1).

Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it!

-----Input-----

The only line of input contains one number n (1 ≤ n ≤ 10^5) — the number Luba has got.

-----Output-----

Output one number — the greatest beautiful divisor of Luba's number. It is obvious that the answer always exists.

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

Output
1

Input
992

Output
496

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

n = int(input())

for k in range(20, 0, -1):
    div = (2**k - 1) * (2**(k - 1))
    if n % div == 0:
        print(div)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/893/C:
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.

Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.

Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants c_{i} gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.

The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?

Take a look at the notes if you think you haven't understood the problem completely.

-----Input-----

The first line contains two integer numbers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 10^5) — the number of characters in Overcity and the number of pairs of friends.

The second line contains n integer numbers c_{i} (0 ≤ c_{i} ≤ 10^9) — the amount of gold i-th character asks to start spreading the rumor.

Then m lines follow, each containing a pair of numbers (x_{i}, y_{i}) which represent that characters x_{i} and y_{i} are friends (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}). It is guaranteed that each pair is listed at most once.

-----Output-----

Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.

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

Output
10

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

Output
55

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

Output
15

-----Note-----

In the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to...

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

def bfs(i):
    nonlocal p, f, v

    q = [i]
    qi = 0

    v[i] = 1

    best = p[i]

    while qi < len(q):
        j = q[qi]
        if p[j] < best:
            best = p[j]
        for k in f[j]:
            if v[k] != 1:
                q.append(k)
                v[k] = 1
        qi += 1

    return best

n, m = [int(i) for i in input().split(" ")]

p = [int(i) for i in input().split(" ")]
v = [0]*n
f = {}

for a in range(n):
    f[a] = []

for a in range(m):
    x, y = [int(i) for i in input().split(" ")]
    f[x-1].append(y-1)
    f[y-1].append(x-1)

cost = 0
for i in range(n):
    if v[i] == 0:
        cost += bfs(i)

print(cost)


I found an interesting problem on https://codeforces.com/problemset/problem/893/D:
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.

She starts with 0 money on her account.

In the evening of i-th day a transaction a_{i} occurs. If a_{i} > 0, then a_{i} bourles are deposited to Luba's account. If a_{i} < 0, then a_{i} bourles are withdrawn. And if a_{i} = 0, then the amount of money on Luba's account is checked.

In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.

It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».

Luba must not exceed this limit, and also she wants that every day her account is checked (the days when a_{i} = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!

-----Input-----

The first line contains two integers n, d (1 ≤ n ≤ 10^5, 1 ≤ d ≤ 10^9) —the number of days and the money limitation.

The second line contains n integer numbers a_1, a_2, ... a_{n} ( - 10^4 ≤ a_{i} ≤ 10^4), where a_{i} represents the transaction in i-th day.

-----Output-----

Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.

-----Examples-----
Input
5 10
-1 5 0 -5 3

Output
0

Input
3 4
-10 0 20

Output
-1

Input
5 10
-5 0 10 -11 0

Output
2

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

R = lambda: map(int, input().split())
n, k = R()
arr = list(R())
tup = [0, 0]
res = 0
for x in arr:
    if x != 0:
        tup[0], tup[1] = tup[0] + x, tup[1] + x
        tup[1] = min(tup[1], k)
    elif tup[1] < 0:
        tup[0], tup[1] = 0, k
        res += 1
    else:
        tup[0] = max(0, tup[0])
    if tup[0] > k:
        res = -1
        break
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/893/E:
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met:  There are y elements in F, and all of them are integer numbers;  $\prod_{i = 1}^{y} F_{i} = x$.

You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1 ≤ i ≤ y) such that A_{i} ≠ B_{i}. Since the answer can be very large, print it modulo 10^9 + 7.

-----Input-----

The first line contains one integer q (1 ≤ q ≤ 10^5) — the number of testcases to solve.

Then q lines follow, each containing two integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ 10^6). Each of these lines represents a testcase.

-----Output-----

Print q integers. i-th integer has to be equal to the number of y_{i}-factorizations of x_{i} modulo 10^9 + 7.

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

Output
36
6

-----Note-----

In the second testcase of the example there are six y-factorizations:  { - 4,  - 1};  { - 2,  - 2};  { - 1,  - 4};  {1, 4};  {2, 2};  {4, 1}.

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

from array import array
md = 10 ** 9 + 7

def fact_all(N):
    lp = array('Q', [2]*(N+1))
    pr = array('Q', [2])
    pra = pr.append
    for i in range(3, N+1, 2):
        if lp[i] == 2:
            lp[i] = i
            pra(i)
        for p in pr:
            ip = i * p
            if p > lp[i] or ip > N:
                break
            lp[ip] = p
    return lp

def cnk(n, k):
    if k > n//2:
        k = n - k
    ans = 1
    for i in range(n-k+1, n+1):
        ans *= i
    for i in range(2, k+1):
        ans //= i
    ans = ans % md
    return ans

def factor(n, lpa=fact_all(10**6)):
    pws = []
    num_ones = 0
    dv = lpa[n]
    while n > 1 and dv * dv <= n:
        lp = 0
        c, o = divmod(n, dv)
        while o == 0:
            lp += 1
            n = c
            c, o = divmod(n, dv)
        if lp == 1:
            num_ones += 1
        else:
            pws.append(lp)
        dv = lpa[n]
    if n > 1:
        num_ones += 1
        # pws.append(1)
    return pws, num_ones

def main():
    q = int(input())
    for __ in range(q):
        x, y = input().split()
        x, y = int(x), int(y)
        ans = pow(2, y - 1, md)
        pws, num_ones = factor(x)
        for f in pws:
            cm = cnk(f + y - 1, f)
            ans = (ans * cm) % md
        if num_ones:
            ans = (ans * pow(y, num_ones, md)) % md
        print(ans)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/894/B:
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.

Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 10^9 + 7.

Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.

-----Input-----

The only line contains three integers n, m and k (1 ≤ n, m ≤ 10^18, k is either 1 or -1).

-----Output-----

Print a single number denoting the answer modulo 1000000007.

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

Output
1

Input
1 3 1

Output
1

Input
3 3 -1

Output
16

-----Note-----

In the first example the only way is to put -1 into the only block.

In the second example the only way is to put 1 into every block.

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