I found an interesting problem on https://codeforces.com/problemset/problem/852/E:
John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N.

John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules.

To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey.

He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey.

In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 10^9 + 7.

-----Input-----

In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities.

In the next N - 1 lines, two numbers a,  b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road.

-----Output-----

Output one number, the answer to the problem modulo 10^9 + 7.

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

Output
4

Input
3
1 2
2 3

Output
10

-----Note-----

Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and...

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/853/B:
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.

There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.

You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.

Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.

-----Input-----

The first line of input contains three integers n, m and k (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 10^5, 1 ≤ k ≤ 10^6).

The i-th of the following m lines contains the description of the i-th flight defined by four integers d_{i}, f_{i}, t_{i} and c_{i} (1 ≤ d_{i} ≤ 10^6, 0 ≤ f_{i} ≤ n, 0 ≤ t_{i} ≤ n, 1 ≤ c_{i} ≤ 10^6, exactly one of f_{i} and t_{i} equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket...

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

from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
    print(-1)
    return
for i in range(m):
    pln.append([int(i) for i in input().split()])
pln.sort()

grp=[[pln[0]]];gt=0;
for i in range(1,m):
    if pln[i][0]!=pln[i-1][0]:
        gt=gt+1
        grp.append([])
    grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
    xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)

from math import inf
pre=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
    for di,fi,ti,ci in x:
        if ti==0:
            if mincost[fi]==inf:
                ct+=1
            if sumcost==inf:
                mincost[fi]=min(mincost[fi],ci)
            else:
                sumcost=sumcost-mincost[fi]
                mincost[fi]=min(mincost[fi],ci)
                sumcost=sumcost+mincost[fi]
    if ct==n and sumcost==inf:
        sumcost=sum(mincost[1:])
    pre[i]=sumcost
#print(pre)

sa=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
    for di,fi,ti,ci in x:
        if fi==0:
            if mincost[ti]==inf:
                ct+=1
            if sumcost==inf:
                mincost[ti]=min(mincost[ti],ci)
            else:
                sumcost=sumcost-mincost[ti]
                mincost[ti]=min(mincost[ti],ci)
                sumcost=sumcost+mincost[ti]
    if ct==n and sumcost==inf:
        sumcost=sum(mincost[1:])
    sa[i]=sumcost
sa.reverse()
#print(sa)

ans=inf
for l,xxi in enumerate(xx):
    r=bisect_right(xx,xxi+k)
    ansl=pre[l]
    ansr= inf if r==len(xx) else sa[r]
    ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/854/A:
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction $\frac{a}{b}$ is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).

During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ( + ) instead of division button (÷) and got sum of numerator and denominator that was equal to n instead of the expected decimal notation.

Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction $\frac{a}{b}$ such that sum of its numerator and denominator equals n. Help Petya deal with this problem.

-----Input-----

In the only line of input there is an integer n (3 ≤ n ≤ 1000), the sum of numerator and denominator of the fraction.

-----Output-----

Output two space-separated positive integers a and b, numerator and denominator of the maximum possible proper irreducible fraction satisfying the given sum.

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

Output
1 2

Input
4

Output
1 3

Input
12

Output
5 7

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

from math import gcd

n = int(input())
curr_opt_a = 1
for a in range(n - 1, 0, -1):
    b = n - a
    if a >= b:
        continue
    if gcd(a, b) == 1:
        curr_opt_a = max(curr_opt_a, a)
print(curr_opt_a, n - curr_opt_a)


I found an interesting problem on https://codeforces.com/problemset/problem/854/B:
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.

Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly k already inhabited apartments, but he doesn't know their indices yet.

Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.

-----Input-----

The only line of the input contains two integers: n and k (1 ≤ n ≤ 10^9, 0 ≤ k ≤ n).

-----Output-----

Print the minimum possible and the maximum possible number of apartments good for Maxim.

-----Example-----
Input
6 3

Output
1 3

-----Note-----

In the sample test, the number of good apartments could be minimum possible if, for example, apartments with indices 1, 2 and 3 were inhabited. In this case only apartment 4 is good. The maximum possible number could be, for example, if apartments with indices 1, 3 and 5 were inhabited. In this case all other apartments: 2, 4 and 6 are good.

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

from sys import stdin, stdout

n,k = list(map(int,stdin.readline().rstrip().split()))

minH = min([1,k,n-k])
maxH = min([2*k,n-k])

print(str(minH) + ' ' + str(maxH))


I found an interesting problem on https://codeforces.com/problemset/problem/855/A:
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.

He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.

Formally, for a name s_{i} in the i-th line, output "YES" (without quotes) if there exists an index j such that s_{i} = s_{j} and j < i, otherwise, output "NO" (without quotes).

-----Input-----

First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list.

Next n lines each contain a string s_{i}, consisting of lowercase English letters. The length of each string is between 1 and 100.

-----Output-----

Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.

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

-----Examples-----
Input
6
tom
lucius
ginny
harry
ginny
harry

Output
NO
NO
NO
NO
YES
YES

Input
3
a
a
a

Output
NO
YES
YES

-----Note-----

In test case 1, for i = 5 there exists j = 3 such that s_{i} = s_{j} and j < i, which means that answer for i = 5 is "YES".

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

def main():
    n = int(input())
    s = set()
    for i in range(n):
        name = input()
        if name in s:
            print("YES")
        else:
            print("NO")
        s.add(name)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/855/B:
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.

Value of x is calculated as maximum of p·a_{i} + q·a_{j} + r·a_{k} for given p, q, r and array a_1, a_2, ... a_{n} such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.

-----Input-----

First line of input contains 4 integers n, p, q, r ( - 10^9 ≤ p, q, r ≤ 10^9, 1 ≤ n ≤ 10^5).

Next line of input contains n space separated integers a_1, a_2, ... a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9).

-----Output-----

Output a single integer the maximum value of p·a_{i} + q·a_{j} + r·a_{k} that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.

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

Output
30

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

Output
12

-----Note-----

In the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.

In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.

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

n, p, q, r = map(int, input().split())
A = list(map(int, input().split()))

P = [p * a for a in A]
Q = [q * a for a in A]
R = [r * a for a in A]

ans = - (10 ** 20)

for i in range(1, n):
	P[i] = max(P[i], P[i - 1])

PQ = [0 for i in range(n)]

for i in range(n):
	PQ[i] = P[i] + Q[i]

	if i:
		PQ[i] = max(PQ[i], PQ[i - 1])

for i in range(n):
	ans = max(ans, PQ[i] + R[i])

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/858/A:
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.

For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.

Write a program that will perform the k-rounding of n.

-----Input-----

The only line contains two integers n and k (1 ≤ n ≤ 10^9, 0 ≤ k ≤ 8).

-----Output-----

Print the k-rounding of n.

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

Output
30000

Input
10000 1

Output
10000

Input
38101 0

Output
38101

Input
123456789 8

Output
12345678900000000

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

def gcd(a, b):
    if (b == 0):
        return a
    else:
        return gcd(b, a % b)

n, k = map(int, input().split())
l = 1
for i in range(k):
    l *= 10
print(str(n // gcd(n, l)) + "0" * k)


I found an interesting problem on https://codeforces.com/problemset/problem/858/B:
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.

Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.

Given this information, is it possible to restore the exact floor for flat n?

-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.

m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers k_{i}, f_{i} (1 ≤ k_{i} ≤ 100, 1 ≤ f_{i} ≤ 100), which means that the flat k_{i} is on the f_{i}-th floor. All values k_{i} are distinct.

It is guaranteed that the given information is not self-contradictory.

-----Output-----

Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.

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

Output
4

Input
8 4
3 1
6 2
5 2
2 1

Output
-1

-----Note-----

In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.

In the second example there can be 3 or 4 flats on each floor, so we can't restore the...

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

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

count_of_good = 0
good_on_level = []

for i in range(m):
    a, b = list(map(int, input().split()))
    d.append((a, b))

for on_level in range(1, 101):
    good = True
    for el in d:
        etaj = el[1]
        kv = el[0]
        if not ((etaj - 1) * on_level < kv <= etaj * on_level):
            good = False
            break
    if good:
        count_of_good += 1
        good_on_level.append(on_level)

ans = []

for i in good_on_level:
    if n % i == 0:
        ans.append(n // i)
    else:
        ans.append(n // i + 1)

if len(ans) == 1:
    print(ans[0])
    return

for i in range(1, len(ans)):
    if ans[i - 1] != ans[i]:
        print('-1')
        return

print(ans[0])


I found an interesting problem on https://codeforces.com/problemset/problem/858/C:
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.

Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.

For example:

  the following words have typos: "hellno", "hackcerrs" and "backtothefutttture";  the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo".

When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.

Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.

-----Input-----

The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.

-----Output-----

Print the given word without any changes if there are no typos.

If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.

-----Examples-----
Input
hellno

Output
hell no

Input
abacaba

Output
abacaba

Input
asdfasdf

Output
asd fasd f

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

s = input()
op = []
dl = len(s)
i = 2
gl = {'a','e','i','o','u'}
l = -1
while i<dl:
    if s[i-2] not in gl and s[i-1] not in gl and s[i] not in gl and s[i-2:i+1]!=s[i-2]*3:
        if l==-1:
            l = i-2
    elif l!=-1:
        op.append(str(l)+'-'+str(i-1))
        l = -1
    i+=1
else:
    if l!=-1:
        op.append(str(l)+'-'+str(i-1))
dlo = len(op)
for i in range(dlo-1,-1,-1):
    l = int(op[i][:op[i].find('-')])
    r = int(op[i][op[i].find('-')+1:])
    st = s[l:r+1]
    dl = len(st)
    st1 = ''
    for j in range(0,dl,2):
        st1+=st[j]
        if j<dl-1:
            st1+=st[j+1]
        if j<dl-2:
            st1+=' '
    s = s[:l]+st1+s[r+1:]
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/858/D:
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.

There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then:

  if he enters 00 two numbers will show up: 100000000 and 100123456,  if he enters 123 two numbers will show up 123456789 and 100123456,  if he enters 01 there will be only one number 100123456.

For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts.

The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.

-----Output-----

Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.

-----Examples-----
Input
3
123456789
100000000
100123456

Output
9
000
01

Input
4
123456789
193456789
134567819
934567891

Output
2
193
81
91

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

n = int(input())
s, p = {}, [''] * n
for k in range(n):
    p[k] =input()
    for q in [p[k][i: j] for i in range(9) for j in range(i + 1, 10)]:
        s[q] = -1 if q in s and s[q] != k else k
for q, k in list(s.items()):
    if ~k and len(p[k]) > len(q):p[k] = q
print('\n'.join(p))


I found an interesting problem on https://codeforces.com/problemset/problem/858/E:
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.

Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.

Vladimir wants to rename the files with tests so that their names are distinct integers starting from 1 without any gaps, namely, "1", "2", ..., "n', where n is the total number of tests.

Some of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.

The only operation Vladimir can perform is the "move" command. Vladimir wants to write a script file, each of the lines in which is "move file_1 file_2", that means that the file "file_1" is to be renamed to "file_2". If there is a file "file_2" at the moment of this line being run, then this file is to be rewritten. After the line "move file_1 file_2" the file "file_1" doesn't exist, but there is a file "file_2" with content equal to the content of "file_1" before the "move" command.

Help Vladimir to write the script file with the minimum possible number of lines so that after this script is run:  all examples are the first several tests having filenames "1", "2", ..., "e", where e is the total number of examples;  all other files contain regular tests with filenames "e + 1", "e + 2", ..., "n", where n is the total number of all tests.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 10^5) — the number of files with tests.

n lines follow, each describing a file with test. Each line has a form of "name_i type_i", where "name_i" is the filename, and "type_i" equals "1", if the i-th file contains an example test, and "0" if it contains a regular test. Filenames of each file are strings of...

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

n = int(input())
t = [1] + [0] * n
b, a = d = [], []
h, s = [], []

for i in range(n):
    f, k = input().split()
    d[int(k)].append(f)

m = len(a)
for i in a:
    if i.isdigit() and i[0] != '0':
        j = int(i)
        if 0 < j <= m:
            t[j] = 1
        elif m < j <= n:
            t[j] = -1
        else:
            s.append(i)
    else:
        s.append(i)
for i in b:
    if i.isdigit() and i[0] != '0':
        j = int(i)
        if m < j <= n:
            t[j] = 1
        elif 0 < j <= m:
            t[j] = -1
        else:
            s.append(i)
    else:
        s.append(i)

x = [j for j in range(1, m + 1) if t[j] < 0]
y = [j for j in range(m + 1, n + 1) if t[j] < 0]

u = [j for j in range(1, m + 1) if not t[j]]
v = [j for j in range(m + 1, n + 1) if not t[j]]

if not s and (x or y):
    s = ['0']
    if y:
        i = y.pop()
        v.append(i)
    else:
        i = x.pop()
        u.append(i)
    h.append(str(i) + ' 0')
    t[i] = 0

while x or y:
    if v and x:
        i = x.pop()
        j = v.pop()
        t[j] = 1
        h.append(str(i) + ' ' + str(j))
        u.append(i)
    else:
        u, v, x, y = v, u, y, x

k = 1
for j in s:
    while t[k] == 1: k += 1
    h.append(j + ' ' + str(k))
    k += 1

d = '\nmove '
print(str(len(h)) + d + d.join(h) if h else 0)


I found an interesting problem on https://codeforces.com/problemset/problem/859/A:
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.

After the qualifying round completes, you know K of the onsite finalists, as well as their qualifying ranks (which start at 1, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.

-----Input-----

The first line of input contains K (1 ≤ K ≤ 25), the number of onsite finalists you know. The second line of input contains r_1, r_2, ..., r_{K} (1 ≤ r_{i} ≤ 10^6), the qualifying ranks of the finalists you know. All these ranks are distinct.

-----Output-----

Print the minimum possible number of contestants that declined the invitation to compete onsite.

-----Examples-----
Input
25
2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 28

Output
3

Input
5
16 23 8 15 4

Output
0

Input
3
14 15 92

Output
67

-----Note-----

In the first example, you know all 25 onsite finalists. The contestants who ranked 1-st, 13-th, and 27-th must have declined, so the answer is 3.

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

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

n = int(input())
data = list(readln())
rs = max(data) - 25
print(0 if rs < 0 else rs)


I found an interesting problem on https://codeforces.com/problemset/problem/859/B:
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.

-----Input-----

Input will consist of a single integer N (1 ≤ N ≤ 10^6), the number of city blocks that must be enclosed by the route.

-----Output-----

Print the minimum perimeter that can be achieved.

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

Output
8

Input
11

Output
14

Input
22

Output
20

-----Note-----

Here are some possible shapes for the examples:

[Image]

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

import math

def main():
    n = int(input())
    length = int(math.sqrt(n))
    if length * length == n:
        print(length * 4)
    elif length * (length+1) >= n:
        print((length * 2 + 1) * 2)
    else:
        print((length+1) * 4)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/859/C:
You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.

The way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the "decider" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.

All of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?

-----Input-----

Input will begin with an integer N (1 ≤ N ≤ 50), the number of slices of pie.

Following this is a line with N integers indicating the sizes of the slices (each between 1 and 100000, inclusive), in the order in which they must be handed out.

-----Output-----

Print two integers. First, the sum of the sizes of slices eaten by Alice, then the sum of the sizes of the slices eaten by Bob, assuming both players make their decisions optimally.

-----Examples-----
Input
3
141 592 653

Output
653 733

Input
5
10 21 10 21 10

Output
31 41

-----Note-----

In the first example, Bob takes the size 141 slice for himself and gives the decider token to Alice. Then Alice gives the size 592 slice to Bob and keeps the decider token for herself, so that she can then give the size 653 slice to herself.

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

'''
codeforces.com/problemset/problem/859/C
author: latesum
'''
n = int(input())
v = list(map(int,input().split()))
v.reverse()
ans = [0, 0]
for i in range(n):
    if ans[1] + v[i] > ans[0]:
        t = ans[1] + v[i]
        ans[1] = ans[0]
        ans[0] = t
    else:
        ans[1] += v[i]
print(ans[1], ans[0])


I found an interesting problem on https://codeforces.com/problemset/problem/859/D:
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2^{N} teams participating in the tournament, numbered from 1 to 2^{N}. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2^{N} - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.

Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2^{N} - 1 points.

For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.

-----Input-----

Input will begin with a line containing N (2 ≤ N ≤ 6).

2^{N} lines follow, each with 2^{N} integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.

-----Output-----

Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or...

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

n = int(input())
m = 1 << n
p = [list(map(int, input().split())) for i in range(m)]
u, x = [1] * m, [0] * m
v, y = u[:], x[:]
for i in range(n):
    d = 1 << i
    for j in range(m):
        s = d * (j // d ^ 1)
        v[j] = u[j] * sum(u[k] * p[j][k] for k in range(s, s + d)) / 100
        y[j] = max(x[s: s + d]) + x[j] + v[j] * d
    u, v, x, y = v, u, y, x
print(max(x))


I found an interesting problem on https://codeforces.com/problemset/problem/859/E:
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.

How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 10^9 + 7.

-----Input-----

Input will begin with a line containing N (1 ≤ N ≤ 100000), the number of engineers.

N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2·N. It is guaranteed that no two engineers sit at the same desk.

-----Output-----

Print the number of possible assignments, modulo 1000000007 = 10^9 + 7.

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

Output
6

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

Output
5

-----Note-----

These are the possible assignments for the first example:   1 5 3 7  1 2 3 7  5 2 3 7  1 5 7 3  1 2 7 3  5 2 7 3

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

n = int(input())
m = 2 * n + 1
u = [[] for i in range(m)]
v = [0] * m
s = [0] * m
d = 10 ** 9 + 7
y = 1

for j in range(n):
    a, b = map(int, input().split())
    v[a] = b
    if a != b:
        s[b] += 1
        u[b].append(a)

for b in range(m):
    if not v[b]:
        x = 0
        p = [b]
        while p:
            x += 1
            a = p.pop()
            s[a] = -1
            p += u[a]
        y = (x * y) % d

for a in range(m):
    if s[a] == 0:
        b = v[a]
        while s[b] == 1:
            s[b] = -1
            b = v[b]
        s[b] -= 1

for a in range(m):
    if s[a] == 1:
        y = (2 * y) % d
        while s[a]:
            s[a] = 0
            a = v[a]

print(y)


I found an interesting problem on https://codeforces.com/problemset/problem/859/G:
n evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number k. Then you may repeatedly select a set of 2 or more points which are evenly spaced, and either increase all numbers at points in the set by k or decrease all numbers at points in the set by k. You would like to eventually end up with all numbers equal to 0. Is it possible?

A set of 2 points is considered evenly spaced if they are diametrically opposed, and a set of 3 or more points is considered evenly spaced if they form a regular polygon.

-----Input-----

The first line of input contains an integer n (3 ≤ n ≤ 100000), the number of points along the circle.

The following line contains a string s with exactly n digits, indicating the numbers initially present at each of the points, in clockwise order.

-----Output-----

Print "YES" (without quotes) if there is some sequence of operations that results in all numbers being 0, otherwise "NO" (without quotes).

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

-----Examples-----
Input
30
000100000100000110000000001100

Output
YES

Input
6
314159

Output
NO

-----Note-----

If we label the points from 1 to n, then for the first test case we can set k = 1. Then we increase the numbers at points 7 and 22 by 1, then decrease the numbers at points 7, 17, and 27 by 1, then decrease the numbers at points 4, 10, 16, 22, and 28 by 1.

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

#Circle of Numbers
import math

def centre(n, pts):
    x, y = 0, 0
    for j in [7,11,13,17,19,23,29,31,37,1193,1663,2711,4007,65537]:
        if math.gcd(n,j) == 1:
            for i in range(n):
                k = int(pts[i])
                x += k*math.cos(math.pi * 2*i*j/n)
                y += k*math.sin(math.pi * 2*i*j/n)
            if not (abs(x) < 0.000001 and abs(y) < 0.000001):
                return 'NO'
    return 'YES'

def strconv(s):
    return [char for char in s]

n = int(input())
pts = strconv(input())
print(centre(n,pts))


I found an interesting problem on https://codeforces.com/problemset/problem/862/A:
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.

Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .

Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?

-----Input-----

The first line contains two integers n and x (1 ≤ n ≤ 100, 0 ≤ x ≤ 100) — the size of the set Dr. Evil owns, and the desired MEX.

The second line contains n distinct non-negative integers not exceeding 100 that represent the set.

-----Output-----

The only line should contain one integer — the minimal number of operations Dr. Evil should perform.

-----Examples-----
Input
5 3
0 4 5 6 7

Output
2

Input
1 0
0

Output
1

Input
5 0
1 2 3 4 5

Output
0

-----Note-----

For the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.

For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.

In the third test case the set is already evil.

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

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

l = [1] * 101

for v in map(int, input().split()):
	l[v] = 0

ans = int(not l[x])

for i in range(x):
	ans += l[i]

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/862/B:
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.

A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.

Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?

A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .

-----Input-----

The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 10^5).

The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.

It's guaranteed that the given graph is a tree.

-----Output-----

Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.

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

Output
0

Input
5
1 2
2 3
3 4
4 5

Output
2

-----Note-----

Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)

Bipartite graph definition: https://en.wikipedia.org/wiki/Bipartite_graph

In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.

In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).

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

n = int(input())

from collections import defaultdict
E = defaultdict(list)

for _ in range(n-1):
  a,b = map(int,input().split())
  a,b = a-1,b-1
  E[a].append(b)
  E[b].append(a)

stack = [1]
visited = {1}
c = 0
d = 0

turn = True

while stack:
  nstack = []
  for v in stack:
    for u in E[v]:
      if u not in visited:
        nstack.append(u)
        visited.add(u)

  if turn:
    d += len(stack)
  else:
    c += len(stack)
  turn = not turn
  stack = nstack

print(c*d-(n-1))


I found an interesting problem on https://codeforces.com/problemset/problem/862/C:
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.

Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 10^6.

-----Input-----

The only line contains two integers n and x (1 ≤ n ≤ 10^5, 0 ≤ x ≤ 10^5) — the number of elements in the set and the desired bitwise-xor, respectively.

-----Output-----

If there is no such set, print "NO" (without quotes).

Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.

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

Output
YES
1 2 4 5 7
Input
3 6

Output
YES
1 2 5

-----Note-----

You can read more about the bitwise-xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR

For the first sample $1 \oplus 2 \oplus 4 \oplus 5 \oplus 7 = 5$.

For the second sample $1 \oplus 2 \oplus 5 = 6$.

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

n, x = map(int, input().split())
if (n == 2 and x == 0):
    print("NO")
    quit()
a = 2**17
b = 2**18
ans = 0
print("YES")
if(n == 1):
    print(x)
    quit()
if (n == 2):
    print(x, 0)
    quit()
for i in range(n-3):
    print(i+1, end = " ")
    ans = (ans ^ (i+1))
if (ans == x):
    print(b, a, a+b)
else:
    print(0, a, a^ans^x)


I found an interesting problem on https://codeforces.com/problemset/problem/862/E:
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, c_{i} = a_{i} - b_{i} + j. Then f(j) = |c_1 - c_2 + c_3 - c_4... c_{n}|. More formally, $f(j) =|\sum_{i = 1}^{n}(- 1)^{i - 1} *(a_{i} - b_{i + j})|$.

Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer x_{i} to all elements in a in range [l_{i};r_{i}] i.e. they should add x_{i} to a_{l}_{i}, a_{l}_{i} + 1, ... , a_{r}_{i} and then they should calculate the minimum value of f(j) for all valid j.

Please help Mahmoud and Ehab.

-----Input-----

The first line contains three integers n, m and q (1 ≤ n ≤ m ≤ 10^5, 1 ≤ q ≤ 10^5) — number of elements in a, number of elements in b and number of queries, respectively.

The second line contains n integers a_1, a_2, ..., a_{n}. ( - 10^9 ≤ a_{i} ≤ 10^9) — elements of a.

The third line contains m integers b_1, b_2, ..., b_{m}. ( - 10^9 ≤ b_{i} ≤ 10^9) — elements of b.

Then q lines follow describing the queries. Each of them contains three integers l_{i} r_{i} x_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n,  - 10^9 ≤ x ≤ 10^9) — range to be updated and added value.

-----Output-----

The first line should contain the minimum value of the function f before any update.

Then output q lines, the i-th of them should contain the minimum value of the function f after performing the i-th update .

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

Output
0
9
0
0

-----Note-----

For the first example before any updates it's optimal to choose j = 0, f(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0.

After the first update a becomes {11, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| =...

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

def read(): return list(map(int, input().split(' ')))
n, m, q = read()
aa = read()
bb = read()
reqs = [read() for _ in range(q)]

asum = 0
bsum = 0
for i, (a, b) in enumerate(zip(aa, bb)):
    asum += a if i % 2 == 0 else -a
    bsum += b if i % 2 == 0 else -b

bpos = [bsum]
for i in range(len(aa), len(bb)):
    b = bb[i]

    rempos = i - len(aa)
    bsum += b if i % 2 == 0 else -b
    bsum -= bb[rempos] if rempos % 2 == 0 else -bb[rempos]
    bpos += [bsum if rempos % 2 == 1 else -bsum]

bpos = sorted(set(bpos))

def closest(arr, value):
    l = 0
    r = len(arr)
    while l + 1 < r:
        m = (l + r) // 2
        if arr[m] <= value:
            l = m
        else:
            r = m

    res = arr[l]
    if l + 1 < len(arr) and abs(arr[l + 1] - value) < abs(arr[l] - value):
        res = arr[l + 1]
    return res

print(abs(asum - closest(bpos, asum)))
for req in reqs:
    l, r, x = req
    l -= 1
    if (r - l) % 2 != 0:
        asum += x if l % 2 == 0 else -x
    print(abs(asum - closest(bpos, asum)))


I found an interesting problem on https://codeforces.com/problemset/problem/863/A:
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.

String t is called a palindrome, if it reads the same from left to right and from right to left.

For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strings "131" and "002010200", respectively, which are palindromes.

You are given some integer number x. Check if it's a quasi-palindromic number.

-----Input-----

The first line contains one integer number x (1 ≤ x ≤ 10^9). This number is given without any leading zeroes.

-----Output-----

Print "YES" if number x is quasi-palindromic. Otherwise, print "NO" (without quotes).

-----Examples-----
Input
131

Output
YES

Input
320

Output
NO

Input
2010200

Output
YES

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

import re
x = re.sub(r'0*$', '', input())
if x == x[::-1]:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/863/B:
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.

Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is w_{i}, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.

Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.

Help the party to determine minimum possible total instability!

-----Input-----

The first line contains one number n (2 ≤ n ≤ 50).

The second line contains 2·n integer numbers w_1, w_2, ..., w_2n, where w_{i} is weight of person i (1 ≤ w_{i} ≤ 1000).

-----Output-----

Print minimum possible total instability.

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

Output
1

Input
4
1 3 4 6 3 4 100 200

Output
5

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

n = int(input())
s = list(map(int, input().split()))
s = list(sorted(s))
ansm = 100000000
for i in range(len(s)):
    s1 = s[:i] + s[i+1:]
    for j in range(len(s1)):
        s2 = s1[:j]+s1[j+1:]
        ans = 0
        for i in range(1, 2*n - 2, 2):
            ans += s2[i] - s2[i-1]
        if ans < ansm:
            ansm = ans
print(ansm)


I found an interesting problem on https://codeforces.com/problemset/problem/863/C:
Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is "Bob", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, "Alice".

So now Ilya wants to compare his robots' performance in a simple game called "1-2-3". This game is similar to the "Rock-Paper-Scissors" game: both robots secretly choose a number from the set {1, 2, 3} and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: 3 beats 2, 2 beats 1 and 1 beats 3.

Both robots' programs make them choose their numbers in such a way that their choice in (i + 1)-th game depends only on the numbers chosen by them in i-th game.

Ilya knows that the robots will play k games, Alice will choose number a in the first game, and Bob will choose b in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all k games, so he asks you to predict the number of points they will have after the final game.

-----Input-----

The first line contains three numbers k, a, b (1 ≤ k ≤ 10^18, 1 ≤ a, b ≤ 3).

Then 3 lines follow, i-th of them containing 3 numbers A_{i}, 1, A_{i}, 2, A_{i}, 3, where A_{i}, j represents Alice's choice in the game if Alice chose i in previous game and Bob chose j (1 ≤ A_{i}, j ≤ 3).

Then 3 lines follow, i-th of them containing 3 numbers B_{i}, 1, B_{i}, 2, B_{i}, 3, where B_{i}, j represents Bob's choice in the game if Alice chose i in previous game and Bob chose j (1 ≤ B_{i}, j ≤ 3).

-----Output-----

Print two numbers. First of them has to be equal to the number of points Alice will have, and second of them must be Bob's score after k games.

-----Examples-----
Input
10 2 1
1 1 1
1 1 1
1 1 1
2 2...

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

def read(): return list(map(int, input().split(' ')))
k, a, b = read()
A = [read() for _ in range(3)]
B = [read() for _ in range(3)]

ra, rb = 0, 0

skipped = False
pos = { (a, b): 0 }
scoreA = { (a, b): 0 }
scoreB = { (a, b): 0 }
if (b - a) % 3 == 1:
    rb = 1
    #scoreB[(a, b)] = rb
elif (b - a) % 3 == 2:
    ra = 1
    #scoreA[(a, b)] = ra

i = 1
while i < k:
    na = A[a-1][b-1]
    nb = B[a-1][b-1]
    #print('game:', na, nb)

    if (na, nb) in pos and not skipped:
        cycleLen = i - pos[(na, nb)]
        cycleScoreA = ra - scoreA[(na, nb)]
        cycleScoreB = rb - scoreB[(na, nb)]

        skipCycles = (k - i) // cycleLen
        #print('Skip:', cycleLen, cycleScoreA, cycleScoreB, skipCycles)
        ra += cycleScoreA * skipCycles
        rb += cycleScoreB * skipCycles
        i += skipCycles * cycleLen

        skipped = True
    else:
        scoreA[(na, nb)] = ra
        scoreB[(na, nb)] = rb
        pos[(na, nb)] = i

        if (nb - na) % 3 == 1:
            rb += 1
            #print(i, '+b', ra, rb)
        elif (nb - na) % 3 == 2:
            ra += 1
            #print(i, '+a', ra, rb)

        i += 1
        a, b = na, nb

#print('Answer')
print(ra, rb)
#print('ScoreA')
#print(scoreA)
#print('ScoreB')
#print(scoreB)
#print('pos')
#print(pos)


I found an interesting problem on https://codeforces.com/problemset/problem/863/D:
You are given an array a of size n, and q queries to it. There are queries of two types:   1 l_{i} r_{i} — perform a cyclic shift of the segment [l_{i}, r_{i}] to the right. That is, for every x such that l_{i} ≤ x < r_{i} new value of a_{x} + 1 becomes equal to old value of a_{x}, and new value of a_{l}_{i} becomes equal to old value of a_{r}_{i};  2 l_{i} r_{i} — reverse the segment [l_{i}, r_{i}].

There are m important indices in the array b_1, b_2, ..., b_{m}. For each i such that 1 ≤ i ≤ m you have to output the number that will have index b_{i} in the array after all queries are performed.

-----Input-----

The first line contains three integer numbers n, q and m (1 ≤ n, q ≤ 2·10^5, 1 ≤ m ≤ 100).

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

Then q lines follow. i-th of them contains three integer numbers t_{i}, l_{i}, r_{i}, where t_{i} is the type of i-th query, and [l_{i}, r_{i}] is the segment where this query is performed (1 ≤ t_{i} ≤ 2, 1 ≤ l_{i} ≤ r_{i} ≤ n).

The last line contains m integer numbers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ n) — important indices of the array.

-----Output-----

Print m numbers, i-th of which is equal to the number at index b_{i} after all queries are done.

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

Output
3 3 1 5 2

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

import sys
import math
from collections import defaultdict,deque
def get(ind ,arr):
	n = len(arr)
	for i in range(n):
		t,l,r = arr[i]
		if t == 1:
			if l <= ind <= r:
				if ind == l:
					ind = r
				else:
					ind -= 1
			continue
		if t == 2:
			if l <=ind <= r:
				ind = (r - ind + l)
			continue
	return ind
n,q,m = map(int,sys.stdin.readline().split())
arr = list(map(int,sys.stdin.readline().split()))
l = []
for i in range(q):
	a,b,c = map(int,sys.stdin.readline().split())
	l.append([a,b,c])
l.reverse()
b = list(map(int,sys.stdin.readline().split()))
ans = []
for i in range(m):
	x = get(b[i],l)
	ans.append(arr[x -1])
print(*ans)


I found an interesting problem on https://codeforces.com/problemset/problem/863/F:
Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.

Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers:  1 l_{i} r_{i} v_{i} — for each x such that l_{i} ≤ x ≤ r_{i} a_{x} ≥ v_{i};  2 l_{i} r_{i} v_{i} — for each x such that l_{i} ≤ x ≤ r_{i} a_{x} ≤ v_{i}.

Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows:

$\operatorname{cos} t = \sum_{i = 1}^{n}(\operatorname{cnt}(i))^{2}$, where cnt(i) is the number of occurences of i in the array.

Help Ivan to determine minimum possible cost of the array that corresponds to the facts!

-----Input-----

The first line contains two integer numbers n and q (1 ≤ n ≤ 50, 0 ≤ q ≤ 100).

Then q lines follow, each representing a fact about the array. i-th line contains the numbers t_{i}, l_{i}, r_{i} and v_{i} for i-th fact (1 ≤ t_{i} ≤ 2, 1 ≤ l_{i} ≤ r_{i} ≤ n, 1 ≤ v_{i} ≤ n, t_{i} denotes the type of the fact).

-----Output-----

If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array.

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

Output
3

Input
3 1
1 1 3 2

Output
5

Input
3 2
1 1 3 2
2 1 3 2

Output
9

Input
3 2
1 1 3 2
2 1 3 1

Output
-1

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

import sys

def is_feasible(cnt,L,R):
	n = len(R)
	inter = [(L[i],R[i]) for i in range(n)]
	right = []
	feasible = True
	for x in range(n):
		for p in inter:
			if p[0] == x:
				right.append(p[1])

		while right and min(right) < x:
			right.remove(min(right))
		for quantity in range(cnt[x]):
			if right:
				right.remove(min(right))
			else:
				feasible = False
	return feasible

n,q = list(map(int,sys.stdin.readline().split()))
L = [0 for i in range(n)]
R = [n-1 for i in range(n)]
for restriction in range(q):
	t,l,r,v = list(map(int,sys.stdin.readline().split()))
	if t == 1:
		for k in range(l-1,r):
			L[k] = max(L[k],v-1)
	else:
		for k in range(l-1,r):
			R[k] = min(R[k],v-1)

is_possible = all(map(lambda x,y : x <= y,L,R))
if not is_possible:
	print(-1)
else:
	cnt = {x:0 for x in range(n)}
	for y in range(n):
		for x in range(n):
			if cnt[x] == y:
				cnt[x] += 1
				if not is_feasible(cnt,L,R):
					cnt[x] -= 1
	ans = sum([cnt[x]*cnt[x] for x in range(n)])
	print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/864/A:
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card.

Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with number he chose. For example, if Petya chose number 5 before the game he will take all cards on which 5 is written and if Vasya chose number 10 before the game he will take all cards on which 10 is written.

The game is considered fair if Petya and Vasya can take all n cards, and the number of cards each player gets is the same.

Determine whether Petya and Vasya can choose integer numbers before the game so that the game is fair.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 100) — number of cards. It is guaranteed that n is an even number.

The following n lines contain a sequence of integers a_1, a_2, ..., a_{n} (one integer per line, 1 ≤ a_{i} ≤ 100) — numbers written on the n cards.

-----Output-----

If it is impossible for Petya and Vasya to choose numbers in such a way that the game will be fair, print "NO" (without quotes) in the first line. In this case you should not print anything more.

In the other case print "YES" (without quotes) in the first line. In the second line print two distinct integers — number that Petya should choose and the number that Vasya should choose to make the game fair. If there are several solutions, print any of them.

-----Examples-----
Input
4
11
27
27
11

Output
YES
11 27

Input
2
6
6

Output
NO

Input
6
10
20
30
20
10
20

Output
NO

Input
6
1
1
2
2
3
3

Output
NO

-----Note-----

In the first example the game will be fair if, for example, Petya chooses number 11, and Vasya chooses number 27. Then the will take all cards — Petya will take cards 1 and 4, and Vasya will take cards 2 and 3. Thus, each of them will take exactly two cards.

In the second example fair game is impossible because the numbers written on the cards are...

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

from collections import defaultdict

n = int(input())
arr = []
nums = set()
f = defaultdict(int)

for _ in range(n):
	arr.append(int(input()))

if n % 2 == 1:
	print("NO")
	return

for num in arr:
	nums.add(num)
	f[num] += 1
	if len(nums) > 2:
		print("NO")
		return

nums = list(nums)

if len(nums) == 2:
	if f[nums[0]] == f[nums[1]]:
		print("YES")
		print(nums[0], nums[1])
		return

print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/864/B:
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.

Let A be a set of positions in the string. Let's call it pretty if following conditions are met:  letters on positions from A in the string are all distinct and lowercase;  there are no uppercase letters in the string which are situated between positions from A (i.e. there is no such j that s[j] is an uppercase letter, and a_1 < j < a_2 for some a_1 and a_2 from A).

Write a program that will determine the maximum number of elements in a pretty set of positions.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 200) — length of string s.

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

-----Output-----

Print maximum number of elements in pretty set of positions for string s.

-----Examples-----
Input
11
aaaaBaabAbA

Output
2

Input
12
zACaAbbaazzC

Output
3

Input
3
ABC

Output
0

-----Note-----

In the first example the desired positions might be 6 and 8 or 7 and 8. Positions 6 and 7 contain letters 'a', position 8 contains letter 'b'. The pair of positions 1 and 8 is not suitable because there is an uppercase letter 'B' between these position.

In the second example desired positions can be 7, 8 and 11. There are other ways to choose pretty set consisting of three elements.

In the third example the given string s does not contain any lowercase letters, so the answer is 0.

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

n = int(input())
s = input()
a = [set()]
k = 0
for i in range(len(s)):
    if s[i].upper() == s[i] and a[-1] != set():
        k += 1
        a.append(set())
    else:
        if s[i].lower() == s[i] and s[i] not in a[-1]:
            a[-1].add(s[i])
print(max([len(x) for x in a]))


I found an interesting problem on https://codeforces.com/problemset/problem/864/C:
A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the point x = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the point x = a and so on. Thus, the bus moves from x = 0 to x = a and back. Moving from the point x = 0 to x = a or from the point x = a to x = 0 is called a bus journey. In total, the bus must make k journeys.

The petrol tank of the bus can hold b liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.

There is a gas station in point x = f. This point is between points x = 0 and x = a. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain b liters of gasoline.

What is the minimum number of times the bus needs to refuel at the point x = f to make k journeys? The first journey starts in the point x = 0.

-----Input-----

The first line contains four integers a, b, f, k (0 < f < a ≤ 10^6, 1 ≤ b ≤ 10^9, 1 ≤ k ≤ 10^4) — the endpoint of the first bus journey, the capacity of the fuel tank of the bus, the point where the gas station is located, and the required number of journeys.

-----Output-----

Print the minimum number of times the bus needs to refuel to make k journeys. If it is impossible for the bus to make k journeys, print -1.

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

Output
4

Input
6 10 2 4

Output
2

Input
6 5 4 3

Output
-1

-----Note-----

In the first example the bus needs to refuel during each journey.

In the second example the bus can pass 10 units of distance without refueling. So the bus makes the whole first journey, passes 4 units of the distance of the second journey and arrives at the point with the gas station. Then it can refuel its tank, finish the second journey and...

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

a, b, f, k = list(map(int, input().split()))
now = b
path = 0
ans = 0
for i in range(k):
    if path == 0:
        if i == k - 1 and now >= a:
            break
        now -= f
        if now < 0:
            print(-1)
            return
        if 2 * (a - f) <= now:
            now -= a - f
        else:
            ans += 1
            now = b - (a - f)
        path = 1
    elif path == 1:
        if i == k - 1 and now >= a:
            break
        now -= a - f
        if now < 0:
            print(-1)
            return
        if 2 * f <= now:
            now -= f
        else:
            ans += 1
            now = b - f
        path = 0
if now < 0:
    print(-1)
    return
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/864/D:
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.

Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.

Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.

In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if x_{i} < y_{i}, where i is the first index in which the permutations x and y differ.

Determine the array Ivan will obtain after performing all the changes.

-----Input-----

The first line contains an single integer n (2 ≤ n ≤ 200 000) — the number of elements in Ivan's array.

The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the description of Ivan's array.

-----Output-----

In the first line print q — the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.

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

Output
2
1 2 4 3

Input
6
4 5 6 3 2 1

Output
0
4 5 6 3 2 1

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

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

-----Note-----

In the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers — this permutation is lexicographically minimal among all suitable.

In the second example Ivan does not need to change anything because...

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

n, ans, j = int(input()), 0, 1
a = [int(i) for i in input().split()]
res, c, lft = [0] * n, [0] * (n + 1), [0] * (n + 1)
for i in a:
    c[i] += 1
while j <= n and c[j]:
    j += 1
for i in range(len(a)):
    if c[a[i]] > 1:
        if lft[a[i]] or a[i] > j:
            ans += 1
            c[a[i]] -= 1
            res[i] = j
            j += 1
            while j <= n and c[j]:
                j += 1
        else:
            lft[a[i]] = 1
            res[i] = a[i]
    else:
        res[i] = a[i]
print(ans)
print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/864/E:
Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take t_{i} seconds to save i-th item. In addition, for each item, he estimated the value of d_{i} — the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if t_{i} ≥ d_{i}, then i-th item cannot be saved.

Given the values p_{i} for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in t_{a} seconds, and the item b — in t_{a} + t_{b} seconds after fire started.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of items in Polycarp's house.

Each of the following n lines contains three integers t_{i}, d_{i}, p_{i} (1 ≤ t_{i} ≤ 20, 1 ≤ d_{i} ≤ 2 000, 1 ≤ p_{i} ≤ 20) — the time needed to save the item i, the time after which the item i will burn completely and the value of item i.

-----Output-----

In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m — the number of items in the desired set. In the third line print m distinct integers — numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.

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

Output
11
2
2 3

Input
2
5 6 1
3 3 5

Output
1
1
1

-----Note-----

In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.

In the second example...

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

from sys import stdin
input = stdin.readline
n = int(input())
T = 2001
t, d, p, idx = [], [], [], []
ans = []
arr = []
for i in range(n):
    a, b, c = map(int, input().split())
    arr.append([a, b, c, i])
arr.sort(key=lambda x: x[1])
for i in arr:
    t.append(i[0]); d.append(i[1]); p.append(i[2]); idx.append(i[3])
dp = [[0 for j in range(n)] for i in range(T)]
for time in range(1, T):
    for i in range(n):
        #dp[time][i] = max(dp[time - 1][i], dp[time][i - 1])
        dp[time][i] = dp[time][i - 1]
        if d[i] > time >= t[i]:
            if i:
                dp[time][i] = max(dp[time][i], p[i] + dp[time - t[i]][i - 1])
            else:
                dp[time][i] = p[i]
b = [0, [0 ,0]]
for i in range(T):
    for j in range(n):
        if b[0] < dp[i][j]:
            b = [dp[i][j], [i, j]]
print(b[0])
b = b[1]
while dp[b[0]][b[1]] and b[0] > -1:
    if b[1] and dp[b[0]][b[1]] != dp[b[0]][b[1] - 1]:
        ans.append(b[1])
        b[0] -= t[b[1]]
    elif b[1] == 0:
        if dp[b[0]][b[1]]:
            ans.append(b[1])
        break
    b[1] -= 1
print(len(ans))
for i in ans[::-1]:
    print(idx[i] + 1, end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/865/B:
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.

It is known that the i-th contestant will eat s_{i} slices of pizza, and gain a_{i} happiness for each slice of type 1 pizza they eat, and b_{i} happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?

-----Input-----

The first line of input will contain integers N and S (1 ≤ N ≤ 10^5, 1 ≤ S ≤ 10^5), the number of contestants and the number of slices per pizza, respectively. N lines follow.

The i-th such line contains integers s_{i}, a_{i}, and b_{i} (1 ≤ s_{i} ≤ 10^5, 1 ≤ a_{i} ≤ 10^5, 1 ≤ b_{i} ≤ 10^5), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.

-----Output-----

Print the maximum total happiness that can be achieved.

-----Examples-----
Input
3 12
3 5 7
4 6 7
5 9 5

Output
84

Input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6

Output
314

-----Note-----

In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.

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

from collections import namedtuple

Member = namedtuple('Member', ['parts', 'a_happy', 'b_happy'])

def happy_diff(m):
    return m.a_happy - m.b_happy

def main():
    input_strings_members, parts = read_input()
    a_members, b_members, other_members = prepare_members(input_strings_members)
    print(count_parts(a_members, b_members, other_members, parts))

def read_input():
    counts_str = input().split()
    members_count, parts = list(map(int, counts_str))
    return [input() for _ in range(members_count)], parts

def prepare_members(input_strings_members):
    a_members = []
    b_members = []
    other_members = []
    for line in input_strings_members:
        m = Member(*list(map(int, line.split())))
        if happy_diff(m) > 0:
            a_members.append(m)
        elif happy_diff(m) < 0:
            b_members.append(m)
        else:
            other_members.append(m)
    return a_members, b_members, other_members

def count_parts(a_members, b_members, other_members, parts_in_one):
    a_members.sort(key=lambda m: happy_diff(m), reverse=False)
    a_modulo = sum(m.parts for m in a_members) % parts_in_one

    a_modulo_members, a_happy_members = split_members_into_happy_groups(a_members, a_modulo)
    a_happy = sum(m.a_happy * m.parts for m in a_happy_members)

    b_members.sort(key=lambda m: happy_diff(m), reverse=True)
    b_modulo = sum(m.parts for m in b_members) % parts_in_one

    b_modulo_members, b_happy_members = split_members_into_happy_groups(b_members, b_modulo)
    b_happy = sum(m.b_happy * m.parts for m in b_happy_members)

    last_happy = count_last_pizzas_happy(a_modulo_members, b_modulo_members, other_members, parts_in_one)

    return a_happy + b_happy + last_happy

def split_members_into_happy_groups(members, modulo):
    modulo_members = []
    happy_members = []
    current_modulo = 0

    for i in range(len(members)):
        m = members[i]
        new_current_modulo = current_modulo + m.parts
        if new_current_modulo < modulo:
           ...


I found an interesting problem on https://codeforces.com/problemset/problem/865/D:
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.

-----Input-----

Input begins with an integer N (2 ≤ N ≤ 3·10^5), the number of days.

Following this is a line with exactly N integers p_1, p_2, ..., p_{N} (1 ≤ p_{i} ≤ 10^6). The price of one share of stock on the i-th day is given by p_{i}.

-----Output-----

Print the maximum amount of money you can end up with at the end of N days.

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

Output
20

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

Output
41

-----Note-----

In the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is  - 5 - 4 + 9 + 12 - 2 + 10 = 20.

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

from heapq import heappush,heappop
n=int(input())
ar=list(map(int,input().split()))
unsed=[]
selled=[]
sm=0
for x in ar:
    U,S=len(unsed),len(selled)
    u=heappop(unsed) if U else float('inf')
    s=heappop(selled) if S else float('inf')
    y=min(u,s)
    if(y<x):
        if(u==y):
            sm+=x-y
            if(S):heappush(selled,s)
            heappush(selled,x)
        else:
            sm+=x-y
            heappush(unsed,y)
            if(U):heappush(unsed,u)
            heappush(selled,x)
    else:
        if(S):heappush(selled,s)
        if(U):heappush(unsed,u)
        heappush(unsed,x)
print(sm)


I found an interesting problem on https://codeforces.com/problemset/problem/867/A:
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.

You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last n days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last n days, or not.

-----Input-----

The first line of input contains single integer n (2 ≤ n ≤ 100) — the number of days.

The second line contains a string of length n consisting of only capital 'S' and 'F' letters. If the i-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence.

-----Output-----

Print "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise.

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

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

Output
NO

Input
2
SF

Output
YES

Input
10
FFFFFFFFFF

Output
NO

Input
10
SSFFSFFSFF

Output
YES

-----Note-----

In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO".

In the second example you just flew from Seattle to San Francisco, so the answer is "YES".

In the third example you stayed the whole period in San Francisco, so the answer is "NO".

In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of π in binary representation. Not very useful information though.

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

n = int(input())
s = input()
sf = 0
fs = 0
last = s[0]
for i in range(n):
    if s[i] != last:
        if last == 'F':
            fs += 1
        else:
            sf += 1
        last = s[i]
if sf > fs:
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/868/B:
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.

The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time h hours, m minutes, s seconds.

Last time Misha talked with the coordinator at t_1 o'clock, so now he stands on the number t_1 on the clock face. The contest should be ready by t_2 o'clock. In the terms of paradox it means that Misha has to go to number t_2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.

Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).

Given the hands' positions, t_1, and t_2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from t_1 to t_2 by the clock face.

-----Input-----

Five integers h, m, s, t_1, t_2 (1 ≤ h ≤ 12, 0 ≤ m, s ≤ 59, 1 ≤ t_1, t_2 ≤ 12, t_1 ≠ t_2).

Misha's position and the target time do not coincide with the position of any hand.

-----Output-----

Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise.

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

-----Examples-----
Input
12 30 45 3 11

Output
NO

Input
12 0 1 12 1

Output
YES

Input
3 47 0 4 9

Output
YES

-----Note-----

The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the...

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

def check1(h):
	nonlocal t1,t2
	if(h==t1 or h==t2):
		return -1
	if(h>min(t1,t2) and h<max(t1,t2)):
		return 1
	else:
		return 0

def check2(m):
	if(m==5*t1 or m==5*t2):
		return -1
	if(m>5*min(t1,t2) and m<5*max(t1,t2)):
		return 1
	else:
		return 0

h,m,s,t1,t2 = list(map(int,input().split()))
if(m!=0 or s!=0):
	h+=0.5
if(s!=0):
	m+=0.5
if(h>12):
	h-=12

l=[check1(h),check2(m),check2(s)]
for i in range(len(l)-1,-1,-1):
	if(l[i] == -1):
		l.pop(i)
flag=0
for val in l:
	if(val!=l[0]):
		flag=1
		break
if(flag):
	print("NO")
else:
	print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/868/C:
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.

k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.

Determine if Snark and Philip can make an interesting problemset!

-----Input-----

The first line contains two integers n, k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 4) — the number of problems and the number of experienced teams.

Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.

-----Output-----

Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise.

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

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

Output
NO

Input
3 2
1 0
1 1
0 1

Output
YES

-----Note-----

In the first example you can't make any interesting problemset, because the first team knows all problems.

In the second example you can choose the first and the third problems.

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

n,k=map(int, input().split())
vis = [0] * 17
for _ in range(n):
	a = list(map(int, input().split()))
	vis[sum(a[i]*(1<<i) for i in range(k))] = 1
flag=0
for i in range(16):
	for j in range(16):
		if i&j==0 and vis[i] and vis[j]: flag=1
print("YES" if flag else "NO")


I found an interesting problem on https://codeforces.com/problemset/problem/869/A:
Rock... Paper!

After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.

A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted by x_1, x_2, ..., x_{n} and y_1, y_2, ..., y_{n} respectively. They reveal their sequences, and repeat until all of 2n integers become distinct, which is the only final state to be kept and considered.

Then they count the number of ordered pairs (i, j) (1 ≤ i, j ≤ n) such that the value x_{i} xor y_{j} equals to one of the 2n integers. Here xor means the bitwise exclusive or operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.

Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.

-----Input-----

The first line of input contains a positive integer n (1 ≤ n ≤ 2 000) — the length of both sequences.

The second line contains n space-separated integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 2·10^6) — the integers finally chosen by Koyomi.

The third line contains n space-separated integers y_1, y_2, ..., y_{n} (1 ≤ y_{i} ≤ 2·10^6) — the integers finally chosen by Karen.

Input guarantees that the given 2n integers are pairwise distinct, that is, no pair (i, j) (1 ≤ i, j ≤ n) exists such that one of the following holds: x_{i} = y_{j}; i ≠ j and x_{i} = x_{j}; i ≠ j and y_{i} = y_{j}.

-----Output-----

Output one line — the name of the winner, that is, "Koyomi" or "Karen" (without quotes). Please be aware of the capitalization.

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

Output
Karen

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

Output
Karen

-----Note-----

In the first example, there are 6 pairs satisfying the constraint: (1, 1), (1, 2), (2, 1), (2, 3), (3, 2) and (3, 3). Thus, Karen wins since 6 is an even number.

In the second example, there are 16 such pairs, and Karen...

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

n = int(input())
data = list(map(int, input().split()))
data2 = list(map(int, input().split()))
print("Karen")


I found an interesting problem on https://codeforces.com/problemset/problem/869/B:
Even if the world is full of counterfeits, I still regard it as wonderful.

Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.

The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes the factorial of integer a, that is, a! = 1 × 2 × ... × a. Specifically, 0! = 1.

Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of b! years, that is, [Image]. Note that when b ≥ a this value is always integer.

As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge.

-----Input-----

The first and only line of input contains two space-separated integers a and b (0 ≤ a ≤ b ≤ 10^18).

-----Output-----

Output one line containing a single decimal digit — the last digit of the value that interests Koyomi.

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

Output
2

Input
0 10

Output
0

Input
107 109

Output
2

-----Note-----

In the first example, the last digit of $\frac{4 !}{2 !} = 12$ is 2;

In the second example, the last digit of $\frac{10 !}{0 !} = 3628800$ is 0;

In the third example, the last digit of $\frac{109 !}{107 !} = 11772$ is 2.

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

a, b = map(int, input().split())
if b - a > 10:
    print(0)
else:
    mul = 1
    for i in range(a + 1, b + 1):
        mul *= i
    print(mul % 10)


I found an interesting problem on https://codeforces.com/problemset/problem/869/C:
— This is not playing but duty as allies of justice, Nii-chan!

— Not allies but justice itself, Onii-chan!

With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!

There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of a, b and c distinct islands respectively.

Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster.

The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998 244 353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.

-----Input-----

The first and only line of input contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 5 000) — the number of islands in the red, blue and purple clusters, respectively.

-----Output-----

Output one line containing an integer — the number of different ways to build bridges, modulo 998 244 353.

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

Output
8

Input
1 2 2

Output
63

Input
1 3 5

Output
3264

Input
6 2 9

Output
813023575

-----Note-----

In the first example, there are 3 bridges that can possibly be built, and no setup of bridges violates the restrictions. Thus the answer is 2^3 = 8.

In the second example, the upper two structures in the figure below are instances of valid ones, while the lower two are invalid due to the blue and purple clusters, respectively. [Image]

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

a, b, c = map(int, input().split())
M = 998244353
def calc(a, b) :
	if a > b:
		a, b = b, a
	ans = 0
	t = 1
	for i in range(a + 1):
		ans = (ans + t) % M
		t = t * (a - i) * (b - i) * pow(i + 1, M - 2, M) % M
	return ans
ans = calc(a, b) * calc(b, c) * calc(a, c) % M
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/870/A:
You are given two lists of non-zero digits.

Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the lengths of the first and the second lists, respectively.

The second line contains n distinct digits a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 9) — the elements of the first list.

The third line contains m distinct digits b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 9) — the elements of the second list.

-----Output-----

Print the smallest pretty integer.

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

Output
25

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

Output
1

-----Note-----

In the first example 25, 46, 24567 are pretty, as well as many other integers. The smallest among them is 25. 42 and 24 are not pretty because they don't have digits from the second list.

In the second example all integers that have at least one digit different from 9 are pretty. It's obvious that the smallest among them is 1, because it's the smallest positive integer.

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

l, lt = input().split()
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a = sorted(a)
b = sorted(b)
for i in a:
    if i in b:
        print(i)
        return
if min(a) < min(b):
    print(str(min(a)) + str(min(b)))
else:
    print(str(min(b)) + str(min(a)))


I found an interesting problem on https://codeforces.com/problemset/problem/870/B:
You are given an array a_1, a_2, ..., a_{n} consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?

Definitions of subsegment and array splitting are given in notes.

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤  10^5) — the size of the array a and the number of subsegments you have to split the array to.

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

-----Output-----

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.

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

Output
5

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

Output
-5

-----Note-----

A subsegment [l,  r] (l ≤ r) of array a is the sequence a_{l},  a_{l} + 1,  ...,  a_{r}.

Splitting of array a of n elements into k subsegments [l_1, r_1], [l_2, r_2], ..., [l_{k}, r_{k}] (l_1 = 1, r_{k} = n, l_{i} = r_{i} - 1 + 1 for all i > 1) is k sequences (a_{l}_1, ..., a_{r}_1), ..., (a_{l}_{k}, ..., a_{r}_{k}).

In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.

In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.

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

n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
x=0
if k==1:
    x=min(a)
elif k==2:
    x=max(a[0],a[n-1])
else:
    x=max(a)
print(x)

#print(" ".join(map(str,a)))


I found an interesting problem on https://codeforces.com/problemset/problem/870/C:
You are given several queries. In the i-th query you are given a single positive integer n_{i}. You are to represent n_{i} as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.

An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.

-----Input-----

The first line contains single integer q (1 ≤ q ≤ 10^5) — the number of queries.

q lines follow. The (i + 1)-th line contains single integer n_{i} (1 ≤ n_{i} ≤ 10^9) — the i-th query.

-----Output-----

For each query print the maximum possible number of summands in a valid splitting to composite summands, or -1, if there are no such splittings.

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

Output
3

Input
2
6
8

Output
1
2

Input
3
1
2
3

Output
-1
-1
-1

-----Note-----

12 = 4 + 4 + 4 = 4 + 8 = 6 + 6 = 12, but the first splitting has the maximum possible number of summands.

8 = 4 + 4, 6 can't be split into several composite summands.

1, 2, 3 are less than any composite number, so they do not have valid splittings.

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

#!/usr/bin/env python3

# min odd non-prime is 9
# min even non-prime in 4, NO even numbers gt 2 are primes

def m(n):
    if n == 9:
        return 1
    elif n < 4:
        return -1
    c = 0
    if n % 2:
        if n >= 13:
            c += 1
            n -= 9
        else:
            return -1
    if not ((n - 2) % 4):
        n -= 2
    if not n % 4:
        return c + n // 4

def __starting_point():
    for i in range(int(input())):
        print(m(int(input())))

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/870/E:
You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.

You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 10^9 + 7.

-----Input-----

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

n lines follow. The (i + 1)-th of these lines contains two integers x_{i}, y_{i} ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — coordinates of the i-th point.

It is guaranteed that all points are distinct.

-----Output-----

Print the number of possible distinct pictures modulo 10^9 + 7.

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

Output
16

Input
2
-1 -1
0 1

Output
9

-----Note-----

In the first example there are two vertical and two horizontal lines passing through the points. You can get pictures with any subset of these lines. For example, you can get the picture containing all four lines in two ways (each segment represents a line containing it). The first way:   [Image]   The second way:   [Image]

In the second example you can work with two points independently. The number of pictures is 3^2 = 9.

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

n = int(input())
disjointSet = [-1] * n
def root(x, level=200):
    dp = []
    while disjointSet[x] >= 0:
        dp.append(x)
        x = disjointSet[x]
    for i in dp:
        disjointSet[i] = x
    return x

def join(x, y):
    r1, r2 = root(x), root(y)
    if r1 == r2:
        return
    disjointSet[r2] = r1

points = []
vertPoints = {}
horizPoints = {}
for i in range(n):
    a, b = map(int, input().split())
    points.append((a, b))
    if a in vertPoints:
        join(i, vertPoints[a])
    else:
        vertPoints[a] = i
    if b in horizPoints:
        join(i, horizPoints[b])
    else:
        horizPoints[b] = i

sets = {}
for i in range(n):
    r = root(i)
    if r in sets:
        sets[r].append(points[i])
    else:
        sets[r] = [points[i]]

ans = 1
for i in sets:
    s = sets[i]
    horiz = [x for x,y in s]
    vert = [y for x,y in s]
    tmp = len(set(horiz)) + len(set(vert))
    if tmp <= len(s):
        ans *= 2 ** tmp
    else:
        ans *= 2 ** tmp - 1
    ans %= 10 ** 9 + 7

print(ans % (10 ** 9 + 7))