I found an interesting problem on https://codeforces.com/problemset/problem/519/D:
A and B are preparing themselves for programming contests.

After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.

A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).

B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).

Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.

Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?

-----Input-----

The first line contains 26 integers x_{a}, x_{b}, ..., x_{z} ( - 10^5 ≤ x_{i} ≤ 10^5) — the value assigned to letters a, b, c, ..., z respectively.

The second line contains string s of length between 1 and 10^5 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.

-----Output-----

Print the answer to the problem.

-----Examples-----
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab

Output
2

Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa

Output
2

-----Note-----

In the first sample test strings satisfying the condition above are abca and bcab.

In the second sample test strings satisfying the condition above are two occurences of aa.

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

import sys

#sys.stdin = open('in.txt', 'rt')

a = list(map(int, input().split()))
s = input().strip()
w = [(0, -1)]
sum = 0
for i in enumerate(s):
    sum += a[ord(i[1]) - ord('a')]
    w.append((sum, i[0]))
w.sort()
dp = [0] * 26
answer = 0
for i in enumerate(w):
    if i[0] >= 1 and i[1][0] != w[i[0] - 1][0]:
        dp = [0] * 26
    if i[1][1] >= 0:
        dp[ord(s[i[1][1]]) - ord('a')] += 1
    if i[1][1] < len(s) - 1:
        answer += dp[ord(s[i[1][1] + 1]) - ord('a')]
print(answer)


I found an interesting problem on https://codeforces.com/problemset/problem/520/A:
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.

You are given a string consisting of lowercase and uppercase Latin letters. Check whether this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.

-----Input-----

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

The second line contains the string. The string consists only of uppercase and lowercase Latin letters.

-----Output-----

Output "YES", if the string is a pangram and "NO" otherwise.

-----Examples-----
Input
12
toosmallword

Output
NO

Input
35
TheQuickBrownFoxJumpsOverTheLazyDog

Output
YES

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

class A:
    def A(self, n, s):
        alphabets = ['A', 'B', 'C', 'D', 'E', 'F', 'G',
                     'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                     'U', 'V', 'W', 'X', 'Y', 'Z']
        s = s.upper()
        for i in  alphabets:
            if i not in s:
                return "NO"
        return "YES"

def __starting_point():
    n = int(input())
    s = input()
    print(A().A(n,s))
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/520/B:
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.

Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?

-----Input-----

The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 10^4), separated by a space .

-----Output-----

Print a single number — the minimum number of times one needs to push the button required to get the number m out of number n.

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

Output
2

Input
10 1

Output
9

-----Note-----

In the first example you need to push the blue button once, and then push the red button once.

In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.

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

a,b=map(int,input().split())
z=0
while a<b:
    if b%2==True:
        z+=1
        b+=1
    else:
        b=b//2
        z+=1
print(str(int(abs((z+a-b)))))


I found an interesting problem on https://codeforces.com/problemset/problem/520/C:
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.

Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): $\rho(s, t) = \sum_{i = 0}^{n - 1} \sum_{j = 0}^{n - 1} h(\operatorname{shift}(s, i), \operatorname{shift}(t, j))$ where $\operatorname{shift}(s, i)$ is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6

Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: $\rho(s, t) = \operatorname{max}_{u :|u|=|s|} \rho(s, u)$.

Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 10^9 + 7.

-----Input-----

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

The second line of the input contains a single string of length n, consisting of characters "ACGT".

-----Output-----

Print a single number — the answer modulo 10^9 + 7.

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

Output
1

Input
2
AG

Output
4

Input
3
TTT

Output
1

-----Note-----

Please note that if for two distinct strings t_1 and t_2 values ρ(s, t_1) и ρ(s, t_2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.

In the first sample, there is ρ("C", "C") = 1, for the remaining...

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

n, s = int(input()), input()
c = sorted(s.count(b) for b in 'ACGT')
print(pow(c.count(c[-1]), n, 10 ** 9 + 7))


I found an interesting problem on https://codeforces.com/problemset/problem/520/E:
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.

The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 10^9 + 7. Help him!

-----Input-----

The first line contains two integers, n and k (0 ≤ k < n ≤ 10^5).

The second line contains a string consisting of n digits.

-----Output-----

Print the answer to the problem modulo 10^9 + 7.

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

Output
27
Input
3 2
108

Output
9

-----Note-----

In the first sample the result equals (1 + 08) + (10 + 8) = 27.

In the second sample the result equals 1 + 0 + 8 = 9.

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

n, k = list(map(int, input().split()))
t = list(map(int, input()))
p, d = 1, 10 ** 9 + 7
s, f = 0, [1] * n
for i in range(2, n): f[i] = (i * f[i - 1]) % d
c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b - a], d - 2, d)) % d
if k:
    u = [0] * (n + 1)
    p = [1] * (n + 1)
    for i in range(n):
        u[i] = (p[i] * c(k - 1, n - 2 - i) + u[i - 1]) % d
        p[i + 1] = (10 * p[i]) % d
    for i in range(n):
        v = u[n - 2 - i] + p[n - 1 - i] * c(k, i)
        s = (s + t[i] * v) % d
else:
    for i in t: s = (s * 10 + i) % d
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/522/A:
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.

These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.

Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.

We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.

-----Output-----

Print a single integer — the maximum length of a repost chain.

-----Examples-----
Input
5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya

Output
6

Input
6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp

Output
2

Input
1
SoMeStRaNgEgUe reposted PoLyCaRp

Output
2

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

def nafig(s):
    for i in range(len(s)):
        x = ord(s[i])
        if (x <= 90) and (x >= 65):
            x += 32
            s = s[:i] + chr(x) + s[i + 1:]
    return s

n = int(input())
dic = dict()
dic['polycarp'] = 1
maxim = 1
for i in range(n):
    st = list(map(str, input().split()))
    st[0] = nafig(st[0])
    st[2] = nafig(st[2])
    dic[st[0]] = dic[st[2]] + 1
    if dic[st[0]] > maxim:
        maxim = dic[st[0]]
print(maxim)


I found an interesting problem on https://codeforces.com/problemset/problem/522/B:
One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together.

Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of width w_{i} pixels and height h_{i} pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is W × H, where W is the total sum of all widths and H is the maximum height of all the photographed friends.

As is usually the case, the friends made n photos — the j-th (1 ≤ j ≤ n) photo had everybody except for the j-th friend as he was the photographer.

Print the minimum size of each made photo in pixels.

-----Input-----

The first line contains integer n (2 ≤ n ≤ 200 000) — the number of friends.

Then n lines follow: the i-th line contains information about the i-th friend. The line contains a pair of integers w_{i}, h_{i} (1 ≤ w_{i} ≤ 10, 1 ≤ h_{i} ≤ 1000) — the width and height in pixels of the corresponding rectangle.

-----Output-----

Print n space-separated numbers b_1, b_2, ..., b_{n}, where b_{i} — the total number of pixels on the minimum photo containing all friends expect for the i-th one.

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

Output
75 110 60
Input
3
2 1
1 2
2 1

Output
6 4 6

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

ws = []
hs = []
a = int(input())

maxes = []
maxx = -1
for i in range(a):
    w, h = list(map(int, input().split(' ')))

    ws.append(w)
    hs.append(h)

hs2 = hs[:]
hs2.sort()
hs2.reverse()

fir = hs2[0]
sec = hs2[1]

t = sum(ws)
god = []
for i in range(a):
    if hs[i] == fir:
        god.append((t - ws[i]) * sec)
    else:
        god.append((t-ws[i])*fir)
print(' '.join([str(i) for i in god]))


I found an interesting problem on https://codeforces.com/problemset/problem/522/C:
Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food.

The flight menu has k dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values a_1, a_2, ..., a_{k}, where a_{i} is the number of portions of the i-th dish.

The stewardess has already given food to m - 1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the m - 1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the m - 1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try.

Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available.

-----Input-----

Each test in this problem consists of one or more input sets. First goes a string that contains a single integer t (1 ≤ t ≤ 100 000) — the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line.

The first line of each set of the input contains integers m, k (2 ≤ m ≤ 100 000, 1 ≤ k ≤ 100 000) — the number of Polycarp's seat and the number of dishes, respectively.

The second line contains a sequence of k integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 100 000), where a_{i} is the initial number of portions of the i-th dish.

Then...

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

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

def testCase():
    m, k = ris()
    q = 0
    a = list(ris())
    some_is_out = False
    tmp = set()
    for i in range(m - 1):
        t, r = ris()
        t -= 1
        if r == 1 and not some_is_out:
            some_is_out = True
            tmp = tmp.union(set([x for x in range(k) if a[x] <= q]))
        if t == -1:
            q += 1
        else:
            if t in tmp:
                tmp.remove(t)
            a[t] -= 1
            if a[t] < 0:
                a[t] = 0
                q += 1
    if tmp:
        q -= min([a[x] for x in tmp])
    print("".join(list(['Y' if a[x] - q <= 0 or x in tmp else 'N' for x in range(len(a))])))

for i in range(int(input())):
    input()
    testCase()


I found an interesting problem on https://codeforces.com/problemset/problem/522/D:
You are given sequence a_1, a_2, ..., a_{n} and m queries l_{j}, r_{j} (1 ≤ l_{j} ≤ r_{j} ≤ n). For each query you need to print the minimum distance between such pair of elements a_{x} and a_{y} (x ≠ y), that:  both indexes of the elements lie within range [l_{j}, r_{j}], that is, l_{j} ≤ x, y ≤ r_{j};  the values of the elements are equal, that is a_{x} = a_{y}.

The text above understands distance as |x - y|.

-----Input-----

The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 5·10^5) — the length of the sequence and the number of queries, correspondingly.

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

Next m lines contain the queries, one per line. Each query is given by a pair of numbers l_{j}, r_{j} (1 ≤ l_{j} ≤ r_{j} ≤ n) — the indexes of the query range limits.

-----Output-----

Print m integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.

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

Output
1
-1
2

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

Output
2
2
3
-1
2

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

import sys

class Fenwick(object):
  def __init__(self, n):
    self.n = n
    self.a = [10**9 for i in range(n)]
    self.w= 10**9

  def zag(self, i, zn):
    self.w= min(self.w, zn)
    while i < self.n:
      self.a[i] = min(self.a[i], zn)
      i = (i | (i + 1))

  def pol(self, r):
    ans= 10**9
    while r >= 0:
      if ans> self.a[r]:
        ans= self.a[r]
      if ans== self.w:
        break
      r = (r & (r + 1)) - 1
    return ans

n, m = [int(x) for x in sys.stdin.readline().split()]
a = [int(x) for x in sys.stdin.readline().split()]

nd= [-1 for i in range(0, len(a))]
vi= {}
for i in range(0, len(a)):
  if a[i] in vi:
    nd[i] = vi[a[i]]
  vi[a[i]] = i

inp= sys.stdin.readlines()
och= [[] for i in range(n)]
for i in range(m):
  l, r = inp[i].split()
  och[int(r) - 1].append((int(l) - 1, i))

der = Fenwick(2 ** 19)
ans= [None for i in range(0, m)]
le= -1
for r in range(n):
  if nd[r] != -1:
    der.zag(500000 - nd[r] + 1, r - nd[r])
    le = max(le, nd[r])
  for (l, ind) in och[r]:
    if l > le:
      ans[ind] = -1
      continue
    zn= der.pol(500000 - l + 1)
    if zn== 10**9:
      zn= -1
    ans[ind] = zn

print('\n'.join(str(zn) for zn in ans))


I found an interesting problem on https://codeforces.com/problemset/problem/523/A:
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.

He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).

Implement this feature to help Polycarp test his editor.

-----Input-----

The first line contains two integers, w and h (1 ≤ w, h ≤ 100) — the width and height of an image in pixels. The picture is given in h lines, each line contains w characters — each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.

-----Output-----

Print 2w lines, each containing 2h characters — the result of consecutive implementing of the three transformations, described above.

-----Examples-----
Input
3 2
.*.
.*.

Output
....
....
****
****
....
....

Input
9...

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

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

matrix_in = [[0 for i in range(a)] for j in range(b)]
for i in range(b):
    line = input()
    for j in range(a):
        matrix_in[i][j] = line[j]

# Right rotate and flip
matrix_rotated = [[0 for i in range(b)] for j in range(a)]
for i in range(a):
    for j in range(b):
        matrix_rotated[i][j] = matrix_in[j][i]

# Print
for i in range(a):
    toprint=""
    for j in range(b):
        toprint += matrix_rotated[i][j]*2
    print(toprint)
    print(toprint)


I found an interesting problem on https://codeforces.com/problemset/problem/523/B:
In this problem you will have to deal with a real algorithm that is used in the VK social network.

As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of T seconds (for example, T = 60 seconds = 1 min and T = 86400 seconds = 1 day). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.

However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.

Let's consider the following formal model. We have a service that works for n seconds. We know the number of queries to this resource a_{t} at each moment of time t (1 ≤ t ≤ n). Let's formulate the following algorithm of calculating the mean with exponential decay. Let c be some real number, strictly larger than one.

// setting this constant value correctly can adjust

// the time range for which statistics will be calculated

double c = some constant value;

// as the result of the algorithm's performance this variable will contain

// the mean number of queries for the last

// T seconds by the current moment of time

double mean = 0.0;

for t = 1..n: // at each second, we do the following:

    // a_{t} is the number of queries that came at the last second;

    mean = (mean + a_{t} / T) / c;

Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant c correctly will make the value of mean not very different...

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

a = list(input().split())
n, T, c = int(a[0]), int(a[1]), float(a[2])
a = list(map(int, input().split()))
m = int(input())
p = list(map(int, input().split()))

sum_a = sum(a[:T - 1])
mean = 0
for t in range(T - 1):
    mean = (mean + a[t]/T) / c

i = 0
for t in range(T - 1, p[-1]):
    sum_a += a[t]
    mean = (mean + a[t]/T) / c
    if t == p[i] - 1:
        real = sum_a / T
        print('%0.6f %0.6f %0.6f' % (real, mean, abs(real - mean) / real))
        i += 1
        if i == len(p) : break
    sum_a -= a[t - T + 1]


I found an interesting problem on https://codeforces.com/problemset/problem/523/C:
A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=«aba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» do not.

However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.

Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.

-----Input-----

The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters.

The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 10^6 letters.

-----Output-----

Print the sought number of ways to cut string t in two so that each part made s happy.

-----Examples-----
Input
aba
baobababbah

Output
2

Input
mars
sunvenusearthmarsjupitersaturnuranusneptune

Output
0

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

s = input()
t = input()

position_left = 0
seen_left = 0

while seen_left < len(s) and position_left < len(t):
    if t[position_left] == s[seen_left]:
        seen_left += 1
    position_left += 1

if seen_left < len(s):
    print(0)
    return

position_right = len(t) - 1
seen_right = 0

while seen_right < len(s) and position_right >= 0:
    if t[position_right] == s[len(s) - seen_right - 1]:
        seen_right += 1
    position_right -= 1

if position_left <= position_right:
    print(position_right - position_left + 2)
else:
    print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/523/D:
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.

We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.

We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.

For each video find the moment it stops being recompressed.

-----Input-----

The first line of the input contains integers n and k (1 ≤ n, k ≤ 5·10^5) — the number of videos and servers, respectively.

Next n lines contain the descriptions of the videos as pairs of integers s_{i}, m_{i} (1 ≤ s_{i}, m_{i} ≤ 10^9), where s_{i} is the time in seconds when the i-th video appeared and m_{i} is its duration in minutes. It is guaranteed that all the s_{i}'s are distinct and the videos are given in the chronological order of upload, that is in the order of increasing s_{i}.

-----Output-----

Print n numbers e_1, e_2, ..., e_{n}, where e_{i} is the time in seconds after the servers start working, when the i-th video will be recompressed.

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

Output
6
7
11

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

Output
1000000001
2000000001
3000000001
4000000001
5000000001
5000000004

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

import heapq
f = lambda: list(map(int, input().split()))
n, k = f()
p = [0] * k
q = [0] * n
for i in range(n):
    s, m = f()
    q[i] = max(p[0], s) + m
    heapq.heapreplace(p, q[i])
print('\n'.join(map(str, q)))


I found an interesting problem on https://codeforces.com/problemset/problem/524/A:
Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если a является другом b, то b также является другом a.

В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.

У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 10^9. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.

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

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

В последующих m строках записано по два числа a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ 10^9, a_{i} ≠ b_{i}), обозначающих идентификаторы пользователей, являющихся друзьями.

Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.

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

Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id:  k id_1 id_2 ... id_{k}", где id — это id самого человека, k — количество его предполагаемых друзей, а id_1, id_2, ..., id_{k} — идентификаторы его предполагаемых друзей в возрастающем порядке.

-----Примеры-----
Входные данные
5 51
10 23
23 42
39 42
10 39
39 58

Выходные данные
10: 1 42
23: 1 39
39: 1 23
42: 1 10
58: 2 10 42

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

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

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

from collections import defaultdict

m, k = map(int, input().split())
friendship = defaultdict(set)
for i in range(m):
    a, b = map(int, input().split())
    friendship[a].add(b)
    friendship[b].add(a)

result = { }
for x, friends in friendship.items():
    s = set()
    for y in friendship:
        if x != y and not y in friends:
            count = 0
            for z in filter(lambda f: y in friendship[f], friends):
                count += 100.0
            if count / len(friends) >= k:
                s.add(y)
    result[x] = s

for x, friends in sorted(result.items()):
    print(x, len(friends), end=' ', sep=": ")
    print(' '.join(map(str, sorted(friends))))


I found an interesting problem on https://codeforces.com/problemset/problem/524/B:
Прошло много лет, и на вечеринке снова встретились n друзей. С момента последней встречи техника шагнула далеко вперёд, появились фотоаппараты с автоспуском, и теперь не требуется, чтобы один из друзей стоял с фотоаппаратом, и, тем самым, оказывался не запечатлённым на снимке.

Упрощенно процесс фотографирования можно описать следующим образом. На фотографии каждый из друзей занимает прямоугольник из пикселей: в стоячем положении i-й из них занимает прямоугольник ширины w_{i} пикселей и высоты h_{i} пикселей. Но также, при фотографировании каждый человек может лечь, и тогда он будет занимать прямоугольник ширины h_{i} пикселей и высоты w_{i} пикселей.

Общая фотография будет иметь размеры W × H, где W — суммарная ширина всех прямоугольников-людей, а H — максимальная из высот. Друзья хотят определить, какую минимальную площадь может иметь общая фотография. Помогите им в этом.

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

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

В последующих n строках следуют по два целых числа w_{i}, h_{i} (1 ≤ w_{i}, h_{i} ≤ 1000), обозначающие размеры прямоугольника, соответствующего i-му из друзей.

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

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

-----Примеры-----
Входные данные
3
10 1
20 2
30 3

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

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

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

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

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

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

def main():
    import sys

    tokens = [int(i) for i in sys.stdin.read().split()]
    tokens.reverse()

    n = tokens.pop()
    people = [(tokens.pop(), tokens.pop()) for i in range(n)]

    result = float("inf")
    for i in range(n):
        for j in range(2):
            maxh = people[i][j]
            S = people[i][j ^ 1]
            for k in range(n):
                if k != i:
                    w, h = people[k]
                    w, h = min(w, h), max(w, h)
                    if w > maxh:
                        S = float("inf")
                        break
                    if h > maxh:
                        S += h
                    else:
                        S += w
            result = min(result, S * maxh)

    print(result)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/524/C:
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.

For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.

Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.

-----Input-----

The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).

The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 10^7) — the denominations of the bills that are used in the country. Numbers a_{i} follow in the strictly increasing order.

The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.

The next q lines contain numbers x_{i} (1 ≤ x_{i} ≤ 2·10^8) — the sums of money in burles that you are going to withdraw from the ATM.

-----Output-----

For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print  - 1, if it is impossible to get the corresponding sum.

-----Examples-----
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950

Output
6
20
19
20
-1
3
-1
-1

Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15

Output
1
1
1
2
2
2
2
-1

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

f = lambda: list(map(int, input().split()))
n, k = f()
t = list(f())

d = {0: 0}
for q in t:
    for i in range(1, k + 1): d[q * i] = i

for j in range(int(input())):
    a = int(input())
    p = [i + d[a - b] for b, i in list(d.items()) if a - b in d]
    print(min(p) if p and min(p) <= k else -1)


I found an interesting problem on https://codeforces.com/problemset/problem/524/D:
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.

But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.

Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:  the number of different users online did not exceed M at any moment,  at some second the number of distinct users online reached value M,  the total number of users (the number of distinct identifiers) was as much as possible.

Help Polycarpus cope with the test.

-----Input-----

The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).

-----Output-----

In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user...

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

def main():
    mode="filee"
    if mode=="file":f=open("test.txt","r")
    get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
    gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")]
    [n,m,t]=get()
    a=[0]*20002
    b=[0]*20002
    if n<m:
        print("No solution")
        return
    for i in range(1,1+n):
        g = gets()
        a[i] = int(g[-1]) + int(g[1])*60 + int(g[0])*3600
        [p,count,sim] = [1,0,0]
    is_solution_there=False
    for i in range(1,n+1):
        while p<i and a[i] - t + 1>a[p]:
            p+=1
            if b[p]!=b[p-1]:
                sim = max(sim-1,0)
        if a[i]<a[p]+t and sim<m:
            count+=1
            sim+=1
        if sim==m:
            is_solution_there=True
        b[i] = count
    if is_solution_there==False:
        print("No solution")
        return
    print(count)
    for i in range(1,n+1):
        print(b[i],end=' ')

    if mode=="file":f.close()

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/525/A:
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.

The potato pie is located in the n-th room and Vitaly needs to go there.

Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key.

In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.

Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.

Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.

Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

-----Input-----

The first line of the input contains a positive integer n (2 ≤ n ≤ 10^5) — the number of rooms in the house.

The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.

The odd positions in...

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

#!/usr/bin/env python
# -.- coding: utf-8 -.-

def main():
    n_rooms = int(input())
    line = input()
    keys = line[0::2]
    doors = line[1::2]
    buykeys = 0
    keyinbag = {}
    for room_index in range(n_rooms - 1):
        if keys[room_index] in keyinbag:
            keyinbag[keys[room_index]] += 1
        else:
            keyinbag[keys[room_index]] = 1
        if not doors[room_index].lower() in keyinbag or\
           keyinbag[doors[room_index].lower()] < 1:
            buykeys += 1
        else:
            keyinbag[doors[room_index].lower()] -= 1
    print(buykeys)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/525/B:
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.

Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer a_{i} and reversed a piece of string (a segment) from position a_{i} to position |s| - a_{i} + 1. It is guaranteed that 2·a_{i} ≤ |s|.

You face the following task: determine what Pasha's string will look like after m days.

-----Input-----

The first line of the input contains Pasha's string s of length from 2 to 2·10^5 characters, consisting of lowercase Latin letters.

The second line contains a single integer m (1 ≤ m ≤ 10^5) —  the number of days when Pasha changed his string.

The third line contains m space-separated elements a_{i} (1 ≤ a_{i}; 2·a_{i} ≤ |s|) — the position from which Pasha started transforming the string on the i-th day.

-----Output-----

In the first line of the output print what Pasha's string s will look like after m days.

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

Output
aedcbf

Input
vwxyz
2
2 2

Output
vwxyz

Input
abcdef
3
1 2 3

Output
fbdcea

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

s = [i for i in input()]
n = int(input())
arr = [int(i) for i in input().split()]
arr.sort()
r = 0
j = 0
for i in range(len(s) // 2):
    while j < n and arr[j] <= i + 1:
        r += 1
        j += 1
    if r % 2 == 1:
        s[i], s[-i - 1] = s[-i - 1], s[i]
print(''.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/525/C:
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length l_{i}.

Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.

Sticks with lengths a_1, a_2, a_3 and a_4 can make a rectangle if the following properties are observed:  a_1 ≤ a_2 ≤ a_3 ≤ a_4  a_1 = a_2  a_3 = a_4

A rectangle can be made of sticks with lengths of, for example, 3 3 3 3 or 2 2 4 4. A rectangle cannot be made of, for example, sticks 5 5 5 7.

Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4.

You have to answer the question — what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?

-----Input-----

The first line of the input contains a positive integer n (1 ≤ n ≤ 10^5) — the number of the available sticks.

The second line of the input contains n positive integers l_{i} (2 ≤ l_{i} ≤ 10^6) — the lengths of the sticks.

-----Output-----

The first line of the output must contain a single non-negative integer — the maximum total area of the rectangles that Ilya can make from the available sticks.

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

Output
8

Input
4
2 2 3 5

Output
0

Input
4
100003 100004 100005 100006

Output
10000800015

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

n = int(input())
a, b = 0, 0
ans = 0
for i in sorted(map(int,input().split()),reverse=True):
    if a == 0 or a > i + 1:
        a = i
    elif b == 0:
        a, b= 0, i
    else:
        ans += i * b
        a, b = 0, 0
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/525/E:
Anya loves to fold and stick. Today she decided to do just that.

Anya has n cubes lying in a line and numbered from 1 to n from left to right, with natural numbers written on them. She also has k stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.

Anya can stick an exclamation mark on the cube and get the factorial of the number written on the cube. For example, if a cube reads 5, then after the sticking it reads 5!, which equals 120.

You need to help Anya count how many ways there are to choose some of the cubes and stick on some of the chosen cubes at most k exclamation marks so that the sum of the numbers written on the chosen cubes after the sticking becomes equal to S. Anya can stick at most one exclamation mark on each cube. Can you do it?

Two ways are considered the same if they have the same set of chosen cubes and the same set of cubes with exclamation marks.

-----Input-----

The first line of the input contains three space-separated integers n, k and S (1 ≤ n ≤ 25, 0 ≤ k ≤ n, 1 ≤ S ≤ 10^16) — the number of cubes and the number of stickers that Anya has, and the sum that she needs to get.

The second line contains n positive integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the numbers, written on the cubes. The cubes in the input are described in the order from left to right, starting from the first one.

Multiple cubes can contain the same numbers.

-----Output-----

Output the number of ways to choose some number of cubes and stick exclamation marks on some of them so that the sum of the numbers became equal to the given number S.

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

Output
1

Input
2 2 7
4 3

Output
1

Input
3 1 1
1 1 1

Output
6

-----Note-----

In the first sample the only way is to choose both cubes and stick an exclamation mark on each of them.

In the second sample the only way is to choose both cubes but don't stick an exclamation mark on any of them.

In the third sample it is possible to choose any of the cubes in three ways, and also...

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

fact = [ 1 ]
for i in range( 1, 20, 1 ):
  fact.append( fact[ i - 1 ] * i )

from collections import defaultdict

N, K, S = list(map( int, input().split() ))
A = list( map( int, input().split() ) )

ldp = [ [ defaultdict( int ) for i in range( K + 1 ) ] for j in range( 2 ) ]
ldp[ 0 ][ 0 ][ 0 ] = 1
for i in range( N // 2 ):
  for j in range( K + 1 ):
    ldp[ ~ i & 1 ][ j ].clear()
  for j in range( K + 1 ):
    for key in ldp[ i & 1 ][ j ]:
      ldp[ ~ i & 1 ][ j ][ key ] += ldp[ i & 1 ][ j ][ key ] # toranai
      ldp[ ~ i & 1 ][ j ][ key + A[ i ] ] += ldp[ i & 1 ][ j ][ key ] # toru
      if j + 1 <= K and A[ i ] <= 18:
        ldp[ ~ i & 1 ][ j + 1 ][ key + fact[ A[ i ] ] ] += ldp[ i & 1 ][ j ][ key ] # kaijyou totte toru

rdp = [ [ defaultdict( int ) for i in range( K + 1 ) ] for j in range( 2 ) ]
rdp[ 0 ][ 0 ][ 0 ] = 1
for i in range( N - N // 2 ):
  for j in range( K + 1 ):
    rdp[ ~ i & 1 ][ j ].clear()
  for j in range( K + 1 ):
    for key in rdp[ i & 1 ][ j ]:
      rdp[ ~ i & 1 ][ j ][ key ] += rdp[ i & 1 ][ j ][ key ]
      rdp[ ~ i & 1 ][ j ][ key + A[ N // 2 + i ] ] += rdp[ i & 1 ][ j ][ key ]
      if j + 1 <= K and A[ N // 2 + i ] <= 18:
        rdp[ ~ i & 1 ][ j + 1 ][ key + fact[ A[ N // 2 + i ] ] ] += rdp[ i & 1 ][ j ][ key ]

ans = 0
for i in range( K + 1 ):
  for key in ldp[ N // 2 & 1 ][ i ]:
    for j in range( 0, K - i + 1, 1 ):
      ans += ldp[ N // 2 & 1 ][ i ][ key ] * rdp[ N - N // 2 & 1 ][ j ][ S - key ]

print( ans )


I found an interesting problem on https://codeforces.com/problemset/problem/526/A:
In this problem you will meet the simplified model of game King of Thieves.

In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. [Image]

An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.

A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.

One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i_1, he can make a sequence of jumps through the platforms i_1 < i_2 < ... < i_{k}, if i_2 - i_1 = i_3 - i_2 = ... = i_{k} - i_{k} - 1. Of course, all segments i_1, i_2, ... i_{k} should be exactly the platforms, not pits.

Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i_1, i_2, ..., i_5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of segments on the level.

Next line contains the scheme of the level represented as a string of n characters '*' and '.'.

-----Output-----

If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).

-----Examples-----
Input
16
.**.*..*.***.**.

Output
yes
Input
11
.*.*...*.*.

Output
no

-----Note-----

In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14.

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

kk=0
x = int(input())
y = input()
z = [i for i in range(len(y)) if y[i] == '*']
for i in range(0, 100):
    for j in range(1, 100):
        if i in z and i+j in z and i+2*j in z and i+3*j in z and i+4*j in z:
            kk=1
if kk==1:
    print("yes")
else:
    print("no")


I found an interesting problem on https://codeforces.com/problemset/problem/526/B:
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. [Image]

The park consists of 2^{n} + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2^{n}, 2^{n} + 1, ..., 2^{n} + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2^{n} + 1) there is a road to the square $\lfloor \frac{i}{2} \rfloor$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.  [Image]  To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square $\lfloor \frac{i}{2} \rfloor$ has a_{i} lights.

Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.

He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit.

The next line contains 2^{n} + 1 - 2 numbers a_2, a_3, ... a_2^{n} + 1 - 1 — the initial numbers of street lights on each road of the park. Here a_{i} is the number of street lights on the road between squares i and $\lfloor \frac{i}{2} \rfloor$. All numbers a_{i} are positive...

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

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: firolunis
# version: 0.1

n = int(input())
park = input().split(' ')
park = [int(i) for i in park]
park.insert(0, 0)
lights = [0 for i in range(2 ** (n + 1) - 1)]
res = 0
for k in range(n, 0, -1):
    for i, j in tuple(enumerate(park))[(2 ** k) - 1:2 ** (k + 1) - 1:2]:
        res += abs(j + lights[i] - park[i + 1] - lights[i + 1])
        lights[i // 2] = max(j + lights[i], park[i + 1] + lights[i + 1])
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/526/C:
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? [Image]

One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs W_{r} grams and each blue candy weighs W_{b} grams. Eating a single red candy gives Om Nom H_{r} joy units and eating a single blue candy gives Om Nom H_{b} joy units.

Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.

-----Input-----

The single line contains five integers C, H_{r}, H_{b}, W_{r}, W_{b} (1 ≤ C, H_{r}, H_{b}, W_{r}, W_{b} ≤ 10^9).

-----Output-----

Print a single integer — the maximum number of joy units that Om Nom can get.

-----Examples-----
Input
10 3 5 2 3

Output
16

-----Note-----

In the sample test Om Nom can eat two candies of each type and thus get 16 joy units.

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

def main():
    c, hr, hb, wr, wb = (int(i) for i in input().split())

    if wb < c**(1/2) > wr:
        if hr / wr < hb / wb:
            wr, hr, wb, hb = wb, hb, wr, hr
        mx = 0
        for i in range(wr + 1):
            tmx = i * hb + ((c - i * wb) // wr) * hr
            mx  = tmx if tmx > mx else mx
    else:
        if wr <= wb:
            wr, hr, wb, hb = wb, hb, wr, hr
        nr = 0
        mx = 0
        while nr * wr <= c:
            tmx = nr * hr + ((c - nr * wr) // wb) * hb
            mx = tmx if tmx > mx else mx
            nr += 1

    print(mx)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/527/A:
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm  ×  b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.

 [Image]

After making a paper ship from the square piece, Vasya looked on the remaining (a - b) mm  ×  b mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.

Can you determine how many ships Vasya will make during the lesson?

-----Input-----

The first line of the input contains two integers a, b (1 ≤ b < a ≤ 10^12) — the sizes of the original sheet of paper.

-----Output-----

Print a single integer — the number of ships that Vasya will make.

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

Output
2

Input
10 7

Output
6

Input
1000000000000 1

Output
1000000000000

-----Note-----

Pictures to the first and second sample test.

 [Image]

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

a, b = list(map(int, input().split()))
num = 0
while b > 0:
    temp = b
    num += (a // b)
    b = a % b
    a = temp
print(num)


I found an interesting problem on https://codeforces.com/problemset/problem/527/B:
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.

Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.

Help him do this!

-----Input-----

The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.

The second line contains string S.

The third line contains string T.

Each of the lines only contains lowercase Latin letters.

-----Output-----

In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.

In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.

If there are multiple possible answers, print any of...

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

import string

n, s, t = int(input()), input(), input()
x, i, j = 0, -1, -1
sc_dict = {c: set() for c in string.ascii_lowercase}
tc_dict = {c: set() for c in string.ascii_lowercase}
sti_dict, tsi_dict = dict(), dict()

for ci, sc, tc in zip(list(range(n)), s, t):
    if sc == tc:
        continue
    sc_dict[sc].add(tc)
    tc_dict[tc].add(sc)
    sti_dict[sc + tc] = ci
    tsi_dict[tc + sc] = ci
    x += 1

for c in string.ascii_lowercase:
    cs = sc_dict[c] & tc_dict[c]
    if not cs:
        continue
    c2 = cs.pop()
    x -= 2
    i = sti_dict[c + c2] + 1
    j = tsi_dict[c + c2] + 1
    break
else:
    for c in string.ascii_lowercase:
        if not sc_dict[c] or not tc_dict[c]:
            continue
        x -= 1
        i = sti_dict[c + sc_dict[c].pop()] + 1
        j = tsi_dict[c + tc_dict[c].pop()] + 1
        break

print(x)
print(i, j)


I found an interesting problem on https://codeforces.com/problemset/problem/527/C:
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm  ×  h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.

In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.

After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.

Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?

-----Input-----

The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).

Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.

-----Output-----

After each cut print on a single line the area of the maximum available glass fragment in mm^2.

-----Examples-----
Input
4 3 4
H 2
V 2
V 3
V 1

Output
8
4
4
2

Input
7 6 5
H 4
V 3
V 5
H 2
V 1

Output
28
16
12
6
4

-----Note-----

Picture for the first sample test:  [Image]  Picture for the second sample test:  $\square$

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

def main():
    from sys import stdin
    w, h, n = list(map(int, stdin.readline().split()))
    res, vrt, hor = [], [], []
    vh = (vrt, hor)
    for i, s in enumerate(stdin.read().splitlines()):
        x = int(s[2:])
        flag = s[0] == 'V'
        vh[flag].append(i)
        res.append([x, flag])
    dim = []
    for tmp, m in zip(vh, (h, w)):
        tmp.sort(key=lambda e: res[e][0])
        u = [None, [0]]
        dim.append(u)
        j = z = 0
        for i in tmp:
            x = res[i][0]
            if z < x - j:
                z = x - j
            j = x
            v = [u, res[i]]
            u.append(v)
            u = v
            res[i].append(u)
        v = [u, [m], None]
        u.append(v)
        dim.append(v)
        if z < m - j:
            z = m - j
        dim.append(z)
    l, r, wmax, u, d, hmax = dim
    whmax = [wmax, hmax]
    for i in range(n - 1, -1, -1):
        x, flag, link = res[i]
        u = whmax[flag]
        res[i] = u * whmax[not flag]
        link[0][2] = link[2]
        link[2][0] = link[0]
        v = link[2][1][0] - link[0][1][0]
        if u < v:
            whmax[flag] = v
    print('\n'.join(map(str, res)))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/527/D:
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.

Consider n distinct points on a line. Let the i-th point have the coordinate x_{i} and weight w_{i}. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |x_{i} - x_{j}| ≥ w_{i} + w_{j}.

Find the size of the maximum clique in such graph.

-----Input-----

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

Each of the next n lines contains two numbers x_{i}, w_{i} (0 ≤ x_{i} ≤ 10^9, 1 ≤ w_{i} ≤ 10^9) — the coordinate and the weight of a point. All x_{i} are different.

-----Output-----

Print a single number — the number of vertexes in the maximum clique of the given graph.

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

Output
3

-----Note-----

If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!

The picture for the sample test. [Image]

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

N = int(input())

pairs = []
for i in range(N):
    x, w = list(map(int, input().split()))
    pairs.append((x, w))

sorted_pairs = sorted(pairs, key=lambda x: x[0])

stack = []
stack.append(sorted_pairs[0])
for x, w in sorted_pairs[1:N]:
    right_x, right_w = stack[-1]
    if right_x + right_w <= x - w:
        stack.append((x, w))
    else:
        if x + w < right_x + right_w:
            stack[-1] = (x, w)

print(len(stack))


I found an interesting problem on https://codeforces.com/problemset/problem/529/B:
Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.

Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a w_{i} pixels wide and a h_{i} pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a h_{i} pixels wide and a w_{i} pixels high rectangle.

The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..)

Help them to achieve this goal.

-----Input-----

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

The next n lines have two integers w_{i}, h_{i} (1 ≤ w_{i}, h_{i} ≤ 1000) each, representing the size of the rectangle, corresponding to the i-th friend.

-----Output-----

Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground.

-----Examples-----
Input
3
10 1
20 2
30 3

Output
180

Input
3
3 1
2 2
4 3

Output
21

Input
1
5 10

Output
50

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

from operator import neg
n = int(input())
a = [tuple(map(int, input().split())) for i in range(n)]

def check(max_h):
    k = n // 2
    b = []
    for w, h in a:
        if h > max_h:
            if k <= 0 or w > max_h:
                return 1 << 60
            b.append((h, w))
            k -= 1
        else:
            b.append((w, h))
    b.sort(key=lambda t: t[1] - t[0])
    r = 0
    for w, h in b:
        if k > 0 and w <= max_h and h < w:
            r += h
            k -= 1
        else:
            r += w
    return r * max_h

print(min(check(h) for h in range(1, 1001)))


I found an interesting problem on https://codeforces.com/problemset/problem/532/C:
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move.

There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0).

You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.

-----Input-----

The first line contains four integers: x_{p}, y_{p}, x_{v}, y_{v} (0 ≤ x_{p}, y_{p}, x_{v}, y_{v} ≤ 10^5) — Polycarp's and Vasiliy's starting coordinates.

It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).

-----Output-----

Output the name of the winner: "Polycarp" or "Vasiliy".

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

Output
Polycarp

Input
4 7 7 4

Output
Vasiliy

-----Note-----

In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn.

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

xp, yp, xv, yv = list(map(int, input().split()))
if xv >= xp and yv >= yp:
    print("Polycarp")
elif yv >= yp + xp:
    print("Polycarp")
elif xv >= xp + yp:
    print("Polycarp")
else:
    print("Vasiliy")


I found an interesting problem on https://codeforces.com/problemset/problem/532/E:
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.

Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.

Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T.

The second line contains word S.

The third line contains word T.

Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.

-----Output-----

Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo.

-----Examples-----
Input
7
reading
trading

Output
1

Input
5
sweet
sheep

Output
0

Input
3
toy
try

Output
2

-----Note-----

In the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).

In the second sample test the two given words couldn't be obtained from the same word by removing one letter.

In the third sample test the two given words could be obtained from either word "tory" or word "troy".

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

import sys

n = int(sys.stdin.readline())
s = sys.stdin.readline().strip()
t = sys.stdin.readline().strip()

can1 = 1
can2 = 1
ft = -1
for i in range(n):
	if s[i] != t[i]:
		ft = i
		break

def check(ft, s, t):
	lt = n-1
	for i in range(ft, n-1):
		if s[i] != t[i+1]:
			lt = i
			break
	for i in range(lt + 1, n):
		if s[i] != t[i]:
			return 0
	return 1

print(check(ft, s, t) + check(ft, t, s))


I found an interesting problem on https://codeforces.com/problemset/problem/534/A:
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.

Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.

-----Input-----

A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.

-----Output-----

In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.

In the second line print k distinct integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ n), where a_{i} is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |a_{i} - a_{i} + 1| ≠ 1 for all i from 1 to k - 1.

If there are several possible answers, output any of them.

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

Output
2
1 3

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

n = int(input())

if n == 1:
	print(1)
	print(1)
elif n == 2:
	print(1)
	print(2)
elif n == 3:
	print(2)
	print(*[1, 3])
elif n == 4:
	print(4)
	print(*[3, 1, 4, 2])
else:

	L = [0]*n

	i = 0
	j = 1
	while j <= n:
		L[i] = j
		j += 2
		i += 1

	j = 2
	while j <= n:
		L[i] = j
		i += 1
		j += 2

	print(len(L))
	print(*L)


I found an interesting problem on https://codeforces.com/problemset/problem/534/B:
The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals v_1 meters per second, and in the end it is v_2 meters per second. We know that this section of the route took exactly t seconds to pass.

Assuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by d meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed d in absolute value), find the maximum possible length of the path section in meters.

-----Input-----

The first line contains two integers v_1 and v_2 (1 ≤ v_1, v_2 ≤ 100) — the speeds in meters per second at the beginning of the segment and at the end of the segment, respectively.

The second line contains two integers t (2 ≤ t ≤ 100) — the time when the car moves along the segment in seconds, d (0 ≤ d ≤ 10) — the maximum value of the speed change between adjacent seconds.

It is guaranteed that there is a way to complete the segment so that:  the speed in the first second equals v_1,  the speed in the last second equals v_2,  the absolute value of difference of speeds between any two adjacent seconds doesn't exceed d.

-----Output-----

Print the maximum possible length of the path segment in meters.

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

Output
26
Input
10 10
10 0

Output
100

-----Note-----

In the first sample the sequence of speeds of Polycarpus' car can look as follows: 5, 7, 8, 6. Thus, the total path is 5 + 7 + 8 + 6 = 26 meters.

In the second sample, as d = 0, the car covers the whole segment at constant speed v = 10. In t = 10 seconds it covers the distance of 100 meters.

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

#sry...

v1, v2 = list(map(int, input().split()))
t, d = list(map(int, input().split()))
L1 = [0]*t
L2 = [0]*t
L1[0] = v1
for i in range(1, t):
    L1[i] = L1[i-1]+d
j = t-2
L2[j+1] = v2
while j >= 0:
    L2[j] = L2[j+1]+d
    j -= 1
ans = 0
for i in range(0, t):
    ans += min(L1[i], L2[i])
print (ans)


I found an interesting problem on https://codeforces.com/problemset/problem/534/C:
Polycarp has n dice d_1, d_2, ..., d_{n}. The i-th dice shows numbers from 1 to d_{i}. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d_1, d_2, ..., d_{n}. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).

For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.

-----Input-----

The first line contains two integers n, A (1 ≤ n ≤ 2·10^5, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d_1 + d_2 + ... + d_{n}.

The second line contains n integers d_1, d_2, ..., d_{n} (1 ≤ d_{i} ≤ 10^6), where d_{i} is the maximum value that the i-th dice can show.

-----Output-----

Print n integers b_1, b_2, ..., b_{n}, where b_{i} is the number of values for which it is guaranteed that the i-th dice couldn't show them.

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

Output
3 3
Input
1 3
5

Output
4
Input
2 3
2 3

Output
0 1

-----Note-----

In the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.

In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.

In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.

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

3

import sys

n, A = list(map(int, sys.stdin.readline().split()))
d = list(map(int, sys.stdin.readline().split()))

s = sum(d)

for x in d:
    z = min(A - n + 1, x) - max(1, A - s + x) + 1
    if z < 0:
        z = 0
    sys.stdout.write("%d " % (x - z))

sys.stdout.write('\n')


I found an interesting problem on https://codeforces.com/problemset/problem/534/D:
On February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.

At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.

Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.

Please note that some students could work independently until the end of the day, without participating in a team contest.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2·10^5) — the number of students who came to CTOP. The next line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} < n), where a_{i} is the number of students with who the i-th student shook hands.

-----Output-----

If the sought order of students exists, print in the first line "Possible" and in the second line print the permutation of the students' numbers defining the order in which the students entered the center. Number i that stands to the left of number j in this permutation means that the i-th student came earlier than the j-th student. If there are multiple answers, print any of them.

If the sought order of students doesn't exist, in a single line print "Impossible".

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

Output
Possible
4 5 1 3 2
Input
9
0 2 3 4 1...

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

n=int(input())
c=[[] for i in range(n)]
[c[int(x)].append(i+1) for i,x in enumerate(input().split())]
s=0;r=[]
for i in range(n):
    while len(c[s])==0 and s>=0:
        s-=3
    if s<0:
        print('Impossible')
        break
    else:
        r+=[c[s].pop()]
        s+=1
else:
     print('Possible')
     print(*r)


I found an interesting problem on https://codeforces.com/problemset/problem/534/E:
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance a_{i} from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, a_{i} < a_{i} + 1 for all i from 1 to n - 1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number n, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop n. During the day, the bus runs non-stop on this route.

The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.

One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.

For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: $5 \rightarrow 6 \rightarrow 5 \rightarrow 4 \rightarrow 3$, then the request about this segment of the path will have form: 3, 4, 5, 5, 6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have...

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

r = lambda: list(map(int, input().split()))
ri = lambda: int(input())
n, a, m, b = ri(), r(), ri(), r()
c = [0] * n
for e in b: c[e - 1] += 1
c[0] *= 2; c[-1] *= 2
d = 0
df= 0
r = max(e // 2 for e in c)
c = [e - r * 2 for e in c]
if any(c):
    for i in range(n - 1):
        de = a[i+1] - a[i]
        d += min(c[i], c[i+1]) * de
        df += de
    print(d + r * 2 * df)
else:
    de = a[1] - a[0]
    for i in range(1, n - 1):
        if a[i + 1] - a[i] != de: print(-1); break
    else: print(r * de * 2 * (n - 1) - de)


I found an interesting problem on https://codeforces.com/problemset/problem/535/A:
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.

His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words. [Image]

He ate coffee mix without water again, so right now he's really messed up and can't think.

Your task is to help him by telling him what to type.

-----Input-----

The first and only line of input contains an integer s (0 ≤ s ≤ 99), Tavas's score.

-----Output-----

In the first and only line of output, print a single string consisting only from English lowercase letters and hyphens ('-'). Do not use spaces.

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

Output
six

Input
99

Output
ninety-nine

Input
20

Output
twenty

-----Note-----

You can find all you need to know about English numerals in http://en.wikipedia.org/wiki/English_numerals .

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

n=int(input())
s = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
s1 =['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
s2 =['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
if n<=10:
    print(s[n])
elif n<20:
    print(s1[n%10-1])
else:
    print(s2[n//10-2], end='')
    if n%10!=0:
        print('-', s[n%10], sep='', end='')


I found an interesting problem on https://codeforces.com/problemset/problem/535/B:
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." [Image]

The problem is:

You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

If we sort all lucky numbers in increasing order, what's the 1-based index of n?

Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.

-----Input-----

The first and only line of input contains a lucky number n (1 ≤ n ≤ 10^9).

-----Output-----

Print the index of n among all lucky numbers.

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

Output
1

Input
7

Output
2

Input
77

Output
6

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

s = str(input())
l = ""
for i in s:
    if i == "4":
        l+= "0"
    else:
        l+= "1"

sum = 0
for i in range(0, len(s)):
    sum+= 2**i

sum+=int(l, 2)

print(sum)


I found an interesting problem on https://codeforces.com/problemset/problem/535/C:
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. [Image]

Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is s_{i} = A + (i - 1) × B.

For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.

Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence s_{l}, s_{l} + 1, ..., s_{r} can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

-----Input-----

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

Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 10^6) for i-th query.

-----Output-----

For each query, print its answer in a single line.

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

Output
4
-1
8
-1

Input
1 5 2
1 5 10
2 7 4

Output
1
2

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

f = lambda: list(map(int, input().split()))
A, B, n = f()
k = 0.5
for i in range(n):
    l, t, m = f()
    b = A / B + l - k
    c = b - k - (m * t) / B
    r = min(l + int((b * b - 2 * c) ** k - b), (t - A) // B + 1)
    print(-1 if r < l else r)


I found an interesting problem on https://codeforces.com/problemset/problem/535/D:
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. [Image]

Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x_1 < x_2 < ... < x_{k} where p matches s. More formally, for each x_{i} (1 ≤ i ≤ k) he condition s_{x}_{i}s_{x}_{i} + 1... s_{x}_{i} + |p| - 1 = p is fullfilled.

Then Malekas wrote down one of subsequences of x_1, x_2, ... x_{k} (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).

After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.

Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.

Answer can be very large, so Tavas wants you to print the answer modulo 10^9 + 7.

-----Input-----

The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1 ≤ n ≤ 10^6 and 0 ≤ m ≤ n - |p| + 1).

The second line contains string p (1 ≤ |p| ≤ n).

The next line contains m space separated integers y_1, y_2, ..., y_{m}, Malekas' subsequence (1 ≤ y_1 < y_2 < ... < y_{m} ≤ n - |p| + 1).

-----Output-----

In a single line print the answer modulo 1000 000 007.

-----Examples-----
Input
6 2
ioi
1 3

Output
26

Input
5 2
ioi
1 2

Output
0

-----Note-----

In the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.

Here |x| denotes the length of string x.

Please note that it's possible that there is no such string (answer is 0).

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

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

def solve():
    n, m = list(map(int, input().split()))
    p = input()
    if m == 0:
        return powmod(n)
    delta = len(p) - 1
    ys = list(map(int, input().split()))
    tail = 0
    free_chars = 0
    for y in ys:
        if y > tail:
            free_chars += y - tail - 1
        elif not is_consistent(p, tail - y + 1):
            return 0
        tail = y + delta
    free_chars += n - tail
    return powmod(free_chars)

ok_set = set()
def is_consistent(p, margin):
    nonlocal ok_set
    if margin in ok_set:
        return True
    elif p[:margin] == p[-margin:]:
        ok_set.add(margin)
        return True
    else:
        return False

def powmod(p):
    mod = 10**9 + 7
    pbin = bin(p)[2:][-1::-1]
    result = 26 if pbin[0] == '1' else 1
    tmp = 26
    for bit in pbin[1:]:
        tmp *= tmp
        tmp %= mod
        if bit == '1':
            result *= tmp
            result %= mod
    return result

print(solve())


I found an interesting problem on https://codeforces.com/problemset/problem/538/A:
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforces^{ω} that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.

There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.

Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.

-----Input-----

The single line of the input contains the word written on the banner. The word only consists of upper-case English letters. The word is non-empty and its length doesn't exceed 100 characters. It is guaranteed that the word isn't word CODEFORCES.

-----Output-----

Print 'YES', if there exists a way to cut out the substring, and 'NO' otherwise (without the quotes).

-----Examples-----
Input
CODEWAITFORITFORCES

Output
YES

Input
BOTTOMCODER

Output
NO

Input
DECODEFORCES

Output
YES

Input
DOGEFORCES

Output
NO

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

s, t = 'CODEFORCES', input().strip()
print('YES' if any(s[:i] == t[:i] and s[i:] == t[len(t) - len(s) + i:] for i in range(len(s) + 1)) else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/538/B:
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.

You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^6).

-----Output-----

In the first line print a single integer k — the minimum number of numbers in the representation of number n as a sum of quasibinary numbers.

In the second line print k numbers — the elements of the sum. All these numbers should be quasibinary according to the definition above, their sum should equal n. Do not have to print the leading zeroes in the numbers. The order of numbers doesn't matter. If there are multiple possible representations, you are allowed to print any of them.

-----Examples-----
Input
9

Output
9
1 1 1 1 1 1 1 1 1

Input
32

Output
3
10 11 11

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

l = list(map(int,list(input())))
print(max(l))
ans = []
while l.count(0) != len(l):
    k = ['0' for i in range(len(l))]
    for i in range(len(l)):
        if l[i] != 0:
            l[i] -= 1
            k[i] = '1'
    ans.append(str(int(''.join(k))))
print(' '.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/538/C:
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer h_{i}. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |h_{i} - h_{i} + 1| ≤ 1 holds.

At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |h_{i} - h_{i} + 1| ≤ 1.

-----Input-----

The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 10^8, 1 ≤ m ≤ 10^5) — the number of days of the hike and the number of notes left in the journal.

Next m lines contain two space-separated integers d_{i} and h_{d}_{i} (1 ≤ d_{i} ≤ n, 0 ≤ h_{d}_{i} ≤ 10^8) — the number of the day when the i-th note was made and height on the d_{i}-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: d_{i} < d_{i} + 1.

-----Output-----

If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route.

If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).

-----Examples-----
Input
8 2
2 0
7 0

Output
2

Input
8 3
2 0
7 0
8 3

Output
IMPOSSIBLE

-----Note-----

For the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).

In the second sample the inequality between h_7 and h_8 does not hold, thus the information is inconsistent.

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

N,M = list(map(int,input().split()))
H = []
for i in range(M):
    d,h = list(map(int,input().split()))
    H.append((d,h))
#print(H[0])
best = (H[0][0]-1) + H[0][1]
for i in range(M - 1):
    diffd = H[i + 1][0] - H[i][0]
    diffh = abs(H[i + 1][1] - H[i][1])
    if (diffd >= diffh):
        best = max(best,max(H[i + 1][1],H[i][1]) + ((diffd - diffh) // 2))
    else:
        print("IMPOSSIBLE")
        break
else:
    best = max(best,H[M - 1][1] + (N - H[M - 1][0]))
    print(best)