I found an interesting problem on https://codeforces.com/problemset/problem/935/D:
Ancient Egyptians are known to have used a large set of symbols $\sum$ to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S_1 and S_2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set $\sum$ have equal probability for being in the position of any erased symbol.

Fifa challenged Fafa to calculate the probability that S_1 is lexicographically greater than S_2. Can you help Fafa with this task?

You know that $|\sum|= m$, i. e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y.

We can prove that the probability equals to some fraction $P / Q$, where P and Q are coprime integers, and $Q \neq 0 \text{mod}(10^{9} + 7)$. Print as the answer the value $R = P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, i. e. such a non-negative integer less than 10^9 + 7, such that $R \cdot Q \equiv P \operatorname{mod}(10^{9} + 7)$, where $a \equiv b \text{mod}(m)$ means that a and b give the same remainders when divided by m.

-----Input-----

The first line contains two integers n and m (1 ≤ n,  m ≤ 10^5) — the length of each of the two words and the size of the alphabet $\sum$, respectively.

The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ m) — the symbols of S_1. If a_{i} = 0, then the symbol at position i was erased.

The third line contains n integers representing S_2 with the same format as S_1.

-----Output-----

Print the value $P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, where P and Q are coprime and $P / Q$ is the answer to the problem.

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

Output
500000004

Input
1 2
1
0

Output
0

Input
7 26
0 15 12 9 13 0 14
11 1 0 13 15...

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

import sys

MOD = 1000000007

def solve(io):
  N = io.readInt()
  M = io.readInt()
  S = io.readIntArray(N)
  T = io.readIntArray(N)

  P = 0
  Q = 1
  A = 1
  B = 1
  for i in range(0, N):
    if S[i] == 0 or T[i] == 0:
      if S[i] == 0 and T[i] == 0:
        gtTop = M * (M - 1) * A
        gtBot = 2 * M * M * B
        eqTop = 1
        eqBot = M
      elif S[i] == 0:
        gtTop = (M - T[i]) * A
        gtBot = M * B
        eqTop = 1
        eqBot = M
      elif T[i] == 0:
        gtTop = (S[i] - 1) * A
        gtBot = M * B
        eqTop = 1
        eqBot = M
    elif S[i] > T[i]:
      gtTop = A
      gtBot = B
      eqTop = 0
      eqBot = 1
    elif S[i] < T[i]:
      gtTop = 0
      gtBot = 1
      eqTop = 0
      eqBot = 1
    elif S[i] == T[i]:
      gtTop = 0
      gtBot = 1
      eqTop = 1
      eqBot = 1
    P, Q = P * gtBot + gtTop * Q, Q * gtBot
    P %= MOD
    Q %= MOD
    A = (A * eqTop) % MOD
    B = (B * eqBot) % MOD
    if S[i] != 0 and T[i] != 0 and S[i] != T[i]:
      break
  io.println((P * modinv(Q, MOD)) % MOD)

def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

def modinv(a, m):
	g, x, _ = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

# +---------------------+
# | TEMPLATE CODE BELOW |
# |    DO NOT MODIFY    |
# +---------------------+

# TODO: maybe reading byte-by-byte is faster than reading and parsing tokens.
class IO:
  input = None
  output = None
  raw = ""
  buf = []
  pos = 0

  def __init__(self, inputStream, outputStream):
    self.input = inputStream
    self.output = outputStream

  def readToBuffer(self):
    self.raw = self.input.readline().rstrip('\n')
    self.buf = self.raw.split()
    self.pos = 0
...


I found an interesting problem on https://codeforces.com/problemset/problem/935/E:
Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.

An Ahmes arithmetic expression can be defined as:   "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer;  "(E_1 op E_2)" is an Ahmes arithmetic expression, where E_1 and E_2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ).  For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions.

On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task:

Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators.

-----Input-----

The first line contains a string E (1 ≤ |E| ≤ 10^4) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'.

The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively.

It is guaranteed that P + M =  the number of erased operators.

-----Output-----

Print one line containing the answer to the problem.

-----Examples-----
Input
(1?1)
1 0

Output
2

Input
(2?(1?2))
1 1

Output
1

Input
((1?(5?7))?((6?2)?7))
3 2

Output
18

Input
((1?(5?7))?((6?2)?7))
2 3

Output
16

-----Note-----  The first sample will be (1 + 1)  =  2.  The second sample will be (2 + (1 - 2))  =  1.  The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7))  =  18.  The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) -...

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

from math import inf

class Node:
    def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0):
        self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ
    def __str__(self):
        return "Node"

memo = {}

def Memoize(node, p, maxValue, minValue):
    if not node in memo:
        memo.update({node : {p : [maxValue, minValue]} })
    else:
        memo[node].update({p : [maxValue, minValue]})

def ExpMaxValue(root: Node, p):

    m = root.signQ - p
    """if root.signQ == 1:
        if p == 1:
            return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value]
        else:
            return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]"""

    if root.signQ == 0:
        return [root.value, root.value]

    if root in memo:
        if p in memo[root]:
            return memo[root][p]

    if m == 0:
        value = ExpMaxValue(root.leftExp, root.leftExp.signQ)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ)[0]
        Memoize(root, p, value, value)
        return [value, value]
    if p == 0:
        value = ExpMaxValue(root.leftExp, 0)[0] - ExpMaxValue(root.rightExp, 0)[0]
        Memoize(root, p, value, value)
        return [value, value]

    maxValue = -inf
    minValue = inf
    if m >= p:
        for pQMid in range(2):
            pQLeftMin = min(p - pQMid, root.leftExp.signQ)
            for pQLeft in range(pQLeftMin + 1):
                if root.leftExp.signQ - pQLeft + (1 - pQMid) > m:
                    continue

                resLeft = ExpMaxValue(root.leftExp, pQLeft)
                resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft)

                if pQMid == 1:
                    maxValue = max(resLeft[0] + resRight[0], maxValue)
                    minValue = min(resLeft[1] + resRight[1], minValue)
                else:
                    maxValue = max(resLeft[0] - resRight[1], maxValue)
     ...


I found an interesting problem on https://codeforces.com/problemset/problem/936/A:
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.

During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.

It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

-----Input-----

The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 10^18).

-----Output-----

Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10^{ - 9}.

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

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

Output
6.5

Input
4 2 20

Output
20.0

-----Note-----

In the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for $\frac{3}{6}$. Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for $\frac{1}{12}$. Thus, after four minutes the chicken will be cooked for $\frac{3}{6} + \frac{1}{12} = \frac{7}{12}$. Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready $\frac{7}{12} + \frac{2.5}{6} = 1$.

In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.

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

from math import ceil
k, d, t = list(map(int, input().split()))
d = ceil(k / d) * d
r, t = divmod(t, k + (d - k) * .5)
print(r * d + min(k, t) + max(t - k, 0) * 2)


I found an interesting problem on https://codeforces.com/problemset/problem/937/A:
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.

As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:   At least one participant should get a diploma.  None of those with score equal to zero should get awarded.  When someone is awarded, all participants with score not less than his score should also be awarded.

Determine the number of ways to choose a subset of participants that will receive the diplomas.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of participants.

The next line contains a sequence of n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 600) — participants' scores.

It's guaranteed that at least one participant has non-zero score.

-----Output-----

Print a single integer — the desired number of ways.

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

Output
3

Input
3
1 1 1

Output
1

Input
4
42 0 0 42

Output
1

-----Note-----

There are three ways to choose a subset in sample case one.  Only participants with 3 points will get diplomas.  Participants with 2 or 3 points will get diplomas.  Everyone will get a diploma!

The only option in sample case two is to award everyone.

Note that in sample case three participants with zero scores cannot get anything.

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

n=input()
a=set(map(int,input().split()))
if 0 in a:
    print(len(a)-1)
else:
    print(len(a))


I found an interesting problem on https://codeforces.com/problemset/problem/937/B:
The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.

The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches $2 \cdot x, 3 \cdot x, \ldots, \lfloor \frac{y}{x} \rfloor \cdot x$.

Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.

In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.

-----Input-----

The only line contains two integers p and y (2 ≤ p ≤ y ≤ 10^9).

-----Output-----

Output the number of the highest suitable branch. If there are none, print -1 instead.

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

Output
5

Input
3 4

Output
-1

-----Note-----

In the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.

It immediately follows that there are no valid branches in second sample case.

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

def f(n):
    i=2
    while i*i<=n:
        if n%i==0:
            return False
        i+=1
    return True
p,y=list(map(int,input().split()))
if p>100000:
    i=y
    while not f(i):
        if i==p:
            print(-1)
            return
        i-=1
    print(i)
else:
    for i in range(y,p,-1):
        for j in range(2,p+1):
            if i%j==0:
                break
        else:
            print(i)
            break
    else:
        print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/938/A:
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.

Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.

You are given a word s. Can you predict what will it become after correction?

In this problem letters a, e, i, o, u and y are considered to be vowels.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 100) — the number of letters in word s before the correction.

The second line contains a string s consisting of exactly n lowercase Latin letters — the word before the correction.

-----Output-----

Output the word s after the correction.

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

Output
werd

Input
4
word

Output
word

Input
5
aaeaa

Output
a

-----Note-----

Explanations of the examples:  There is only one replace: weird $\rightarrow$ werd; No replace needed since there are no two consecutive vowels; aaeaa $\rightarrow$ aeaa $\rightarrow$ aaa $\rightarrow$ aa $\rightarrow$ a.

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

n = input()
s = input()
bad = "aeiouy"
while True:
    ok = True
    for i in range(1, len(s)):
        if (s[i] in bad) and (s[i-1] in bad):
            s = s[:i] + s[i+1:]
            ok = False
            break
    if(ok):
        print(s)
        break


I found an interesting problem on https://codeforces.com/problemset/problem/938/B:
You and your friend are participating in a TV show "Run For Your Prize".

At the start of the show n prizes are located on a straight line. i-th prize is located at position a_{i}. Positions of all prizes are distinct. You start at position 1, your friend — at position 10^6 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.

You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.

Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.

What is the minimum number of seconds it will take to pick up all the prizes?

-----Input-----

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

The second line contains n integers a_1, a_2, ..., a_{n} (2 ≤ a_{i} ≤ 10^6 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

-----Output-----

Print one integer — the minimum number of seconds it will take to collect all prizes.

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

Output
8

Input
2
2 999995

Output
5

-----Note-----

In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.

In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.

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

v = 'aiouey'
n = int(input())
a = list(map(int,input().split()))
fr = 1000000
mi = 0
for i in a:
    mi = max(min(fr-i,i-1),mi)
print(mi)


I found an interesting problem on https://codeforces.com/problemset/problem/938/C:
Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m × m of this matrix contains at least one zero.

Consider the following problem:

You are given two integers n and m. You have to construct an m-free square matrix of size n × n such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.

You don't have to solve this problem. Instead, you have to construct a few tests for it.

You will be given t numbers x_1, x_2, ..., x_{t}. For every $i \in [ 1, t ]$, find two integers n_{i} and m_{i} (n_{i} ≥ m_{i}) such that the answer for the aforementioned problem is exactly x_{i} if we set n = n_{i} and m = m_{i}.

-----Input-----

The first line contains one integer t (1 ≤ t ≤ 100) — the number of tests you have to construct.

Then t lines follow, i-th line containing one integer x_{i} (0 ≤ x_{i} ≤ 10^9).

Note that in hacks you have to set t = 1.

-----Output-----

For each test you have to construct, output two positive numbers n_{i} and m_{i} (1 ≤ m_{i} ≤ n_{i} ≤ 10^9) such that the maximum number of 1's in a m_{i}-free n_{i} × n_{i} matrix is exactly x_{i}. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer  - 1.

-----Example-----
Input
3
21
0
1

Output
5 2
1 1
-1

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

n = int(input())
for x in range(n):
    x = int(input())
    if x == 0:
        print(1, 1)
    else:
        flag = True
        for d in range(1, int(x**0.5)+2):
            if x % d == 0:
                s = x // d
                n = (s + d)//2
               # if int(n) != n:
                  #  continue
                nm = s - n
                if nm == 0:
                    continue
                m = n//nm
                if (m>0) and (n**2 - (n//m)**2 == x):
                    print(n, m)
                    flag = False
                    break
        if flag:
            print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/938/D:
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.

There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city v_{i} to city u_{i} (and from u_{i} to v_{i}), and it costs w_{i} coins to use this route.

Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is a_{i} coins.

You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).

Formally, for every $i \in [ 1, n ]$ you have to calculate $\operatorname{min}_{j = 1} 2 d(i, j) + a_{j}$, where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.

-----Input-----

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

Then m lines follow, i-th contains three integers v_{i}, u_{i} and w_{i} (1 ≤ v_{i}, u_{i} ≤ n, v_{i} ≠ u_{i}, 1 ≤ w_{i} ≤ 10^12) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input.

The next line contains n integers a_1, a_2, ... a_{k} (1 ≤ a_{i} ≤ 10^12) — price to attend the concert in i-th city.

-----Output-----

Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).

-----Examples-----
Input
4 2
1 2 4
2 3 7
6 20 1...

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

from __future__ import division, print_function
py2 = round(0.5)

if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import BytesIO, IOBase

# FastIO for PyPy2 and PyPy3 by Pajenegod
class FastI(object):
    def __init__(self, fd=0, buffersize=2**14):
        self.stream = stream = BytesIO(); self.bufendl = 0
        def read2buffer():
            curpos = stream.tell(); s = os.read(fd, buffersize + os.fstat(fd).st_size)
            stream.seek(0,2); stream.write(s); stream.seek(curpos); return s
        self.read2buffer = read2buffer
    def read(self):
        while self.read2buffer(): pass
        return self.stream.read() if self.stream.tell() else self.stream.getvalue()
    def readline(self):
        while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b'\n') + (not s)
        self.bufendl -= 1; return self.stream.readline()
    def input(self): return self.readline().rstrip(b'\r\n')

class FastO(IOBase):
    def __init__(self, fd=1):
        stream = BytesIO()
        self.flush = lambda: os.write(fd, stream.getvalue()) + stream.truncate(0) + stream.seek(0)
        self.write = stream.write if py2 else lambda s: stream.write(s.encode())

sys.stdin, sys.stdout = FastI(), FastO()
input = sys.stdin.readline

big = 3E12

class segheap:
    def __init__(self,data):
        n = len(data)
        m = 1
        while m<n:m*=2
        self.n = n
        self.m = m

        self.data = [big]*(2*m)
        for i in range(n):
            self.data[i+m] = data[i]
        for i in reversed(range(m)):
            self.data[i] = min(self.data[2*i],self.data[2*i+1])

    def mini(self):
        i = 1
        while i<self.m:
            if self.data[i]==self.data[2*i]:
                i = 2*i
            else:
                i = 2*i+1
        i -= self.m
        self.setter(i,big)
        return i
    def setter(self,ind,val):
        ind += self.m
        if val<self.data[ind]:
            while ind>0 and self.data[ind]>val:
        ...


I found an interesting problem on https://codeforces.com/problemset/problem/938/E:
You are given an array a of length n. We define f_{a} the following way:

  Initially f_{a} = 0, M = 1;  for every 2 ≤ i ≤ n if a_{M} < a_{i} then we set f_{a} = f_{a} + a_{M} and then set M = i.

Calculate the sum of f_{a} over all n! permutations of the array a modulo 10^9 + 7.

Note: two elements are considered different if their indices differ, so for every array a there are exactly n! permutations.

-----Input-----

The first line contains integer n (1 ≤ n ≤  1 000 000) — the size of array a.

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

-----Output-----

Print the only integer, the sum of f_{a} over all n! permutations of the array a modulo 10^9 + 7.

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

Output
1
Input
3
1 1 2

Output
4

-----Note-----

For the second example all the permutations are:

  p = [1, 2, 3] : f_{a} is equal to 1;  p = [1, 3, 2] : f_{a} is equal to 1;  p = [2, 1, 3] : f_{a} is equal to 1;  p = [2, 3, 1] : f_{a} is equal to 1;  p = [3, 1, 2] : f_{a} is equal to 0;  p = [3, 2, 1] : f_{a} is equal to 0.

Where p is the array of the indices of initial array a. The sum of f_{a} is equal to 4.

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

def main():
    f= [1]
    for i in range(1,1000002):
        f.append((f[-1] * i)%1000000007)

    n = int(input())
    a = sorted(int(x) for x in input().split())
    sol = 0
    j = 0
    s = 1
    sq = 1
    for i in range(n - 1):
        sq = sq * (n - i) % 1000000007
        if a[i] != a[i + 1]:
            sol += a[i] * (i - j + 1) * f[n - j - 1] * s
            j = i + 1
            s = sq

    print(sol % 1000000007)

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/939/A:
As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number f_{i}, where 1 ≤ f_{i} ≤ n and f_{i} ≠ i.

We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 5000) — the number of planes.

The second line contains n integers f_1, f_2, ..., f_{n} (1 ≤ f_{i} ≤ n, f_{i} ≠ i), meaning that the i-th plane likes the f_{i}-th.

-----Output-----

Output «YES» if there is a love triangle consisting of planes on Earth. Otherwise, output «NO».

You can output any letter in lower case or in upper case.

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

Output
YES

Input
5
5 5 5 5 1

Output
NO

-----Note-----

In first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.

In second example there are no love triangles.

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

n = int(input())
L = list(map(int, input().split()))
f = False
for i in range(n):
    j = L[i]
    k = L[j - 1]
    m = L[k - 1]
    if i == m - 1:
        f = True
        break
print('YES' if f else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/939/B:
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.

Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.

Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves a_{i} hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.

Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.

Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.

-----Input-----

The first line contains two integers N and K (0 ≤ N ≤ 10^18, 1 ≤ K ≤ 10^5) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces.

The second line contains K integers a_1, a_2, ..., a_{K} (1 ≤ a_{i} ≤ 10^18 for all i) — the capacities of boxes.

-----Output-----

Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input.

If there are many correct answers, output any of them.

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

Output
2 4

Input
28 3
5 6 30

Output
1 5

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

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

mx=0
mxval=0
for i in range(k):
    if A[i]*(n//A[i])>mxval:
        mxval = A[i]*(n//A[i])
        mx = i
print(mx+1, n//A[mx])


I found an interesting problem on https://codeforces.com/problemset/problem/939/C:
In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.

Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are a_{i} people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.

Help platform select such an hour, that the number of people who will participate in the contest is maximum.

-----Input-----

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day.

The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10 000), where a_{i} is the number of people in the i-th timezone who want to participate in the contest.

The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).

-----Output-----

Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.

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

Output
3

Input
5
1 2 3 4 1
1 3

Output
4

-----Note-----

In the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.

In second...

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

h = int(input())
ppl = [int(x) for x in input().split()]
sl = [int(x) for x in input().split()]
n = sl[1] - sl[0] if sl[1] > sl[0] else sl[1] - sl[0] + h
m = 0
index = 0
temp = sum(ppl[0:n])
ans = []
for i in range(h):
    if m < temp:
        m = temp
        ans.clear()
        ans.append(i)
    elif m == temp:
        ans.append(i)
    temp -= ppl[i]
    temp += ppl[(i+n) % h]
res = [(sl[0] + h - index - 1) % h + 1  for index in ans]
# print(n)
# print(m)
print(min(res))


I found an interesting problem on https://codeforces.com/problemset/problem/939/D:
Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.

This story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.

More formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length n consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (c_1, c_2) (where c_1 and c_2 are some lowercase English letters), which can arbitrary number of times transform a single letter c_1 to c_2 and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the letterings.

The second line contains a string with length n, consisting of lowercase English letters — the lettering on Valya's pullover.

The third line contains the lettering on Tolya's t-shirt in the same format.

-----Output-----

In the first line output a single integer — the minimum amount of mana t required for rescuing love of Valya and Tolya.

In the next t lines output pairs of space-separated lowercase English letters — spells that Tolya's grandmother should buy. Spells and letters in spells can be printed in any order.

If there are many optimal answers, output...

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

def f(x):
    if data[x] != x:
        data[x] = f(data[x])
        return data[x]
    else:
        return x

n = int(input())
s = input()
t = input()
data = [i for i in range(26)]
for i in range(n):
    a, b = f(ord(s[i]) - ord("a")), f(ord(t[i]) - ord("a"))
    if a != b:
        data[a] = b
ans = 0
for i in range(26):
    f(i)
for i in range(26):
    ans += max(0, data.count(i) - 1)
print(ans)
for i in range(26):
    ans = []
    for j in range(26):
        if data[j] == i:
            ans.append(chr(j + ord("a")))
    for j in range(len(ans) - 1):
        print(ans[j], ans[j + 1])


I found an interesting problem on https://codeforces.com/problemset/problem/939/E:
You are given a multiset S consisting of positive integers (initially empty). There are two kind of queries:   Add a positive integer to S, the newly added integer is not less than any number in it.  Find a subset s of the set S such that the value $\operatorname{max}(s) - \operatorname{mean}(s)$ is maximum possible. Here max(s) means maximum value of elements in s, $\operatorname{mean}(s)$ — the average value of numbers in s. Output this maximum possible value of $\operatorname{max}(s) - \operatorname{mean}(s)$.

-----Input-----

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

Each of the next Q lines contains a description of query. For queries of type 1 two integers 1 and x are given, where x (1 ≤ x ≤ 10^9) is a number that you should add to S. It's guaranteed that x is not less than any number in S. For queries of type 2, a single integer 2 is given.

It's guaranteed that the first query has type 1, i. e. S is not empty when a query of type 2 comes.

-----Output-----

Output the answer for each query of the second type in the order these queries are given in input. Each number should be printed in separate line.

Your answer is considered correct, if each of your answers has absolute or relative error not greater than 10^{ - 6}.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-6}$.

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

Output
0.0000000000
0.5000000000
3.0000000000

Input
4
1 1
1 4
1 5
2

Output
2.0000000000

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

import sys
input = sys.stdin.readline

Q = int(input())
a = []
sm = []

def best():
    mx = a[-1]
    n = len(a)
    l, r = 0, n-2
    ret = mx
    while l <= r:
        mid = (l + r) // 2
        s = sm[mid] + mx
        c = mid + 2
        avg = s / c
        if a[mid] > avg:
            r = mid - 1
        else:
            ret = avg
            l = mid + 1
    return ret

for _ in range(Q):
    inp = [int(i) for i in input().split()]
    if len(inp) == 2:
        x = inp[1]
        a.append(x)
        sm.append((sm[-1] if sm else 0) + x)
    else:
        mx = a[-1]
        avg = best()
        ans = mx - avg
        print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/940/A:
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.

The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2.

Diameter of multiset consisting of one point is 0.

You are given n points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed d?

-----Input-----

The first line contains two integers n and d (1 ≤ n ≤ 100, 0 ≤ d ≤ 100) — the amount of points and the maximum allowed diameter respectively.

The second line contains n space separated integers (1 ≤ x_{i} ≤ 100) — the coordinates of the points.

-----Output-----

Output a single integer — the minimum number of points you have to remove.

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

Output
1

Input
3 0
7 7 7

Output
0

Input
6 3
1 3 4 6 9 10

Output
3

-----Note-----

In the first test case the optimal strategy is to remove the point with coordinate 4. The remaining points will have coordinates 1 and 2, so the diameter will be equal to 2 - 1 = 1.

In the second test case the diameter is equal to 0, so its is unnecessary to remove any points.

In the third test case the optimal strategy is to remove points with coordinates 1, 9 and 10. The remaining points will have coordinates 3, 4 and 6, so the diameter will be equal to 6 - 3 = 3.

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

number, diameter = [int(x) for x in input().split()]
numbers = [int(x) for x in input().split()]
numbers.sort()

max_covered = 0
for i in range(len(numbers)):
	j = i
	while j != len(numbers) and abs(numbers[i] - numbers[j]) <= diameter:
		j += 1
	max_covered = max(j - i, max_covered)

print(len(numbers) - max_covered)


I found an interesting problem on https://codeforces.com/problemset/problem/940/B:
Right now she actually isn't. But she will be, if you don't solve this problem.

You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations:   Subtract 1 from x. This operation costs you A coins.  Divide x by k. Can be performed only if x is divisible by k. This operation costs you B coins.  What is the minimum amount of coins you have to pay to make x equal to 1?

-----Input-----

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

The second line contains a single integer k (1 ≤ k ≤ 2·10^9).

The third line contains a single integer A (1 ≤ A ≤ 2·10^9).

The fourth line contains a single integer B (1 ≤ B ≤ 2·10^9).

-----Output-----

Output a single integer — the minimum amount of coins you have to pay to make x equal to 1.

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

Output
6

Input
5
5
2
20

Output
8

Input
19
3
4
2

Output
12

-----Note-----

In the first testcase, the optimal strategy is as follows:   Subtract 1 from x (9 → 8) paying 3 coins.  Divide x by 2 (8 → 4) paying 1 coin.  Divide x by 2 (4 → 2) paying 1 coin.  Divide x by 2 (2 → 1) paying 1 coin.

The total cost is 6 coins.

In the second test case the optimal strategy is to subtract 1 from x 4 times paying 8 coins in total.

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

x = int(input())
k = int(input())
a = int(input())
b = int(input())

c = 0

while x > 1:
	if x % k > 0:
		if x > k:
			c += a * (x % k)
			x -= x % k
		else:
			c += a * (x % k - 1)
			x = 1

	else:
		if (x-x//k)*a >= b:
			c += b
			x = x//k
		else:
			c += (x-1)*a
			x = 1

print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/940/C:
And where the are the phone numbers?

You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.

It's guaranteed that the answer exists.

Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.

String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that p_{i} < q_{i} and for all j < i it is satisfied that p_{j} = q_{j}. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.

-----Input-----

The first line of input contains two space separated integers n and k (1 ≤ n, k ≤ 100 000) — the length of s and the required length of t.

The second line of input contains the string s consisting of n lowercase English letters.

-----Output-----

Output the string t conforming to the requirements above.

It's guaranteed that the answer exists.

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

Output
aca

Input
3 2
abc

Output
ac

Input
3 3
ayy

Output
yaa

Input
2 3
ba

Output
baa

-----Note-----

In the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca.

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

n,k=list(map(int,input().split(' ')))
s=input()
setl=set(s)
l=sorted(list(setl))
cnt=0
if k>n:
    print(s+(k-n)*l[0])
else:
    ans=""
    for j in range(k-1,-1,-1):
        cnt+=1
        if s[j]==l[-1]:
            ans+=l[0]
        else:
            x=l.index(s[j])
            ans+=l[x+1]
            break
    print(s[0:k-cnt]+ans[::-1])


I found an interesting problem on https://codeforces.com/problemset/problem/940/D:
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme."

"Little Alena got an array as a birthday present..."

The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:

b_1 = b_2 = b_3 = b_4 = 0.

For all 5 ≤ i ≤ n:   b_{i} = 0 if a_{i}, a_{i} - 1, a_{i} - 2, a_{i} - 3, a_{i} - 4 > r and b_{i} - 1 = b_{i} - 2 = b_{i} - 3 = b_{i} - 4 = 1  b_{i} = 1 if a_{i}, a_{i} - 1, a_{i} - 2, a_{i} - 3, a_{i} - 4 < l and b_{i} - 1 = b_{i} - 2 = b_{i} - 3 = b_{i} - 4 = 0  b_{i} = b_{i} - 1 otherwise

You are given arrays a and b' of the same length. Find two integers l and r (l ≤ r), such that applying the algorithm described above will yield an array b equal to b'.

It's guaranteed that the answer exists.

-----Input-----

The first line of input contains a single integer n (5 ≤ n ≤ 10^5) — the length of a and b'.

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

The third line of input contains a string of n characters, consisting of 0 and 1 — the elements of b'. Note that they are not separated by spaces.

-----Output-----

Output two integers l and r ( - 10^9 ≤ l ≤ r ≤ 10^9), conforming to the requirements described above.

If there are multiple solutions, output any of them.

It's guaranteed that the answer exists.

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

Output
6 15

Input
10
-10 -9 -8 -7 -6 6 7 8 9 10
0000111110

Output
-5 5

-----Note-----

In the first test case any pair of l and r pair is valid, if 6 ≤ l ≤ r ≤ 10^9, in that case b_5 = 1, because a_1, ..., a_5 < l.

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

import re
input()
a = list(map(int, input().split()))
b = input()
l, r = -10**9, 10**9

# a: a a a a a > r
# b: 1 1 1 1 0
for m in re.finditer("11110", b):
	i = m.start(0)
	r = min([r + 1] + a[i:i+5]) - 1

# a: a a a a a < l
# b: 0 0 0 0 1
for m in re.finditer("00001", b):
	i = m.start(0)
	l = max([l - 1] + a[i:i+5]) + 1

print(l, r)


I found an interesting problem on https://codeforces.com/problemset/problem/940/E:
Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.

You are given an array a of length n and an integer c.

The value of some array b of length k is the sum of its elements except for the $\lfloor \frac{k}{c} \rfloor$ smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.

Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.

-----Input-----

The first line contains integers n and c (1 ≤ n, c ≤ 100 000).

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

-----Output-----

Output a single integer  — the smallest possible sum of values of these subarrays of some partition of a.

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

Output
6

Input
12 10
1 1 10 10 10 10 10 10 9 10 10 10

Output
92

Input
7 2
2 3 6 4 5 7 1

Output
17

Input
8 4
1 3 4 5 5 3 4 1

Output
23

-----Note-----

In the first example any partition yields 6 as the sum.

In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.

In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.

In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.

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

from functools import *
from time import time
from heapq import *

#
# def measure_time(fun):
#     def wrapper(*args, **kwargs):
#         begin = time()
#         rv = fun(*args, **kwargs)
#         end = time()
#         print(end - begin)
#         return rv
#     return wrapper
#
#
# def our_cache(func):
#     memo = [-1]*(max+1)
#
#     @wraps(func)
#     def wrapper(arg):
#         if memo[arg] == -1:
#             memo[arg] = func(arg)
#         return memo[arg]
#     return wrapper

def main():
    n, c = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]

    if c > n:
        print(sum(a))
        return

    b = n * [0]
    s = 0
    h = []
    for i in range(n):
        s = s + a[i] if i <= c-1 else s + a[i] - a[i-c]
        heappush(h, (a[i], i))
        if i <= c-2:
            b[i] = s
        else:
            while i-h[0][1] >= c:
                heappop(h)
            v1 = b[i-c] + s - h[0][0]
            v2 = a[i] + b[i-1]
            b[i] = min(v1, v2)

    print(b[-1])

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/946/A:
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.

Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of B - C?

-----Input-----

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

The second line contains n integers a_1, a_2, ..., a_{n} ( - 100 ≤ a_{i} ≤ 100) — the elements of sequence a.

-----Output-----

Print the maximum possible value of B - C, where B is the sum of elements of sequence b, and C is the sum of elements of sequence c.

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

Output
3

Input
6
16 23 16 15 42 8

Output
120

-----Note-----

In the first example we may choose b = {1, 0}, c = { - 2}. Then B = 1, C =  - 2, B - C = 3.

In the second example we choose b = {16, 23, 16, 15, 42, 8}, c = {} (an empty sequence). Then B = 120, C = 0, B - C = 120.

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

n = int(input())
a = list(map(int, input().split()))
num = 0
for i in range(n):
    if a[i] < 0:
        num += -1 * a[i]
    else:
        num += a[i]

print(num)


I found an interesting problem on https://codeforces.com/problemset/problem/946/B:
You have two variables a and b. Consider the following sequence of actions performed with these variables: If a = 0 or b = 0, end the process. Otherwise, go to step 2; If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3; If b ≥ 2·a, then set the value of b to b - 2·a, and repeat step 1. Otherwise, end the process.

Initially the values of a and b are positive integers, and so the process will be finite.

You have to determine the values of a and b after the process ends.

-----Input-----

The only line of the input contains two integers n and m (1 ≤ n, m ≤ 10^18). n is the initial value of variable a, and m is the initial value of variable b.

-----Output-----

Print two integers — the values of a and b after the end of the process.

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

Output
0 1

Input
31 12

Output
7 12

-----Note-----

Explanations to the samples: a = 12, b = 5 $\rightarrow$ a = 2, b = 5 $\rightarrow$ a = 2, b = 1 $\rightarrow$ a = 0, b = 1; a = 31, b = 12 $\rightarrow$ a = 7, b = 12.

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

a,b= (list(map(int,input().strip().split(' '))))
while(True):
   if(a==0 or b==0):
      break
   if(a>=2*b):
      d = a//(2*b)
      d=max(d-1,1)
      a = a-d*2*b
   if(a==0 or b==0):
      break
   if(b>=2*a):
      d = b//(a*2)
      d=max(d-1,1)
      b = b-d*2*a
   if(a==0 or b==0):
      break
   if(a<2*b and b<2*a):
      break
print(a,b)


I found an interesting problem on https://codeforces.com/problemset/problem/946/C:
You are given a string s consisting of |s| small english letters.

In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.

Your target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.

-----Input-----

The only one line of the input consisting of the string s consisting of |s| (1 ≤ |s| ≤ 10^5) small english letters.

-----Output-----

If you can get a string that can be obtained from the given string and will contain english alphabet as a subsequence, print it. Otherwise print «-1» (without quotes).

-----Examples-----
Input
aacceeggiikkmmooqqssuuwwyy

Output
abcdefghijklmnopqrstuvwxyz

Input
thereisnoanswer

Output
-1

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

s=input()
alpha="abcdefghijklmnopqrstuvwxyz"
c=0
cnt=0
ans=""
while cnt<len(s) and c<26:
    if (ord(s[cnt])-ord('a'))<=c:
        ans+=alpha[c]
        c+=1
    else:
        ans+=s[cnt]
    cnt+=1
if c==26:
    ans+=s[cnt:]
    print(ans)
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/946/D:
Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.

There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends j - i + 1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.

Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.

Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons?

-----Input-----

The first line contains three integers n, m and k (1 ≤ n, m ≤ 500, 0 ≤ k ≤ 500) — the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively.

Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson).

-----Output-----

Print the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons.

-----Examples-----
Input
2 5 1
01001
10110

Output
5

Input
2 5 0
01001
10110

Output
8

-----Note-----

In the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second...

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

n, m, k = input().split(' ')
n = int(n)
m = int(m)
k = int(k)
ind = []
pre = []

for _ in range(n):
    s = input()
    ind.append([])
    for i, c in enumerate(s):
        if c == '1':
            ind[-1].append(i)

for i in range(n):
    pre.append([])
    for j in range(k + 1):
        pre[i].append([])
        if len(ind[i]) > j:
            pre[i][j] = ind[i][-1] - ind[i][0] + 1
        else:
            pre[i][j] = 0
            continue
        for x in range(j + 1):
            y = len(ind[i]) - 1 - j + x

            if y >= x and ind[i][y] - ind[i][x] + 1 < pre[i][j]:
                pre[i][j] = ind[i][y] - ind[i][x] + 1
dp = [[]]

for i in range(k + 1):
    dp[0].append(pre[0][i])

for i in range(1, n):
    dp.append([])
    for j in range(0, k + 1):
        dp[i].append(pre[i][j] + dp[i - 1][0])
        for z in range(j + 1):
            dp[i][j] = min(dp[i][j], dp[i - 1][z] + pre[i][j - z])

print(dp[n - 1][k])


I found an interesting problem on https://codeforces.com/problemset/problem/948/A:
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.

The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.

Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.

-----Input-----

First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively.

Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.

-----Output-----

If it is impossible to protect all sheep, output a single line with the word "No".

Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf.

If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.

-----Examples-----
Input
6 6
..S...
..S.W.
.S....
..W...
...W..
......

Output
Yes
..SD..
..SDW.
.SD...
.DW...
DD.W..
......

Input
1 2
SW

Output
No

Input
5 5
.S...
...S.
S....
...S.
.S...

Output
Yes
.S...
...S.
S.D..
...S.
.S...

-----Note-----

In the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.

In the...

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

import sys

s = input().split()
r,c = list(map(int, s))
f = ['']*r
for x in range(r):
    f[x] = input().replace('.', 'D')
    if 'WS' in f[x] or 'SW' in f[x]:
        print('No')
        return
    if x > 0:
        for y in range(c):
            up = f[x][y]+f[x-1][y]
            if up in ['SW', 'WS']:
                print('No')
                return
print('Yes')
for x in range(r):
    print(f[x])


I found an interesting problem on https://codeforces.com/problemset/problem/949/A:
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.

Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.

-----Input-----

In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters.

-----Output-----

If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≤ k ≤ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer l_{i} (1 ≤ l_{i} ≤ |s|), which is the length of the i-th subsequence, and then l_{i} indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1.

Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.

-----Examples-----
Input
0010100

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

Input
111

Output
-1

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

def read_data():
    a = list(map(int, list(input().strip())))
    return a

def solve():
    sol = []
    pos = -1
    try:
        for i in range(0,len(a)):
            if a[i] == 0:
                if pos > -1:
                    sol[pos].append(i+1)
                    pos -= 1
                else:
                    sol.append([i+1])
            else:
                pos += 1
                sol[pos].append(i+1)
    except:
        return -1
    if pos == -1:
        return sol
    else:
        return -1

def print_sol(sol):
    if sol == -1:
        print(sol)
        return 0
    print(len(sol))
    for list in sol:
        print(len(list), *list)

a = read_data()
sol = solve()
print_sol(sol)


I found an interesting problem on https://codeforces.com/problemset/problem/949/C:
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).

Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers.

For each of m company clients, let us denote indices of two different data centers storing this client data as c_{i}, 1 and c_{i}, 2.

In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day.

Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer u_{j} (0 ≤ u_{j} ≤ h - 1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance.

Summing up everything above, the condition u_{c}_{i}, 1 ≠ u_{c}_{i}, 2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance.

Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for...

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

import sys

# sys.stind.readline lee datos el doble de
# rápido que la funcion por defecto input
input = sys.stdin.readline
length = len

def get_input():
    n, m, h = [int(x) for x in input().split(' ')]

    digraph = [[] for _ in range(n + 1)]
    transpose = [[] for _ in range(n + 1)]
    mantainence = [0] + [int(x) for x in input().split(' ')]

    for _ in range(m):
        c1, c2 = [int(x) for x in input().split(' ')]

        if (mantainence[c1] + 1) % h == mantainence[c2]:
            digraph[c1].append(c2)
            transpose[c2].append(c1)
        if (mantainence[c2] + 1) % h == mantainence[c1]:
            digraph[c2].append(c1)
            transpose[c1].append(c2)

    return digraph, transpose

def dfs_cc_1_visit(graph, node, color, finalization_stack):
    stack = [node]

    while stack:
        current_node = stack[-1]

        if color[current_node] != 'white':
            stack.pop()
            if color[current_node] == 'grey':
                finalization_stack.append(current_node)
                color[current_node] = 'black'
            continue

        color[current_node] = 'grey'
        for adj in graph[current_node]:
            if color[adj] == 'white':
                stack.append(adj)

def dfs_cc_1(graph):
    n = length(graph)
    finalization_stack = []
    color = ['white'] * n
    for i in range(1, n):
        if color[i] == 'white':
            dfs_cc_1_visit(graph, i, color, finalization_stack)
    return finalization_stack

def dfs_cc_2_visit(graph, node, color, scc, component):
    stack = [node]

    while stack:
        current_node = stack[-1]

        if color[current_node] != 'white':
            stack.pop()
            color[current_node] = 'black'
            scc[current_node] = component
            continue

        color[current_node] = 'grey'
        for adj in graph[current_node]:
            if color[adj] == 'white':
                stack.append(adj)

def dfs_cc_2(graph, stack_time):
    n = length(graph)
    color = ['white'] * n
    scc = [0] *...


I found an interesting problem on https://codeforces.com/problemset/problem/949/D:
Instructors of Some Informatics School make students go to bed.

The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially, in i-th room there are a_{i} students. All students are currently somewhere in the house, therefore a_1 + a_2 + ... + a_{n} = nb. Also 2 instructors live in this house.

The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room n, while the second instructor starts near room n and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if n is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends.

When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to b, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students.

While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most d rooms, that is she can move to a room with number that differs my at most d. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously.

Formally, here is what's happening:  A curfew is announced, at this point in room i there are a_{i} students.  Each student can run to another room but not further than d rooms away from her...

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

func = lambda: map(int, input().split())
n, d, b = func()
d += 1
t, a = 0, [0] * (n + 1)
for i, x in enumerate(func()):
    t += x
    a[i + 1] = t
print(max(i - min(a[min(n, i * d)], (a[n] - a[max(0, n - i * d)])) // b for i in range(n + 3 >> 1)))


I found an interesting problem on https://codeforces.com/problemset/problem/950/A:
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.

The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.

Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.

Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.

-----Input-----

The only line contains three integers l, r and a (0 ≤ l, r, a ≤ 100) — the number of left-handers, the number of right-handers and the number of ambidexters at the training.

-----Output-----

Print a single even integer — the maximum number of players in the team. It is possible that the team can only have zero number of players.

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

Output
6

Input
5 5 5

Output
14

Input
0 2 0

Output
0

-----Note-----

In the first example you can form a team of 6 players. You should take the only left-hander and two ambidexters to play with left hand, and three right-handers to play with right hand. The only person left can't be taken into the team.

In the second example you can form a team of 14 people. You have to take all five left-handers, all five right-handers, two ambidexters to play with left hand and two ambidexters to play with right hand.

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

# -*- coding: utf-8 -*-
"""
Created on Fri Mar  9 09:54:56 2018

@author: Nikita
"""

L, R, A = list(map(int, input().split()))
if L <= R:
  if A < R - L:
    print(2 * (L + A))
  else:
    A -= (R - L)
    print(2 * (R + A // 2))
else:
  if A < L - R:
    print(2 * (R + A))
  else:
    A -= (L - R)
    print(2 * (L + A // 2))


I found an interesting problem on https://codeforces.com/problemset/problem/950/B:
Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.

Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred through the network: if an archive consists of k files of sizes l_1, l_2, ..., l_{k} bytes, then the i-th file is split to one or more blocks b_{i}, 1, b_{i}, 2, ..., b_{i}, m_{i} (here the total length of the blocks b_{i}, 1 + b_{i}, 2 + ... + b_{i}, m_{i} is equal to the length of the file l_{i}), and after that all blocks are transferred through the network, maintaining the order of files in the archive.

Zhorik thinks that the two messages contain the same archive, because their total lengths are equal. However, each file can be split in blocks in different ways in the two messages.

You are given the lengths of blocks in each of the two messages. Help Zhorik to determine what is the maximum number of files could be in the archive, if the Zhorik's assumption is correct.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 10^5) — the number of blocks in the first and in the second messages.

The second line contains n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 10^6) — the length of the blocks that form the first message.

The third line contains m integers y_1, y_2, ..., y_{m} (1 ≤ y_{i} ≤ 10^6) — the length of the blocks that form the second message.

It is guaranteed that x_1 + ... + x_{n} = y_1 + ... + y_{m}. Also, it is guaranteed that x_1 + ... + x_{n} ≤ 10^6.

-----Output-----

Print the maximum number of files the intercepted array could consist of.

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

Output
3

Input
3 3
1 10 100
1 100 10

Output
2

Input
1 4
4
1 1 1 1

Output
1

-----Note-----

In the first example the maximum number of files in the archive is 3. For example, it is possible that in the archive are three files of sizes 2 + 5 = 7, 15 = 3 +...

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

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

sm1 = sm2 = 0
i = j = 0
cnt = 0

moveX = moveY = True

while i < len(xs):
    if moveX:
        sm1 += xs[i]
    if moveY:
        sm2 += ys[j]
    if sm1 < sm2:
        i += 1
        moveX = True
        moveY = False
    elif sm1 > sm2:
        j += 1
        moveX = False
        moveY = True
    else:
        sm1 = sm2 = 0
        cnt += 1
        i += 1
        j += 1
        moveX = True
        moveY = True

print(cnt)


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

The input contains a single integer a (10 ≤ a ≤ 999).

-----Output-----

Output 0 or 1.

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

Output
1

Input
927

Output
1

Input
48

Output
0

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

import sys

def read_line():
    return sys.stdin.readline().rstrip("\r\n")

n = int(read_line())
print(n % 2)


I found an interesting problem on https://codeforces.com/problemset/problem/952/C:
Everybody knows of spaghetti sort. You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you...

You come up with the following algorithm. For each number in the array a_{i}, build a stack of a_{i} ravioli. The image shows the stack for a_{i} = 4.

 [Image]

Arrange the stacks in one row in the order in which the corresponding numbers appear in the input array. Find the tallest one (if there are several stacks of maximal height, use the leftmost one). Remove it and add its height to the end of the output array. Shift the stacks in the row so that there is no gap between them. Repeat the procedure until all stacks have been removed.

At first you are very happy with your algorithm, but as you try it on more inputs you realize that it doesn't always produce the right sorted array. Turns out when two stacks of ravioli are next to each other (at any step of the process) and differ in height by two or more, the top ravioli of the taller stack slides down on top of the lower stack.

Given an input array, figure out whether the described algorithm will sort it correctly.

-----Input-----

The first line of input contains a single number n (1 ≤ n ≤ 10) — the size of the array.

The second line of input contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 100) — the elements of the array.

-----Output-----

Output "YES" if the array can be sorted using the described procedure and "NO" if it can not.

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

Output
YES

Input
3
3 1 2

Output
NO

-----Note-----

In the second example the array will change even before the tallest stack is chosen for the first time: ravioli from stack of height 3 will slide on the stack of height 1, and the algorithm will output an array {2, 2, 2}.

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

"""
Codeforces April Fools 2018 Problem C

Author  : chaotic_iak
Language: Python 3.5.2
"""

################################################### SOLUTION

def initialize_solution():
    pass

def main():
    n, = read()
    a = read()
    for i in range(n-1):
        if abs(a[i] - a[i+1]) >= 2:
            return "NO"
    return "YES"

########################################## PROBLEM CONSTANTS

READ_FROM_FILE = None
OUTPUT_PREFIX = None
INTERACTIVE = False

#################################################### HELPERS

import sys

def read(callback=int, split=True):
    if READ_FROM_FILE:
        ipt = sfile.readline().strip()
    else:
        ipt = input().strip()
    if INTERACTIVE and ipt == "WRONG_ANSWER":
        return
    if split:
        return list(map(callback, ipt.split()))
    else:
        return callback(ipt)

def write(value, end="\n"):
    if value is None: return
    try:
        if not isinstance(value, str):
            value = " ".join(map(str, value))
    except:
        pass
    if READ_FROM_FILE:
        tfile.write(str(value, end=end))
    else:
        print(value, end=end)
    if INTERACTIVE:
        sys.stdout.flush()

sfile = None
tfile = None
if READ_FROM_FILE:
    sfile = open(READ_FROM_FILE + ".in", "r")
    sfile.seek(0)
    tfile = open(READ_FROM_FILE + ".out", "w")
if OUTPUT_PREFIX is None:
    result = main()
    if result is not None:
        write(result)
else:
    initialize_solution()
    TOTAL_CASES, = read()
    for CASE_NUMBER in range(1, TOTAL_CASES+1):
        write(OUTPUT_PREFIX.replace("%d", str(CASE_NUMBER)), end="")
        result = main()
        if result is not None:
            write(result)
if sfile is not None: sfile.close()
if tfile is not None: tfile.close()


I found an interesting problem on https://codeforces.com/problemset/problem/952/E:
Not to be confused with chessboard.

 [Image]

-----Input-----

The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have.

The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.

-----Output-----

Output a single number.

-----Examples-----
Input
9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard

Output
3

Input
6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard

Output
4

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/952/F:
One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution...

-----Input-----

The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive.

-----Output-----

Reproduce the output of the reference solution, including the bug.

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

Output
4

Input
2+2

Output
-46

Input
112-37

Output
375

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

a = input()
q, s = [0], 0
z = []
for i in range(len(a)):
    y = a[i]
    if (y=="+"):
        z.append(1)
        q.append(0)
        s+=1
    elif (y=="-"):
        z.append(-1)
        q.append(0)
        s+=1
    q[s] = 10*q[s] + (ord(y)-ord("0"))
otv = q[0]
for i in range(1, s+1):
    otv += z[i-1]*q[i]
print(otv)


I found an interesting problem on https://codeforces.com/problemset/problem/954/A:
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.

In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.

Your problem is to print the minimum possible length of the sequence of moves after the replacements.

-----Input-----

The first line of the input contains one integer n (1 ≤ n ≤ 100) — the length of the sequence. The second line contains the sequence consisting of n characters U and R.

-----Output-----

Print the minimum possible length of the sequence of moves after all replacements are done.

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

Output
3

Input
17
UUURRRRRUUURURUUU

Output
13

-----Note-----

In the first test the shortened sequence of moves may be DUD (its length is 3).

In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13).

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/954/B:
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard.

Initially, you have an empty string. Until you type the whole string, you may perform the following operation:  add a character to the end of the string.

Besides, at most once you may perform one additional operation: copy the string and append it to itself.

For example, if you have to type string abcabca, you can type it in 7 operations if you type all the characters one by one. However, you can type it in 5 operations if you type the string abc first and then copy it and type the last character.

If you have to type string aaaaaaaaa, the best option is to type 4 characters one by one, then copy the string, and then type the remaining character.

Print the minimum number of operations you need to type the given string.

-----Input-----

The first line of the input containing only one integer number n (1 ≤ n ≤ 100) — the length of the string you have to type. The second line containing the string s consisting of n lowercase Latin letters.

-----Output-----

Print one integer number — the minimum number of operations you need to type the given string.

-----Examples-----
Input
7
abcabca

Output
5

Input
8
abcdefgh

Output
8

-----Note-----

The first test described in the problem statement.

In the second test you can only type all the characters one by one.

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

n = int(input())

s = input()

ss = ""

i = 0
longest  = 0

for i in range(int(n/2)):
	#print(s[0:i+1])
	#print(s[i+1:i+i+1+1])
	if s[0:i+1] == s[i+1:i+i+1+1]:
		longest = i

ans = n-longest

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/954/C:
There is a matrix A of size x × y filled with integers. For every $i \in [ 1 . . x ]$, $j \in [ 1 . . y ]$ A_{i}, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix.

You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a_1, a_2, ..., a_{n} denoting that you started in the cell containing the number a_1, then moved to the cell with the number a_2, and so on.

From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i < x;  (i, j + 1) — only if j < y;  (i - 1, j) — only if i > 1;  (i, j - 1) — only if j > 1.

Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a_1, then move to the cell containing a_2 (in one step), then move to the cell containing a_3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?

-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice).

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

-----Output-----

If all possible values of x and y such that 1 ≤ x, y ≤ 10^9 contradict with the information about your path, print NO.

Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 10^9.

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

Output
YES
3 3

Input
6
1 2 1 2 5 3

Output
NO

Input
2
1 10

Output
YES
4 9

-----Note-----

The matrix and the path on it in the first test looks...

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

n = int(input())
walk = list(map(int, input().split()))
MAXN = 1000000000
def solve1():
    for i in range(n-1):
        if abs(walk[i+1]-walk[i]) != 1:
            return False
    print("YES")
    print(MAXN, 1)
    return True

def solve2():
    colum = -1
    for i in range(n-1):
        diff = abs(walk[i+1]-walk[i])
        if diff != 1:
            if colum == -1:
                colum = diff
            elif colum != diff:
                return False
    if colum<=0:
        return False
    for i in range(n-1):
        if abs(walk[i+1]-walk[i]) == 1 and ((walk[i+1]-1)//colum != (walk[i]-1)//colum):
            return False
    print("YES")
    print(MAXN,colum)
    return True

if solve1():
    pass
elif solve2():
    pass
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/954/D:
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.

In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.

You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.

-----Input-----

The firt line of the input contains integers n, m, s and t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}), meaning that this road connects junctions u_{i} and v_{i} directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.

-----Output-----

Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.

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

Output
0

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

Output
5

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

Output
3

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

n,k,s,t=map(int,input().split())
m=[set() for i in range(n+1)]
for i in range(k):
    a,b=map(int,input().split())
    m[a].add(b)
    m[b].add(a)
forw=[-1]*(n+1)
back=forw.copy()
take,push=[],[s]
forw[s]=0
way=0
z=0
while push:
    way+=1
    take,push=push,take
    while take:
        a=take.pop()
        if a==t and not z:
            z=way-1
        for x in m[a]:
            if forw[x]==-1:
                forw[x]=way
                push.append(x)
take,push=[],[t]
back[t]=0
way=0
while push:
    way+=1
    take,push=push,take
    while take:
        a=take.pop()
        for x in m[a]:
            if back[x]==-1:
                back[x]=way
                push.append(x)
ans=0
for i in range(1,n):
    for j in range(i+1,n+1):
        if j not in m[i] and min(forw[j]+back[i],forw[i]+back[j])+1>=z:
            ans+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/954/E:
Consider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to a_{i} ml per second (this amount may be a real number). The water delivered by i-th tap has temperature t_{i}.

If for every $i \in [ 1, n ]$ you set i-th tap to deliver exactly x_{i} ml of water per second, then the resulting temperature of water will be $\frac{\sum_{i = 1}^{n} x_{i} t_{i}}{\sum_{i = 1}^{n} x_{i}}$ (if $\sum_{i = 1}^{n} x_{i} = 0$, then to avoid division by zero we state that the resulting water temperature is 0).

You have to set all the water taps in such a way that the resulting temperature is exactly T. What is the maximum amount of water you may get per second if its temperature has to be T?

-----Input-----

The first line contains two integers n and T (1 ≤ n ≤ 200000, 1 ≤ T ≤ 10^6) — the number of water taps and the desired temperature of water, respectively.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) where a_{i} is the maximum amount of water i-th tap can deliver per second.

The third line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 10^6) — the temperature of water each tap delivers.

-----Output-----

Print the maximum possible amount of water with temperature exactly T you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0).

Your answer is considered correct if its absolute or relative error doesn't exceed 10^{ - 6}.

-----Examples-----
Input
2 100
3 10
50 150

Output
6.000000000000000

Input
3 9
5 5 30
6 6 10

Output
40.000000000000000

Input
2 12
1 3
10 15

Output
1.666666666666667

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

rd = lambda: map(int, input().split())
n, t = rd()
a = list(rd())
b = list(rd())
x = [[b[i], a[i]] for i in range(n)]
x.sort()
tot, val = sum(a), 0
for i in range(n):
    val += (t - x[i][0]) * x[i][1]
if val:
    f = 2 * (val > 0) - 1
    for i in range(n)[::f]:
        if f * (val - x[i][1] * (t - x[i][0])) <= 0:
            tot -= val / (t - x[i][0])
            break
        tot -= x[i][1]
        val -= (t - x[i][0]) * x[i][1]
print(tot)


I found an interesting problem on https://codeforces.com/problemset/problem/955/A:
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.

At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.

Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.

-----Input-----

The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening.

The second line contains four integers H, D, C and N (1 ≤ H ≤ 10^5, 1 ≤ D, C, N ≤ 10^2).

-----Output-----

Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10^{ - 4}.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-4}$.

-----Examples-----
Input
19 00
255 1 100 1

Output
25200.0000

Input
17 41
1000 6 15 11

Output
1365.0000

-----Note-----

In the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.

In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles.

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

from math import gcd, floor, ceil
from random import randrange
def li():
    return list(map(int, input().split()))
h, m = li()
cur, d, c, n = li()
if 60 * h + m < 20 * 60:
    an = ((cur + n - 1) // n) * c
    cur += (20 * 60 - 60 * h - m) * d
    c *= 0.8
    an = min(an, c * ((cur + n - 1) // n))
else:
    c *= 0.8
    an = c * ((cur + n - 1) // n)
print(an)


I found an interesting problem on https://codeforces.com/problemset/problem/955/B:
Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.

You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.

-----Input-----

The only line contains s (1 ≤ |s| ≤ 10^5) consisting of lowercase latin letters.

-----Output-----

Print «Yes» if the string can be split according to the criteria above or «No» otherwise.

Each letter can be printed in arbitrary case.

-----Examples-----
Input
ababa

Output
Yes

Input
zzcxx

Output
Yes

Input
yeee

Output
No

-----Note-----

In sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.

There's no suitable partition in sample case three.

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

from collections import Counter

cnt = Counter(input().strip())
vals = sorted(cnt.values())

if len(vals) == 1 or len(vals) > 4:
    print("No")
elif len(vals) == 2:
    a, b = vals
    if a == 1:
        print("No")
    else:
        print("Yes")
elif len(vals) == 3:
    a, b, c = vals
    if c == 1:
        print("No")
    else:
        print("Yes")
elif len(vals) == 4:
    print("Yes")
else:
    raise RuntimeError("Should never happen")


I found an interesting problem on https://codeforces.com/problemset/problem/955/C:
You're given Q queries of the form (L, R).

For each query you have to find the number of such x that L ≤ x ≤ R and there exist integer numbers a > 0, p > 1 such that x = a^{p}.

-----Input-----

The first line contains the number of queries Q (1 ≤ Q ≤ 10^5).

The next Q lines contains two integers L, R each (1 ≤ L ≤ R ≤ 10^18).

-----Output-----

Output Q lines — the answers to the queries.

-----Example-----
Input
6
1 4
9 9
5 7
12 29
137 591
1 1000000

Output
2
1
0
3
17
1111

-----Note-----

In query one the suitable numbers are 1 and 4.

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

import math
import bisect
import sys

def flrt(exp,x):
    l=max(0,math.floor(x**(1/exp))-3)

    r= math.floor(x**(1/exp))+3
    while l<r:
        mid=(l+r)//2
        if mid**exp<=x:
            l=mid+1
        else:
            r=mid
    return l-1

def c1(r):
    ans=set()
    pr = [5,7,11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61]
    for i in pr:
        x=2
        while x**i <= r:
            val=x**i
            b2=flrt(2,val)
            b3=flrt(3,val)
            if b2**2 != val and b3**3 != val:
                ans.add(val)
            x+=1
    return ans

def solve(r, pc):
    if r==0:
        return 0

    a=[2,3]
    ans=0
    for i in range(1,2**len(a)):
        tot=0
        mult=1
        for j,x in enumerate(a):
            if i&(1<<j):
                mult*=x
                tot+=1
        d=  flrt(mult,r)
        ans+= d if tot%2 else -d

    return ans + bisect.bisect_right(pc,r)

    lp=0
    rp=len(pc)
    while lp<rp:
        mid = (lp+rp)//2
        if pc[mid] <= r:
            lp = mid+1
        else:
            rp = mid

    return ans + lp
q = int(input())

pc= c1(1e18+1)

pca=list(pc)
pca.sort()

for i in range(q):
    l,r = [int(x) for x in sys.stdin.readline().split()]
    ans=solve(r,pca)-solve(l-1,pca)
    sys.stdout.write(str(ans)+'\n')


I found an interesting problem on https://codeforces.com/problemset/problem/957/A:
Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.

Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colours.

Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.

-----Input-----

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

The second line contains a string s of n characters, the i-th of which is either 'C' (denoting a segment painted in cyan), 'M' (denoting one painted in magenta), 'Y' (one painted in yellow), or '?' (an unpainted one).

-----Output-----

If there are at least two different ways of painting, output "Yes"; otherwise output "No" (both without quotes).

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

-----Examples-----
Input
5
CY??Y

Output
Yes

Input
5
C?C?Y

Output
Yes

Input
5
?CYC?

Output
Yes

Input
5
C??MM

Output
No

Input
3
MMY

Output
No

-----Note-----

For the first example, there are exactly two different ways of colouring: CYCMY and CYMCY.

For the second example, there are also exactly two different ways of colouring: CMCMY and CYCMY.

For the third example, there are four ways of colouring: MCYCM, MCYCY, YCYCM, and YCYCY.

For the fourth example, no matter how the unpainted segments are coloured, the existing magenta segments will prevent the painting from satisfying the requirements. The similar is true for the fifth example.

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

n = int(input())
a = input()
for i in range(1,n):
    if a[i] == a[i-1] and a[i] != '?':
        print('No')
        return

for i in range(n):
    if a[i] == '?':
        if i ==0 or i == n-1:
            print('Yes')
            return
        elif a[i-1] == '?' or a[i+1] == '?':
                print('Yes')
                return
        else:
            if a[i-1] == a[i+1]:
                print('Yes')
                return
print('No')