I found an interesting problem on https://codeforces.com/problemset/problem/750/A:
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th problem.

Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, where he will participate in the contest first.

How many problems can Limak solve if he wants to make it to the party?

-----Input-----

The only line of the input contains two integers n and k (1 ≤ n ≤ 10, 1 ≤ k ≤ 240) — the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house.

-----Output-----

Print one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier.

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

Output
2

Input
4 190

Output
4

Input
7 1

Output
7

-----Note-----

In the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5 + 10 = 15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.

In the second sample, Limak can solve all 4 problems in 5 + 10 + 15 + 20 = 50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.

In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems.

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

n, k = list(map(int, input().split()))
t = 240 - k
cur = 0
ans = 0
for i in range(1,n + 1):
    cur += i * 5
    if (cur > t):
        break
    ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/750/B:
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.

Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move t_{i} kilometers in the direction represented by a string dir_{i} that is one of: "North", "South", "West", "East".

Limak isn’t sure whether the description is valid. You must help him to check the following conditions:  If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South.  If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North.  The journey must end on the North Pole.

Check if the above conditions are satisfied and print "YES" or "NO" on a single line.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 50).

The i-th of next n lines contains an integer t_{i} and a string dir_{i} (1 ≤ t_{i} ≤ 10^6, $\operatorname{dir}_{i} \in \{\text{North, South, West, East} \}$) — the length and the direction of the i-th part of the journey, according to the description Limak got.

-----Output-----

Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes.

-----Examples-----
Input
5
7500 South
10000 East
3500 North
4444 West
4000 North

Output
YES

Input
2
15000 South
4000 East

Output
NO

Input
5
20000 South
1000 North
1000000 West
9000 North
10000 North

Output
YES

Input
3
20000 South
10 East
20000...

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

n = int(input())
pos = 0
is_correct = True
for i in range(n):
    d, direc = input().split()
    d = int(d)
    if is_correct:
        if pos == 0 and direc != 'South':
            is_correct = False
        if pos == 20000 and direc != 'North':
            is_correct = False
        if direc in ('North', 'South'):
            if direc == 'North':
                pos -= d
            elif direc == 'South':
                pos += d
            if pos < 0 or pos > 20000:
                is_correct = False

is_correct = is_correct and pos == 0
if is_correct:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/750/C:
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.

Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division d_{i} (i.e. he belonged to this division just before the start of this contest) and his rating changed by c_{i} just after the contest. Note that negative c_{i} denotes the loss of rating.

What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".

-----Input-----

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

The i-th of next n lines contains two integers c_{i} and d_{i} ( - 100 ≤ c_{i} ≤ 100, 1 ≤ d_{i} ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.

-----Output-----

If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.

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

Output
1907

Input
2
57 1
22 2

Output
Impossible

Input
1
-5 1

Output
Infinity

Input
4
27 2
13 1
-50 1
8 2

Output
1897

-----Note-----

In the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating:  Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7.  With rating 1894 Limak is in the division 2. His rating increases by 5.  Limak has rating 1899 and is still in the division 2. In the last...

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

import sys

def change_rating(div,change):
    if div == 1:
        ranged[0] = max(ranged[0],1900)
    else:
        ranged[1] = min(ranged[1],1899)
    if ranged[0] > ranged[1]:
        return False
    ranged[0] += change
    ranged[1] += change
    return True

def get_max_cur(start):
    t = start
    m = start
    for change in reversed(changes):
        m = max(m, start - change)
        start -= change
    if m >= inf:
        return m
    return t
n = int(input())
inf = sys.maxsize * 2000
ranged = [-inf,inf]
changes = []
for _ in range(n):
    chnage, div = list(map(int,input().split()))
    if not change_rating(div,chnage):
        print('Impossible')
        return
    changes.append(chnage)
max_r = get_max_cur(ranged[1])
if max_r >= inf:
    print('Infinity')
else:
    print(max_r)


I found an interesting problem on https://codeforces.com/problemset/problem/750/D:
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on.

Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t_1, t_2, ..., t_{n}. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t_1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t_2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2^{n} - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash.

Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 30) — the total depth of the recursion.

The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 5). On the i-th level each of 2^{i} - 1 parts will cover t_{i} cells before exploding.

-----Output-----

Print one integer, denoting the number of cells which will be visited at least once by any part of the firework.

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

Output
39

Input
6
1 1 1 1 1 3

Output
85

Input
1
3

Output
3

-----Note-----

For the...

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

import time

coord = set()
flows = int(input())
start = time.time()
t = list(map(int, input().split()))
directions = {0: (0, 1), 1: (1, 1), 2: (1, 0), 3: (1, -1), 4: (0, -1), 5: (-1, -1), 6: (-1, 0), 7: (-1, 1)}
was = [[[[0 for j in range(300)] for i in range(300)] for x in range(31)] for y in range(8)]# np.zeros([600,600,31,8])

def flight(n, x=0, y=0, direction=0):
    if was[direction][n][x][y]:
        #print(x, y, direction, n, len(was))
        return
    was[direction][n][x][y] = 1
    if n:
        for _ in range(t[flows - n]):
            x += directions[direction][0]
            y += directions[direction][1]
            coord.add((x, y))
        flight(n - 1, x, y, (direction + 1) % 8)
        flight(n - 1, x, y, (direction - 1) % 8)

flight(flows)
# print(coord)
print(len(coord))


I found an interesting problem on https://codeforces.com/problemset/problem/753/A:
Santa Claus has n candies, he dreams to give them as gifts to children.

What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.

-----Input-----

The only line contains positive integer number n (1 ≤ n ≤ 1000) — number of candies Santa Claus has.

-----Output-----

Print to the first line integer number k — maximal number of kids which can get candies.

Print to the second line k distinct integer numbers: number of candies for each of k kid. The sum of k printed numbers should be exactly n.

If there are many solutions, print any of them.

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

Output
2
2 3

Input
9

Output
3
3 5 1

Input
2

Output
1
2

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

n = int(input())
k = 1
while k * (k + 1) // 2 <= n:
    k += 1
k -= 1
print(k)
for i in range(1, k):
    print(i, end=' ')
print(n - k * (k - 1) // 2)


I found an interesting problem on https://codeforces.com/problemset/problem/754/A:
One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A.

Lesha is tired now so he asked you to split the array. Help Lesha!

-----Input-----

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

The next line contains n integers a_1, a_2, ..., a_{n} ( - 10^3 ≤ a_{i} ≤ 10^3) — the elements of the array A.

-----Output-----

If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes).

Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers l_{i} and r_{i} which denote the subarray A[l_{i}... r_{i}] of the initial array A being the i-th new array. Integers l_{i}, r_{i} should satisfy the following conditions:  l_1 = 1  r_{k} = n  r_{i} + 1 = l_{i} + 1 for each 1 ≤ i < k.

If there are multiple answers, print any of them.

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

Output
YES
2
1 2
3 3

Input
8
9 -12 3 4 -4 -10 7 3

Output
YES
2
1 2
3 8

Input
1
0

Output
NO

Input
4
1 2 3 -5

Output
YES
4
1 1
2 2
3 3
4 4

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

from sys import stdin

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

f = False
for i in range(len(a)):
    if a[i] != 0:
        ln = i
        f = True
        break
if not f:
    print('NO')
else:
    print('YES')
    l = 0
    i = ln + 1
    ans = []
    while i < len(a):
        if a[i] == 0:
            i += 1
        else:
            ans.append((l+1, i))
            l = i
            i += 1
    if l < len(a):
        ans.append((l+1, i))
    print(len(ans))
    for i in ans:
        print(i[0],i[1])


I found an interesting problem on https://codeforces.com/problemset/problem/754/B:
Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not.

The rules of tic-tac-toe on the 4 × 4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal).

-----Input-----

The tic-tac-toe position is given in four lines.

Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn.

-----Output-----

Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise.

-----Examples-----
Input
xx..
.oo.
x...
oox.

Output
YES

Input
x.ox
ox..
x.o.
oo.x

Output
NO

Input
x..x
..oo
o...
x.xo

Output
YES

Input
o.x.
o...
.x..
ooxx

Output
NO

-----Note-----

In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row.

In the second example it wasn't possible to win by making single turn.

In the third example Ilya could have won by placing X in the last row between two existing Xs.

In the fourth example it wasn't possible to win by making single turn.

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

#!/usr/bin/env pypy3
# -*- coding: UTF-8 -*-
import sys
import re
import math
import itertools
import collections
import bisect
#sys.stdin=file('input.txt')
#sys.stdout=file('output.txt','w')
#10**9+7
mod=1000000007
#mod=1777777777
pi=3.1415926535897932
IS=float('inf')
xy=[(1,0),(-1,0),(0,1),(0,-1)]
bs=[(-1,-1),(-1,1),(1,1),(1,-1)]
def niten(a,b): return abs(a-b) if a>=0 and b>=0 else  a+abs(b) if a>=0 else abs(a)+b if b>=0 else abs(abs(a)-abs(b))
def fib(n): return [(seq.append(seq[i-2] + seq[i-1]), seq[i-2])[1] for seq in [[0, 1]] for i in range(2, n)]
def gcd(a,b): return a if b==0 else gcd(b,a%b)
def lcm(a,b): return a*b/gcd(a,b)
def eucl(x1,y1,x2,y2): return ((x1-x2)**2+(y1-y2)**2)**0.5
def choco(xa,ya,xb,yb,xc,yc,xd,yd): return 1 if abs((yb-ya)*(yd-yc)+(xb-xa)*(xd-xc))<1.e-10 else 0
def pscl(num,l=[1]):
    for i in range(num):
        l = map(lambda x,y:x+y,[0]+l,l+[0])
    return l

l=[]
for i in range(4):
    x=input()
    if 'xx.' in x or '.xx' in x or 'x.x' in x:
        print('YES')
        return
    elif 'ooo' in x:
        print('NO')
        return

    l.append(x)
for i in range(2):
    for j in range(4):
        tate=l[i][j]+l[i+1][j]+l[i+2][j]
        if 'xx.' in tate or '.xx' in tate or 'x.x' in tate:
            print('YES')
            return
        elif 'ooo' in tate:
            print('NO')
            return
        if j>=2:
            y=l[i][j]+l[i+1][j-1]+l[i+2][j-2]
            if 'xx.' in y or '.xx' in y or 'x.x' in y:
                print('YES')
                return
            elif 'ooo' in y:
                print('NO')
                return
        if j<2:
            y=l[i][j]+l[i+1][j+1]+l[i+2][j+2]
            if 'xx.' in y or '.xx' in y or 'x.x' in y:
                print('YES')
                return
            elif 'ooo' in y:
                print('NO')
                return
print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/754/C:
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.

At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that there could not be two or more messages in a row with the same sender. Moreover, a sender never mention himself in his messages.

Vladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.

He has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!

-----Input-----

The first line contains single integer t (1 ≤ t ≤ 10) — the number of chats. The t chats follow. Each chat is given in the following format.

The first line of each chat description contains single integer n (1 ≤ n ≤ 100) — the number of users in the chat.

The next line contains n space-separated distinct usernames. Each username consists of lowercase and uppercase English letters and digits. The usernames can't start with a digit. Two usernames are different even if they differ only with letters' case. The length of username is positive and doesn't exceed 10 characters.

The next line contains single integer m (1 ≤ m ≤ 100) — the number of messages in the chat. The next m line contain the messages in the following formats, one per line:   <username>:<text> — the format of a message with known sender. The username should appear in the list of usernames of the chat.  <?>:<text> — the format of a message with unknown sender.

The text of a message can consist of lowercase and uppercase English letter, digits, characters '.' (dot), ',' (comma), '!' (exclamation mark), '?' (question...

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

from sys import stdin

t = int(stdin.readline())

def c(l,r,msg):
    f = True
    if l > 0 and not msg[l-1].isdigit() and not msg[l-1].isalpha():
        pass
    elif l == 0:
        pass
    else:
        f = False

    if r == len(msg) - 1:
        pass
    elif not msg[r+1].isdigit() and not msg[r+1].isalpha():
        pass
    else:
        f = False

    return f

def dd(i):
    if i - 1 in no_author_set:
        authors[i-1].discard(authors[i])
        if len(authors[i-1]) == 1:
            no_author_set.discard(i-1)
            for d in authors[i-1]:
                authors[i-1] = d
                break
            dd(i-1)
        if len(authors[i-1]) == 0:
            return False
    if i + 1 in no_author_set:
        authors[i+1].discard(authors[i])
        if len(authors[i+1]) == 1:
            no_author_set.discard(i+1)
            for d in authors[i+1]:
                authors[i+1] = d
                break
            dd(i+1)
        if len(authors[i-1]) == 0:
            return False
    return True

try:
    answers = []
    for i in range(t):
        ans = True
        n = int(stdin.readline())
        names = set(stdin.readline().strip().split())
        m = int(stdin.readline())
        authors = list()
        messages = list()
        no_author = list()
        no_author_set = set()
        for j in range(m):
            line = stdin.readline().strip()
            author, msg = line.split(':')
            messages.append(msg)
            if author == '?':
                no_author.append(j)
                no_author_set.add(j)
                a_set = set()
                for name in names:
                    l = msg.find(name)
                    while l != -1:
                        if c(l,l+len(name)-1, msg):
                            a_set.add(name)
                        l = msg.find(name,l+len(name))
                authors.append(names-a_set)
                if j-1 not in no_author_set:
                    authors[j].discard(authors[j-1])
            else:
               ...


I found an interesting problem on https://codeforces.com/problemset/problem/754/D:
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.

The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from l_{i} to r_{i}, inclusive. Today Fedor wants to take exactly k coupons with him.

Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·10^5) — the number of coupons Fedor has, and the number of coupons he wants to choose.

Each of the next n lines contains two integers l_{i} and r_{i} ( - 10^9 ≤ l_{i} ≤ r_{i} ≤ 10^9) — the description of the i-th coupon. The coupons can be equal.

-----Output-----

In the first line print single integer — the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted.

In the second line print k distinct integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — the ids of the coupons which Fedor should choose.

If there are multiple answers, print any of them.

-----Examples-----
Input
4 2
1 100
40 70
120 130
125 180

Output
31
1 2

Input
3 2
1 12
15 20
25 30

Output
0
1 2

Input
5 2
1 10
5 15
14 50
30 70
99 100

Output
21
3 4

-----Note-----

In the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total.

In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.

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

from heapq import heappop, heappush

n, k = [int(x) for x in input().split()]
cs = []
for i in range(n):
    l, r = [int(x) for x in input().split()]
    cs.append((l, r, i+1))
cs.sort()
h = []
lcs = set()
for i in range(k-1):
    heappush(h, [cs[i][1], cs[i][2]])
    lcs.add(cs[i][2])
l = -1
poped = []
push_i = k-1
for i in range(k-1, n):
    heappush(h, [cs[i][1], cs[i][2]])
    d = h[0][0] - cs[i][0]
    if d > l:
        l = d
        for j in range(push_i, i+1):
            lcs.add(cs[j][2])
        for e in poped:
            lcs.remove(e)
        push_i = i+1
        poped = []
    poped.append(heappop(h)[1])

print(l+1)
if l == -1:
    for i in range(1, k+1):
        print(i, end=' ')

else:
    for i in lcs:
        print(i, end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/755/A:
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".

Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any n.

-----Input-----

The only number in the input is n (1 ≤ n ≤ 1000) — number from the PolandBall's hypothesis.

-----Output-----

Output such m that n·m + 1 is not a prime number. Your answer will be considered correct if you output any suitable m such that 1 ≤ m ≤ 10^3. It is guaranteed the the answer exists.

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

Output
1
Input
4

Output
2

-----Note-----

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

For the first sample testcase, 3·1 + 1 = 4. We can output 1.

In the second sample testcase, 4·1 + 1 = 5. We cannot output 1 because 5 is prime. However, m = 2 is okay since 4·2 + 1 = 9, which is not a prime number.

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

def primesSieve(limit):
    def internalPrimesSieve(limit):
        a = [True] * limit # Initialize the primality list
        a[0] = a[1] = False

        for (i, isprime) in enumerate(a):
            if isprime:
                yield i
                for n in range(i*i, limit, i): # Mark factors non-prime
                    a[n] = False
    return [p for p in internalPrimesSieve(limit)]

n = int(input())
primes = primesSieve(1000002)
for i in range(1,1001):
    if n*i + 1 not in primes:
        print(i)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/755/B:
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.

You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?

-----Input-----

The first input line contains two integers n and m (1 ≤ n, m ≤ 10^3) — number of words PolandBall and EnemyBall know, respectively.

Then n strings follow, one per line — words familiar to PolandBall.

Then m strings follow, one per line — words familiar to EnemyBall.

Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players.

Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.

-----Output-----

In a single line of print the answer — "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally.

-----Examples-----
Input
5 1
polandball
is
a
cool
character
nope

Output
YES
Input
2 2
kremowka
wadowicka
kremowka
wiedenska

Output
YES
Input
1 2
a
a
b

Output
NO

-----Note-----

In the first example PolandBall knows much more words and wins effortlessly.

In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins.

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

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

    p_words = set()
    e_words = set()

    for _ in range(n):
        p_words.add(input())
    for _ in range(m):
        e_words.add(input())

    common = p_words & e_words

    p_words -= common
    e_words -= common

    we_win = False
    p_turn = True

    a, b, c = len(p_words), len(e_words), len(common)

    while True:
        if c > 0:
            c -= 1
        else:
            if p_turn:
                if a == 0:
                    we_win = False
                    break
                else:
                    a -= 1
            else:
                if b == 0:
                    we_win = True
                    break
                else:
                    b -= 1

        p_turn = not p_turn

    print("YES" if we_win else "NO")

main()


I found an interesting problem on https://codeforces.com/problemset/problem/755/D:
PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments.

He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1:

Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex.

Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.

-----Input-----

There are only two numbers in the input: n and k (5 ≤ n ≤ 10^6, 2 ≤ k ≤ n - 2, gcd(n, k) = 1).

-----Output-----

You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.

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

Output
2 3 5 8 11
Input
10 3

Output
2 3 4 6 9 12 16 21 26 31

-----Note-----

The greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.

For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines. [Image] [Image] [Image] [Image] [Image] [Image]

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

n, m = [int(i) for i in input().split()]
if m > n//2:
    m = n-m
ans = [1]
count = 0
c = 1
for i in range(n):
    count+=m
    if count>n:
        c+=1
        count-=n
        ans.append(ans[-1] +c)
        c+=1
    else:
        ans.append(ans[-1] +c)
ans = ans[1:]
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/756/A:
Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.

Pavel has a plan: a permutation p and a sequence b_1, b_2, ..., b_{n}, consisting of zeros and ones. Each second Pavel move skewer on position i to position p_{i}, and if b_{i} equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.

Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.

There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k ≥ 2n), so that after k seconds each skewer visits each of the 2n placements.

It can be shown that some suitable pair of permutation p and sequence b exists for any n.

-----Input-----

The first line contain the integer n (1 ≤ n ≤ 2·10^5) — the number of skewers.

The second line contains a sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the permutation, according to which Pavel wants to move the skewers.

The third line contains a sequence b_1, b_2, ..., b_{n} consisting of zeros and ones, according to which Pavel wants to reverse the skewers.

-----Output-----

Print single integer — the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.

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

Output
2

Input
3
2 3 1
0 0 0

Output
1

-----Note-----

In the first example Pavel can change the permutation to 4, 3, 1, 2.

In the second example Pavel...

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

import sys

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

ans = 0
num_cycles = 0
checked = set()

for i in range(n):
    if i in checked:
        continue

    checked.add(i)

    nxt = p[i] - 1

    while nxt != i:
        checked.add(nxt)
        nxt = p[nxt] - 1

    num_cycles += 1

ans += num_cycles if num_cycles != 1 else 0
ans += (sum(b) % 2) == 0

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/756/B:
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.

The fare is constructed in the following manner. There are three types of tickets:   a ticket for one trip costs 20 byteland rubles,  a ticket for 90 minutes costs 50 byteland rubles,  a ticket for one day (1440 minutes) costs 120 byteland rubles.

Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to t + x - 1, inclusive. Assume that all trips take exactly one minute.

To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum a - b.

You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip.

-----Input-----

The first line of input contains integer number n (1 ≤ n ≤ 10^5) — the number of trips made by passenger.

Each of the following n lines contains the time of trip t_{i} (0 ≤ t_{i} ≤ 10^9), measured in minutes from the time of starting the system. All t_{i} are different, given in ascending order, i. e. t_{i} + 1 > t_{i} holds for all 1 ≤ i < n.

-----Output-----

Output n integers. For each trip, print the sum the passenger is charged after it.

-----Examples-----
Input
3
10
20
30

Output
20
20
10

Input
10
13
45
46
60
103
115
126
150
256
516

Output
20
20
10
0
20
0
0
20
20
10

-----Note-----

In the first example, the system works as follows: for the first and second trips it is cheaper to pay for two one-trip tickets, so each time 20 rubles is charged, after the third trip the...

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

n=int(input())
trips=[]
prix=[0]
k=0
j=0
for i in range (n):

    trips.append(int(input()))
    while trips[i]-trips[j]>=90 :
        j+=1
    while trips[i]-trips[k]>=1440:
        k+=1
    prix.append(min(min(prix[k]+120,prix[j]+50),prix[-1]+20))
    print(prix[-1]-prix[-2])


I found an interesting problem on https://codeforces.com/problemset/problem/757/A:
Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.

Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.

Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?

Note: uppercase and lowercase letters are considered different.

-----Input-----

Input contains a single line containing a string s (1  ≤  |s|  ≤  10^5) — the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s.

The string s contains lowercase and uppercase English letters, i.e. $s_{i} \in \{a, b, \ldots, z, A, B, \ldots, Z \}$.

-----Output-----

Output a single integer, the answer to the problem.

-----Examples-----
Input
Bulbbasaur

Output
1

Input
F

Output
0

Input
aBddulbasaurrgndgbualdBdsagaurrgndbb

Output
2

-----Note-----

In the first case, you could pick: Bulbbasaur.

In the second case, there is no way to pick even a single Bulbasaur.

In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur".

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

s = input()
c1 = s.count('B')
c2 = s.count('u')
c3 = s.count('l')
c4 = s.count('b')
c5 = s.count('a')
c6 = s.count('s')
c7 = s.count('r')
print(min(c1, c2//2, c3, c4, c5//2, c6, c7))


I found an interesting problem on https://codeforces.com/problemset/problem/757/B:
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.

But Zulu warns him that a group of k > 1 Pokemon with strengths {s_1, s_2, s_3, ..., s_{k}} tend to fight among each other if gcd(s_1, s_2, s_3, ..., s_{k}) = 1 (see notes for gcd definition).

Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take?

Note: A Pokemon cannot fight with itself.

-----Input-----

The input consists of two lines.

The first line contains an integer n (1 ≤ n ≤ 10^5), the number of Pokemon in the lab.

The next line contains n space separated integers, where the i-th of them denotes s_{i} (1 ≤ s_{i} ≤ 10^5), the strength of the i-th Pokemon.

-----Output-----

Print single integer — the maximum number of Pokemons Bash can take.

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

Output
2

Input
5
2 3 4 6 7

Output
3

-----Note-----

gcd (greatest common divisor) of positive integers set {a_1, a_2, ..., a_{n}} is the maximum positive integer that divides all the integers {a_1, a_2, ..., a_{n}}.

In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.

In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.

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

dict = {}
ans = {}
for i in range(-1,100110):
	dict[i] = []
	ans[i] = 0
for i in range(2,100010):
	if dict[i] == []:
		j = i+i
		while j <= 100010:
			#print(dict[j])
			tmp = dict[j]
			tmp += [i]
			dict[j] = tmp
			#print(dict[j])
			j += i
		dict[i] = [i]
n = input()
n = input()
n = n.split(" ")
banyak = 0
for i in n:
	tmp = int(i)
	for j in dict[tmp] :
		ans[j] += 1
		if ans[j] > banyak : banyak = ans[j]
if (banyak == 0) : banyak = 1
print(banyak)


I found an interesting problem on https://codeforces.com/problemset/problem/757/C:
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has g_{i} Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving.

Formally, an evolution plan is a permutation f of {1, 2, ..., m}, such that f(x) = y means that a Pokemon of type x evolves into a Pokemon of type y.

The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.

Two evolution plans f_1 and f_2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f_1(i) ≠ f_2(i).

Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 10^9 + 7.

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^6) — the number of gyms and the number of Pokemon types.

The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the...

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

import sys
from collections import defaultdict, Counter

P = 10 ** 9 + 7

def factmod(n):
    res = 1
    for i in range(2, n+1):
        res *= i
        res %= P

    return res

def solve():
    n, m = list(map(int, input().split()))
    colour = {i:0 for i in range(1, m+1)}
    colour_map = {}
    for i, line in enumerate(sys.stdin):
        A = [int(x) for x in line.split()]
        count = Counter(A)

        if count[A[0]] == 1:
            count.pop(A[0])
        else:
            count[A[0]] -= 1

        for c in count:
            p = (colour[c], i, count[c])
            if p in colour_map:
                colour[c] = colour_map[p]
            else:
                colour[c] = colour_map[p] = len(colour_map) + 1

    count = Counter(list(colour.values()))

    res = 1
    for c in count:
        res *= factmod(count[c])
        res %= P

    return res

print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/758/A:
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.

Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in a_{i} burles (burle is the currency in Berland).

You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

-----Input-----

The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom.

The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} (0 ≤ a_{i} ≤ 10^6) — the welfare of the i-th citizen.

-----Output-----

In the only line print the integer S — the minimum number of burles which are had to spend.

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

Output
10
Input
5
1 1 0 1 1

Output
1
Input
3
1 3 1

Output
4
Input
1
12

Output
0

-----Note-----

In the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.

In the second example it is enough to give one burle to the third citizen.

In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.

In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.

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

s = input()
s = list(map(int, input().split()))
print(len(s) * max(s) - sum(s))


I found an interesting problem on https://codeforces.com/problemset/problem/758/B:
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.

Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.

It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' — red, 'B' — blue, 'Y' — yellow, 'G' — green.

Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.

-----Input-----

The first and the only line contains the string s (4 ≤ |s| ≤ 100), which describes the garland, the i-th symbol of which describes the color of the i-th light bulb in the order from the beginning of garland:   'R' — the light bulb is red,  'B' — the light bulb is blue,  'Y' — the light bulb is yellow,  'G' — the light bulb is green,  '!' — the light bulb is dead.

The string s can not contain other symbols except those five which were described.

It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'.

It is guaranteed that the string s is correct garland with some blown light bulbs, it means that for example the line "GRBY!!!B" can not be in the input data.

-----Output-----

In the only line print four integers k_{r}, k_{b}, k_{y}, k_{g} — the number of dead light bulbs of red, blue, yellow and green colors accordingly.

-----Examples-----
Input
RYBGRYBGR

Output
0 0 0 0
Input
!RGYB

Output
0 1 0 0
Input
!!!!YGRB

Output
1 1 1 1
Input
!GB!RG!Y!

Output
2 1 1 0

-----Note-----

In the first example there are no dead light bulbs.

In the...

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/758/C:
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others.

Seating in the class looks like a rectangle, where n rows with m pupils in each.

The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the 1-st row, the 2-nd row, ..., the n - 1-st row, the n-th row, the n - 1-st row, ..., the 2-nd row, the 1-st row, the 2-nd row, ...

The order of asking of pupils on the same row is always the same: the 1-st pupil, the 2-nd pupil, ..., the m-th pupil.

During the lesson the teacher managed to ask exactly k questions from pupils in order described above. Sergei seats on the x-th row, on the y-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values:  the maximum number of questions a particular pupil is asked,  the minimum number of questions a particular pupil is asked,  how many times the teacher asked Sergei.

If there is only one row in the class, then the teacher always asks children from this row.

-----Input-----

The first and the only line contains five integers n, m, k, x and y (1 ≤ n, m ≤ 100, 1 ≤ k ≤ 10^18, 1 ≤ x ≤ n, 1 ≤ y ≤ m).

-----Output-----

Print three integers:  the maximum number of questions a particular pupil is asked,  the minimum number of questions a particular pupil is asked,  how many times the teacher asked Sergei.

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

Output
3 2 3
Input
4 2 9 4 2

Output
2 1 1
Input
5 5 25 4 3

Output
1 1 1
Input
100 100 1000000000000000000 100 100

Output
101010101010101 50505050505051 50505050505051

-----Note-----

The order of asking pupils in the first test:   the pupil from the first row who seats at the first table, it means it is Sergei;  the...

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

def main():
    n, m, k, x, y = list(map(int, input().split()))
    A = [[0] * m for i in range(n)]
    MOD = (2 * n - 2) * m
    if n > 1:
        for i in range(m):
            A[0][i] += k // MOD
            A[-1][i] += k // MOD
        for i in range(1, n - 1):
            for j in range(m):
                A[i][j] += 2 * (k // MOD)
        k %= MOD
        for i in range(n):
            for j in range(m):
                if k > 0:
                    A[i][j] += 1
                    k -= 1
        for i in range(n - 2, -1, -1):
            for j in range(m):
                if k > 0:
                    A[i][j] += 1
                    k -= 1
    else:
        MOD = m
        for i in range(m):
            A[0][i] = k // MOD
        k %= MOD
        for i in range(m):
            if k > 0:
                A[0][i] += 1
                k -= 1
    maxx = -1
    minn = 10 ** 100
    for row in A:
        maxx = max(maxx, max(row))
        minn = min(minn, min(row))
    print(maxx, minn, A[x - 1][y - 1])

main()


I found an interesting problem on https://codeforces.com/problemset/problem/758/D:
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets 11311 (475 = 1·16^2 + 13·16^1 + 11·16^0). Alexander lived calmly until he tried to convert the number back to the decimal number system.

Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base n he will get the number k.

-----Input-----

The first line contains the integer n (2 ≤ n ≤ 10^9). The second line contains the integer k (0 ≤ k < 10^60), it is guaranteed that the number k contains no more than 60 symbols. All digits in the second line are strictly less than n.

Alexander guarantees that the answer exists and does not exceed 10^18.

The number k doesn't contain leading zeros.

-----Output-----

Print the number x (0 ≤ x ≤ 10^18) — the answer to the problem.

-----Examples-----
Input
13
12

Output
12
Input
16
11311

Output
475
Input
20
999

Output
3789
Input
17
2016

Output
594

-----Note-----

In the first example 12 could be obtained by converting two numbers to the system with base 13: 12 = 12·13^0 or 15 = 1·13^1 + 2·13^0.

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

n=0
k=""
mem=[[-1 for xx in range(66)] for yy in range(66)]

def go(ind,po):
    nonlocal n
    nonlocal k
    nonlocal mem
    if ind>=len(k):
        return 0
    if mem[ind][po] != -1:
        return mem[ind][po]
    for i in range(ind,len(k)):
        cur=int((k[ind:i+1])[::-1])
        if (cur>=n):
            break
        if (k[i]=='0' and i != ind):
            continue
        if (mem[ind][po]==-1):
            if(go(i+1,po+1)!=-1):
                mem[ind][po]=cur*pow(n,po)+go(i+1,po+1)
        else:
            if(go(i+1,po+1)!=-1):
                mem[ind][po]=min(mem[ind][po],cur*pow(n,po)+go(i+1,po+1))
    return mem[ind][po]

n=int(input())
k=input()
k=k[::-1]

print(go(0,0))


I found an interesting problem on https://codeforces.com/problemset/problem/759/E:
There are n types of coins in Byteland. Conveniently, the denomination of the coin type k divides the denomination of the coin type k + 1, the denomination of the coin type 1 equals 1 tugrick. The ratio of the denominations of coin types k + 1 and k equals a_{k}. It is known that for each x there are at most 20 coin types of denomination x.

Byteasar has b_{k} coins of type k with him, and he needs to pay exactly m tugricks. It is known that Byteasar never has more than 3·10^5 coins with him. Byteasar want to know how many ways there are to pay exactly m tugricks. Two ways are different if there is an integer k such that the amount of coins of type k differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo 10^9 + 7.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 3·10^5) — the number of coin types.

The second line contains n - 1 integers a_1, a_2, ..., a_{n} - 1 (1 ≤ a_{k} ≤ 10^9) — the ratios between the coin types denominations. It is guaranteed that for each x there are at most 20 coin types of denomination x.

The third line contains n non-negative integers b_1, b_2, ..., b_{n} — the number of coins of each type Byteasar has. It is guaranteed that the sum of these integers doesn't exceed 3·10^5.

The fourth line contains single integer m (0 ≤ m < 10^10000) — the amount in tugricks Byteasar needs to pay.

-----Output-----

Print single integer — the number of ways to pay exactly m tugricks modulo 10^9 + 7.

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

4
2

Output
1

Input
2
1
4 4
2

Output
3

Input
3
3 3
10 10 10
17

Output
6

-----Note-----

In the first example Byteasar has 4 coins of denomination 1, and he has to pay 2 tugricks. There is only one way.

In the second example Byteasar has 4 coins of each of two different types of denomination 1, he has to pay 2 tugricks. There are 3 ways: pay one coin of the first type and one coin of the other, pay two coins of the first type, and pay two coins of the second type.

In the third example the...

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

p = 1000000007

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

d = [1] * 300001
td = [0] * 300001
L = b[0]
for i in range(1, n):
	if a[i - 1] != 1:
		t = m % a[i - 1]
		if L < t:
			print(0)
			return
		m //= a[i - 1]
		for j in range((L - t) // a[i - 1] + 1):
			d[j] = d[j * a[i - 1] + t]
		L = (L - t) // a[i - 1]
	k = 0
	for j in range(L + b[i] + 1):
		if j <= L:
			k = (k + d[j]) % p
		td[j] = k
		if j >= b[i]:
			k = (k - d[j - b[i]] + p) % p
	L += b[i]
	for j in range(L + 1):
		d[j] = td[j]
print(d[m] if m <= L else 0)


I found an interesting problem on https://codeforces.com/problemset/problem/760/A:
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: $\left. \begin{array}{|r|r|r|r|r|r|} \hline & {2} & {9} & {16} & {23} & {30} \\ \hline & {3} & {10} & {17} & {24} & {31} \\ \hline & {4} & {11} & {18} & {25} & {} \\ \hline & {5} & {12} & {19} & {26} & {} \\ \hline & {6} & {13} & {20} & {27} & {} \\ \hline & {7} & {14} & {21} & {28} & {} \\ \hline 1 & {8} & {15} & {22} & {29} & {} \\ \hline \end{array} \right.$

Petr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.

-----Input-----

The only line contain two integers m and d (1 ≤ m ≤ 12, 1 ≤ d ≤ 7) — the number of month (January is the first month, December is the twelfth) and the weekday of the first date of this month (1 is Monday, 7 is Sunday).

-----Output-----

Print single integer: the number of columns the table should have.

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

Output
6

Input
1 1

Output
5

Input
11 6

Output
5

-----Note-----

The first example corresponds to the January 2017 shown on the picture in the statements.

In the second example 1-st January is Monday, so the whole month fits into 5 columns.

In the third example 1-st November is Saturday and 5 columns is enough.

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/760/B:
n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have.

Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?

-----Input-----

The only line contain three integers n, m and k (1 ≤ n ≤ m ≤ 10^9, 1 ≤ k ≤ n) — the number of hobbits, the number of pillows and the number of Frodo's bed.

-----Output-----

Print single integer — the maximum number of pillows Frodo can have so that no one is hurt.

-----Examples-----
Input
4 6 2

Output
2

Input
3 10 3

Output
4

Input
3 6 1

Output
3

-----Note-----

In the first example Frodo can have at most two pillows. In this case, he can give two pillows to the hobbit on the first bed, and one pillow to each of the hobbits on the third and the fourth beds.

In the second example Frodo can take at most four pillows, giving three pillows to each of the others.

In the third example Frodo can take three pillows, giving two pillows to the hobbit in the middle and one pillow to the hobbit on the third bed.

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

n, m, k = map(int, input().split())
ans = 1
m -= n
left = k - 1
right = n - k

put = 1
while (m >= put):
    m -= put
    ans += 1
    put += (left > 0) + (right > 0)
    if (left): left -= 1
    if (right): right -= 1
    if (left == right == 0):
        ans += (m // put)
        break
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/761/A:
On her way to programming school tiger Dasha faced her first test — a huge staircase! [Image]

The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers.

You need to check whether there is an interval of steps from the l-th to the r-th (1 ≤ l ≤ r), for which values that Dasha has found are correct.

-----Input-----

In the only line you are given two integers a, b (0 ≤ a, b ≤ 100) — the number of even and odd steps, accordingly.

-----Output-----

In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.

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

Output
YES

Input
3 1

Output
NO

-----Note-----

In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5.

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

a,b=list(map(int,input().split()))
print("YES"if abs(a-b)<=1 and a+b>0 else"NO")


I found an interesting problem on https://codeforces.com/problemset/problem/761/B:
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:

The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track.

Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the n barriers. Thus, each of them wrote n integers in the ascending order, each of them was between 0 and L - 1, inclusively. [Image] Consider an example. Let L = 8, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence [2, 4, 6], and Sasha writes down [1, 5, 7].

There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks.

Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction — counterclockwise, if you look on a track from above.

-----Input-----

The first line contains two integers n and L (1 ≤ n ≤ 50, n ≤ L ≤ 100) — the number of barriers on a track and its length.

The second line contains n distinct integers in the ascending order — the distance from Kefa's start to each barrier in the order of its appearance. All integers are in the range from 0 to L - 1 inclusively.

The second line contains n distinct integers in the ascending order — the distance from Sasha's start to each barrier...

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

n, l = list(map(int, input().split()))
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
aa = [0] * n
bb = [0] * n
aa[0] = l - a[-1] + a[0]
bb[0] = l - b[-1] + b[0]
for i in range(1, n):
    aa[i] = a[i] - a[i - 1]
    bb[i] = b[i] - b[i - 1]
for i in range(n):
    if aa == bb:
        print("YES")
        break
    aa.append(aa[0])
    aa.pop(0)
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/761/C:
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:  There is at least one digit in the string,  There is at least one lowercase (small) letter of the Latin alphabet in the string,  There is at least one of three listed symbols in the string: '#', '*', '&'.  [Image]

Considering that these are programming classes it is not easy to write the password.

For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).

During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.

You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.

-----Input-----

The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.

Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.

You have such input data that you can always get a valid password.

-----Output-----

Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.

-----Examples-----
Input
3 4
1**2
a3*0
c4**

Output
1

Input
5...

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

n, m = map(int, input().split())
s = [input() for i in range(0, n)]
dp = [[n*m + 1] * 8 for i in range(0, n + 1)]

def minLenA(s):
    for i in range(0, len(s)):
        if '0' <= s[i] <= '9':
            return i;
    return m + 1

def minLenB(s):
    for i in range(0, len(s)):
        if 'a' <= s[i] <= 'z':
            return i;
    return m + 1

def minLenC(s):
    for i in range(0, len(s)):
        if s[i] in ["#", "*", "&"]:
            return i;
    return m + 1

dp[0][0] = 0
dp[0][1:] = [n*m + 1] * 7

l = [[0] * 3 for i in range(0, n)]
for i in range(0, n):
    l[i][0] = min(minLenA(s[i]),1 + minLenA(list(reversed(s[i]))))
    l[i][1] = min(minLenB(s[i]), 1 +minLenB(list(reversed(s[i]))))
    l[i][2] = min(minLenC(s[i]), 1 + minLenC(list(reversed(s[i]))))
for i in range(1, n + 1):
    for j in range(0, 8):
        dp[i][j] = min(dp[i - 1][j ^ 1] + l[i-1][0], dp[i-1][j],dp[i][j]);
        dp[i][j] = min(dp[i - 1][j ^ 2] + l[i-1][1], dp[i-1][j],dp[i][j]);
        dp[i][j] = min(dp[i - 1][j ^ 4] + l[i-1][2],dp[i-1][j],dp[i][j]);
print(dp[-1][7])


I found an interesting problem on https://codeforces.com/problemset/problem/761/D:
Dasha logged into the system and began to solve problems. One of them is as follows:

Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: c_{i} = b_{i} - a_{i}.

About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l ≤ a_{i} ≤ r and l ≤ b_{i} ≤ r. About sequence c we know that all its elements are distinct.

 [Image]

Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.

Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that p_{i} equals to the number of integers which are less than or equal to c_{i} in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.

Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.

-----Input-----

The first line contains three integers n, l, r (1 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the sequence and boundaries of the segment where the elements of sequences a and b are.

The next line contains n integers a_1,  a_2,  ...,  a_{n} (l ≤ a_{i} ≤ r) — the elements of the sequence a.

The next line contains n distinct integers p_1,  p_2,  ...,  p_{n} (1 ≤ p_{i} ≤ n) — the compressed sequence of the sequence c.

-----Output-----

If there is no the suitable sequence b, then in the only line print "-1".

Otherwise, in the only line print n integers — the elements of any suitable sequence b.

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

Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1...

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

def binary_search(l, r, k):
    while (l <= r):
        mid = l+r >> 1
        if (mid < k):
            l = mid+1
        else:
            r = mid-1
    return l

def main():
    n, l, r = map(int, input().split())
    a = list(map(int, input().split()))
    p = list(map(int, input().split()))
    x = [(p[i], i+1, a[i]) for i in range(n)]

    x.sort()
    a = [x[i][2] for i in range(n)]
    p = [x[i][1] for i in range(n)]
    b = [0]*(n+1)
    b[p[0]-1] = l

    for i in range(1,n):
        idx_list = p[i-1]-1
        b[p[i]-1] = binary_search(l, r, b[idx_list] - a[i-1] + a[i])
        if (b[idx_list] - a[i-1] == b[p[i]-1] - a[i]):
            b[p[i]-1] += 1

    if (max(b) > r):
        print(-1)
        return
    for i in range(n):
        print(b[i], end=' ')

main()


I found an interesting problem on https://codeforces.com/problemset/problem/761/E:
Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve.  [Image]

The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.

The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points.

Help Dasha to find any suitable way to position the tree vertices on the plane.

It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 10^18 in absolute value.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree.

Each of next n - 1 lines contains two integers u_{i}, v_{i} (1 ≤ u_{i}, v_{i} ≤ n) that mean that the i-th edge of the tree connects vertices u_{i} and v_{i}.

It is guaranteed that the described graph is a tree.

-----Output-----

If the puzzle doesn't have a solution then in the only line print "NO".

Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers x_{i}, y_{i} (|x_{i}|, |y_{i}| ≤ 10^18) — the coordinates of the point which corresponds to the i-th vertex of the tree.

If there are several solutions, print any of them.

-----Examples-----
Input
7
1 2
1 3
2 4
2 5
3 6
3 7
Output
YES
0 0
1 0
0 1
2 0
1 -1
-1 1
0 2
Input
6
1 2
2 3
2 4
2 5
2 6

Output
NO

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

-----Note-----

In the first sample one of the possible positions of tree is: [Image]

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

def main():
	n = int(input())
	graph = [[] for i in range(n)]
	ans = [(0,0)] * n

	for _ in range(n - 1):
		u, v = [int(el) for el in input().split()]
		u -= 1
		v -= 1
		graph[u].append(v)
		graph[v].append(u)

	for l in graph:
		if len(l) > 4:
			print('NO')
			return

	step = 1 << 28

	used = [False] * n
	def dfs(v, direction, step, koord):
		used[v] = True
		if direction == 'u':
			my_koord = (koord[0] + step, koord[1])
			dirs = ['u', 'l', 'r']
		elif direction == 'd':
			my_koord = (koord[0] - step, koord[1])
			dirs = ['d', 'l', 'r']
		elif direction == 'l':
			my_koord = (koord[0], koord[1] - step)
			dirs = ['u', 'd', 'l']
		elif direction == 'r':
			my_koord = (koord[0], koord[1] + step)
			dirs = ['u', 'd', 'r']
		elif direction == '':
			my_koord = (0, 0)
			dirs = ['u', 'd', 'l', 'r']

		ans[v] = my_koord

		d = 0
		for u in graph[v]:
			if not used[u]:
				dfs(u, dirs[d], step >> 1, my_koord)
				d += 1

	dfs(0, '', step, (0, 0))

	print('YES')
	for k in ans:
		print(k[0], k[1])

main()


I found an interesting problem on https://codeforces.com/problemset/problem/762/A:
You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist.

Divisor of n is any such natural number, that n can be divided by it without remainder.

-----Input-----

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

-----Output-----

If n has less than k divisors, output -1.

Otherwise, output the k-th smallest divisor of n.

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

Output
2

Input
5 3

Output
-1

Input
12 5

Output
6

-----Note-----

In the first example, number 4 has three divisors: 1, 2 and 4. The second one is 2.

In the second example, number 5 has only two divisors: 1 and 5. The third divisor doesn't exist, so the answer is -1.

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

import sys
from math import sqrt, floor
from collections import Counter

def factorize(n):
    limit = floor(sqrt(n))
    factor = Counter()

    p = 2
    while n % p == 0:
        factor[p] += 1
        n //= p

    for p in range(3, limit + 1, 2):
        while n % p == 0:
            factor[p] += 1
            n //= p
    if n > 1:
        factor[n] += 1

    return factor

def make_divisors(n):
    result = [1]

    for p, e in factorize(n).items():
        result = [x * p**i for i in range(e + 1) for x in result]

    return sorted(result)

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

divisors = make_divisors(n)

if k > len(divisors):
    ans = -1
else:
    ans = divisors[k - 1]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/762/B:
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!

The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.

You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.

You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.

-----Input-----

The first line contains three integers a, b and c (0 ≤ a, b, c ≤ 10^5)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively.

The next line contains one integer m (0 ≤ m ≤ 3·10^5)  — the number of mouses in the price list.

The next m lines each describe another mouse. The i-th line contains first integer val_{i} (1 ≤ val_{i} ≤ 10^9)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.

-----Output-----

Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.

-----Example-----
Input
2 1 1
4
5 USB
6 PS/2
3 PS/2
7 PS/2

Output
3 14

-----Note-----

In the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.

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

from sys import stdin

A, B, C = list(map(int, stdin.readline().split()))
M = int(stdin.readline())

usb_mouses = []
ps2_mouses = []
for m in range(M):
    p, t = stdin.readline().split()

    if t == "USB":
        usb_mouses.append(int(p))
    elif t == "PS/2":
        ps2_mouses.append(int(p))

usb_mouses.sort()
ps2_mouses.sort()

usb_cur = 0
ps2_cur = 0

cost = 0

while usb_cur < len(usb_mouses) and A > 0:
    cost += usb_mouses[usb_cur]
    usb_cur += 1
    A -= 1

while ps2_cur < len(ps2_mouses) and B > 0:
    cost += ps2_mouses[ps2_cur]
    ps2_cur += 1
    B -= 1

while C > 0:
    if usb_cur < len(usb_mouses) and ps2_cur < len(ps2_mouses):
        if usb_mouses[usb_cur] < ps2_mouses[ps2_cur]:
            cost += usb_mouses[usb_cur]
            usb_cur += 1
        else:
            cost += ps2_mouses[ps2_cur]
            ps2_cur += 1
    elif usb_cur < len(usb_mouses):
        cost += usb_mouses[usb_cur]
        usb_cur += 1
    elif ps2_cur < len(ps2_mouses):
        cost += ps2_mouses[ps2_cur]
        ps2_cur += 1
    else:
        break

    C -= 1

print("{} {}".format(usb_cur + ps2_cur, cost))


I found an interesting problem on https://codeforces.com/problemset/problem/762/C:
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.

Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.

-----Input-----

The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 10^5 characters.

-----Output-----

On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.

If the answer consists of zero characters, output «-» (a minus sign).

-----Examples-----
Input
hi
bob

Output
-

Input
abca
accepted

Output
ac

Input
abacaba
abcdcba

Output
abcba

-----Note-----

In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.

In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.

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

import math

def prefixIds(a, b):
	prefSubsId = [math.inf] * len(b)

	# print(a)
	# print(b)

	bId = 0
	aId = 0

	while aId < len(a):
		if bId == len(b):
			break

		if a[aId] == b[bId]:
			prefSubsId[bId] = aId + 1
			bId += 1
			aId += 1
		else:
			aId += 1

	return prefSubsId

a = input()
b = input()

# print(a)
# print(b)

n = len(b)

prefLens = prefixIds(a, b)
suffLens = prefixIds(a[::-1], b[::-1])[::-1]

# for i in range(n):
# 	if suffLens[i] != math.inf:
# 		suffLens[i] = len(a) - suffLens[i]

# print(*prefLens, sep='\t')
# print(*suffLens, sep='\t')

prefLen = 0
suffLen = 0

minCutLen = n
lBorder = -1
rBorder = n

while suffLen < n and suffLens[suffLen] == math.inf:
	suffLen += 1

curCutLen = suffLen
# print(curCutLen)
if curCutLen < minCutLen:
	minCutLen = curCutLen
	rBorder = suffLen

while prefLen < suffLen and prefLens[prefLen] != math.inf:
	while suffLen < n and prefLens[prefLen] + suffLens[suffLen] > len(a):
		# print(suffLen)
		suffLen += 1
	# print(prefLen)
	# print(suffLen)
	curCutLen = suffLen - prefLen - 1
	# print(curCutLen)
	if curCutLen < minCutLen:
		minCutLen = curCutLen
		lBorder = prefLen
		rBorder = suffLen
	prefLen += 1
	# print(prefLens[prefLen])
	# print(suffLens[suffLen])
# 	# print()

# print("pref, suff")
# print(prefLen)
# print(suffLen)

# print(minCutLen)
# print(n)
# print(lBorder)
# print(rBorder)

if minCutLen == n:
	print('-')
elif minCutLen == 0:
	print(b)
else:
	print(b[:lBorder + 1] + b[rBorder:])

# print(maxPrefLen)
# print(maxSuffLen)


I found an interesting problem on https://codeforces.com/problemset/problem/764/A:
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.

Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1, 2, ..., z. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.

-----Input-----

The only string contains three integers — n, m and z (1 ≤ n, m, z ≤ 10^4).

-----Output-----

Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.

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

Output
10

Input
1 2 5

Output
2

Input
2 3 9

Output
1

-----Note-----

Taymyr is a place in the north of Russia.

In the first test the artists come each minute, as well as the calls, so we need to kill all of them.

In the second test we need to kill artists which come on the second and the fourth minutes.

In the third test — only the artist which comes on the sixth minute.

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

n,m,z=list(map(int,input().split()))
ans=0
for i in range(1,z+1):
  if i%m==0 and i%n==0:
    ans+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/764/B:
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number a_{i}, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.

In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.

After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.

-----Input-----

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

The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9), where a_{i} is the number written on the i-th cube after Dima has changed their order.

-----Output-----

Print n integers, separated by spaces — the numbers written on the cubes in their initial order.

It can be shown that the answer is unique.

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

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

Output
2 1 6 2 5 4 9 6

-----Note-----

Consider the first sample.  At the begining row was [2, 3, 9, 6, 7, 1, 4].  After first operation row was [4, 1, 7, 6, 9, 3, 2].  After second operation row was [4, 3, 9, 6, 7, 1, 2].  After third operation row was [4, 3, 7, 6, 9, 1, 2].  At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].

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

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

for i in range(n//2):
    if i % 2 == 0:
        t = a[i]
        a[i] = a[n-i-1]
        a[n-i-1] = t

print(*a)


I found an interesting problem on https://codeforces.com/problemset/problem/765/B:
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.

To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.

You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.

-----Input-----

In the only line of input there is a string S of lowercase English letters (1 ≤ |S| ≤ 500) — the identifiers of a program with removed whitespace characters.

-----Output-----

If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".

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

Output
YES

Input
jinotega

Output
NO

-----Note-----

In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:

 replace all occurences of number with a, the result would be "a string a character a string a",

 replace all occurences of string with b, the result would be "a b a character a b a",

 replace all occurences of character with c, the result would be "a b a c a b a",

 all identifiers have been replaced, thus the obfuscation is finished.

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

s = input()

is_correct = True

for fs in range(26):
    for sc in range(fs + 1, 26):
        is_first = s.find(chr(ord('a') + fs))
        is_second = s.find(chr(ord('a') + sc))

        if is_second != -1:
            is_correct &= is_first != -1
            is_correct &= is_first < is_second

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


I found an interesting problem on https://codeforces.com/problemset/problem/765/C:
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.

Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.

Note that the game consisted of several complete sets.

-----Input-----

The first line contains three space-separated integers k, a and b (1 ≤ k ≤ 10^9, 0 ≤ a, b ≤ 10^9, a + b > 0).

-----Output-----

If the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets.

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

Output
1

Input
11 2 3

Output
-1

-----Note-----

Note that the rules of the game in this problem differ from the real table tennis game, for example, the rule of "balance" (the winning player has to be at least two points ahead to win a set) has no power within the present problem.

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

k, a, b = map(int, input().split())
ans = a // k + b // k
if ans == 0 or (min(a, b) < k and max(a, b) % k):
    print(-1)
else:
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/765/D:
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.

Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.

Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all $x \in [ m ]$, and h(g(x)) = f(x) for all $x \in [ n ]$, or determine that finding these is impossible.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^5).

The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n).

-----Output-----

If there is no answer, print one integer -1.

Otherwise, on the first line print the number m (1 ≤ m ≤ 10^6). On the second line print n numbers g(1), ..., g(n). On the third line print m numbers h(1), ..., h(m).

If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.

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

Output
3
1 2 3
1 2 3

Input
3
2 2 2

Output
1
1 1 1
2

Input
2
2 1

Output
-1

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

n = int(input())
a = list(map(int, input().split()))
i = 0
h = dict()
g = []
for x in a:
    cur = x
    if a[cur - 1] != cur:
        print("-1")
        quit()
    if not h.__contains__(cur):
        h[cur] = len(g)
        g.append(cur)
print(len(g))
for x in a:
    print(h[x] + 1, end=" ")
print()
for x in g:
    print(x, end=" ")


I found an interesting problem on https://codeforces.com/problemset/problem/766/A:
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.

Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.

A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.

-----Input-----

The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 10^5 characters.

-----Output-----

If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.

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

Output
5

Input
a
a

Output
-1

-----Note-----

In the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.

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

s1 = input()
s2 = input()
if s1 != s2:
    print(max(len(s1), len(s2)))
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/766/B:
Mahmoud has n line segments, the i-th of them has length a_{i}. Ehab challenged him to use exactly 3 line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly 3 of them to form a non-degenerate triangle.

Mahmoud should use exactly 3 line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.

-----Input-----

The first line contains single integer n (3 ≤ n ≤ 10^5) — the number of line segments Mahmoud has.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the lengths of line segments Mahmoud has.

-----Output-----

In the only line print "YES" if he can choose exactly three line segments and form a non-degenerate triangle with them, and "NO" otherwise.

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

Output
YES

Input
3
4 1 2

Output
NO

-----Note-----

For the first example, he can use line segments with lengths 2, 4 and 5 to form a non-degenerate triangle.

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

n = int(input())
x = list(map(int, input().strip().split(' ')))

x.sort()
try:
    znak = True
    for i in range(len(x)):
        for j in range(i + 1, len(x) - 1):
            if x[i] + x[j] > x[j+1]:
                print('YES')
                znak = False
                1/0
    if znak:
        print('NO')

except:
    pass


I found an interesting problem on https://codeforces.com/problemset/problem/766/C:
Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than a_{i}. For example, if a_1 = 2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.

Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a_1 = 2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.

A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.

While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions:   How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 10^9 + 7.  What is the maximum length of a substring that can appear in some valid splitting?  What is the minimum number of substrings the message can be spit in?

Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message...

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

cin=lambda: list(map(int,input().split()))
n=int(input())
st=input()
a=list(cin())
dp=[0]*(n+2)
mn=[10**4]*(n+2)
mx=1
dp[0]=1
dp[-1]=1
mn[0]=1
mn[-1]=0
mod=int(1e9)+7

for i in range(1,n):
    c=10**4
    for j in range(i,-1,-1):
        ind=ord(st[j])-ord('a')
        c=min(c,a[ind])
        if c<i-j+1:break
        dp[i] += dp[j-1]
        mn[i] = min(mn[i],mn[j-1]+1)
        mx=max(mx,i-j+1)

print('\n'.join(map(str,[dp[n-1]%mod,mx,mn[n-1]])))


I found an interesting problem on https://codeforces.com/problemset/problem/766/D:
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.

He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.

Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.

After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.

After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.

-----Input-----

The first line of input contains three integers n, m and q (2 ≤ n ≤ 10^5, 1 ≤ m, q ≤ 10^5) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.

The second line contains n distinct words a_1, a_2, ..., a_{n} consisting of small English letters with length not exceeding 20,...

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

f = lambda: input().split()
n, m, k = map(int, f())
u = list(range(n + 1))
v = [n] * n
s = {q: i for i, q in zip(u, f())}
p = ['YES'] * m

def g(i):
    k = u[i]
    while k != u[k]: k = u[k]
    while u[i] != k: i, u[i] = u[i], k
    return k

for l in range(m):
    r, x, y = f()
    i, j = s[x], s[y]
    a, b = g(i), g(j)
    i, j = v[a], v[b]
    c, d = g(i), g(j)
    if r == '2': b, d = d, b
    if a == d: p[l] = 'NO'
    elif c == b == n: v[a], v[d] = d, a
    elif c == b: p[l] = 'NO'
    elif c == n: u[a] = b
    elif b == n: u[d] = c
    elif d == n: u[b] = a
    else: u[a], u[c] = b, d

u = [g(q) for q in u]
v = [u[q] for q in v]

for l in range(k):
    x, y = f()
    i, j = s[x], s[y]
    a, c = u[i], u[j]
    p.append(str(3 - 2 * (a == c) - (a == v[c])))

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