I found an interesting problem on https://codeforces.com/problemset/problem/688/A:
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.

For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.

Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.

-----Input-----

The first line of the input contains two integers n and d (1 ≤ n, d ≤ 100) — the number of opponents and the number of days, respectively.

The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.

-----Output-----

Print the only integer — the maximum number of consecutive days that Arya will beat all present opponents.

-----Examples-----
Input
2 2
10
00

Output
2

Input
4 1
0100

Output
1

Input
4 5
1101
1111
0110
1011
1111

Output
2

-----Note-----

In the first and the second samples, Arya will beat all present opponents each of the d days.

In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4.

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

n, d = [int(x) for x in input().split()]
max_vic = 0
vic = 0
test = '1'*n
for i in range(d):
    if input() == test:
        max_vic = max(vic, max_vic)
        vic = 0
    else:
        vic += 1
max_vic = max(vic, max_vic)
print(max_vic)


I found an interesting problem on https://codeforces.com/problemset/problem/688/B:
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.

Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.

Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?

-----Input-----

The only line of the input contains a single integer n (1 ≤ n ≤ 10^{100 000}).

-----Output-----

Print the n-th even-length palindrome number.

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

Output
11

Input
10

Output
1001

-----Note-----

The first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.

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


I found an interesting problem on https://codeforces.com/problemset/problem/689/A:
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: [Image]

Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253": [Image]  [Image]

Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?

-----Input-----

The first line of the input contains the only integer n (1 ≤ n ≤ 9) — the number of digits in the phone number that Mike put in.

The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.

-----Output-----

If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.

Otherwise print "NO" (without quotes) in the first line.

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

Output
NO

Input
2
09

Output
NO

Input
9
123456789

Output
YES

Input
3
911

Output
YES

-----Note-----

You can find the picture clarifying the first sample case in the statement above.

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

n = int(input())
numb = input()
num = [0]*10
for i in numb:
    num[int(i)] = 1
ans = 0
if num[1] + num[2] + num[3] > 0:
    ans += 1
if num[1] + num[4] + num[7] + num[0] > 0:
    ans += 1
if num[3] + num[6] + num[9] + num[0] > 0:
    ans += 1
if num[7] + num[0] + num[9] > 0:
    ans += 1
if ans == 4:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/689/B:
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.

City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number i to intersection j requires |i - j| units of energy. The total energy spent by Mike to visit a sequence of intersections p_1 = 1, p_2, ..., p_{k} is equal to $\sum_{i = 1}^{k - 1}|p_{i} - p_{i + 1}$ units of energy.

Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly n shortcuts in Mike's city, the i^{th} of them allows walking from intersection i to intersection a_{i} (i ≤ a_{i} ≤ a_{i} + 1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence p_1 = 1, p_2, ..., p_{k} then for each 1 ≤ i < k satisfying p_{i} + 1 = a_{p}_{i} and a_{p}_{i} ≠ p_{i} Mike will spend only 1 unit of energy instead of |p_{i} - p_{i} + 1| walking from the intersection p_{i} to intersection p_{i} + 1. For example, if Mike chooses a sequence p_1 = 1, p_2 = a_{p}_1, p_3 = a_{p}_2, ..., p_{k} = a_{p}_{k} - 1, he spends exactly k - 1 units of total energy walking around them.

Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1 ≤ i ≤ n Mike is interested in finding minimum possible total energy of some sequence p_1 = 1, p_2, ..., p_{k} = i.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 200 000) — the number of Mike's city intersection.

The second line contains n integers a_1, a_2, ..., a_{n} (i ≤ a_{i} ≤ n , $a_{i} \leq a_{i + 1} \forall i < n)$, describing shortcuts of Mike's city, allowing to walk from intersection i to intersection...

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

"""
Codeforces Round #361 (Div. 2)

Problem 689 B. Mike and Shortcuts

@author yamaton
@date 2016-07-09
"""

import itertools as it
import functools
import operator
import collections
import math
import sys

def solve(xs, n):
    nodes = list(range(1, n+1))

    neighbors = collections.defaultdict(set)
    for from_, to_ in zip(nodes, nodes[1:]):
        neighbors[from_].add(to_)
        neighbors[to_].add(from_)
    for from_, to_ in enumerate(xs, 1):
        neighbors[from_].add(to_)

    distance = {1: 0}
    q = collections.deque([1])
    while q:
        node = q.popleft()
        for x in neighbors[node]:
            if x not in distance:
                distance[x] = distance[node] + 1
                q.append(x)
    return [distance[i] for i in nodes]

def pp(*args, **kwargs):
    return print(*args, file=sys.stderr, **kwargs)

def main():
    n = int(input())
    xs = [int(s) for s in input().strip().split()]
    assert len(xs) == n
    result = solve(xs, n)
    print(*result)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/689/C:
Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible!

Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly k times more than the previous one. The value of k (k > 1) is a secret integer known only to them. It is also known that each thief's bag can carry at most n chocolates (if they intend to take more, the deal is cancelled) and that there were exactly four thieves involved.

Sadly, only the thieves know the value of n, but rumours say that the numbers of ways they could have taken the chocolates (for a fixed n, but not fixed k) is m. Two ways are considered different if one of the thieves (they should be numbered in the order they take chocolates) took different number of chocolates in them.

Mike want to track the thieves down, so he wants to know what their bags are and value of n will help him in that. Please find the smallest possible value of n or tell him that the rumors are false and there is no such n.

-----Input-----

The single line of input contains the integer m (1 ≤ m ≤ 10^15) — the number of ways the thieves might steal the chocolates, as rumours say.

-----Output-----

Print the only integer n — the maximum amount of chocolates that thieves' bags can carry. If there are more than one n satisfying the rumors, print the smallest one.

If there is no such n for a false-rumoured m, print  - 1.

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

Output
8

Input
8

Output
54

Input
10

Output
-1

-----Note-----

In the first sample case the smallest n that leads to exactly one way of stealing chocolates is n = 8, whereas the amounts of stealed chocolates are (1, 2, 4, 8) (the number of chocolates stolen by each of the thieves).

In the second sample case the smallest n that leads to exactly 8 ways is n = 54 with the possibilities: (1, 2, 4, 8),  (1, 3, 9, 27),  (2, 4, 8, 16),  (2, 6, 18, 54),  (3, 6, 12, 24),  (4, 8, 16, 32),  (5, 10,...

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

n = int(input())
l, r = 0, 10**16
D = [x ** 3.0 for x in range(2, 170417)]
DD = [x*x*x for x in range(2, 170417)]
while l < r:
    m = (l+r) // 2
    if sum(int(m/d) for d in D) < n:
        l = m + 1
    else:
        r = m;
if sum(l//d for d in DD) == n:
    print(l);
else :
    print((-1));


I found an interesting problem on https://codeforces.com/problemset/problem/689/D:
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows?

Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r), Mike can instantly tell the value of $\operatorname{max}_{i = l}^{r} a_{i}$ while !Mike can instantly tell the value of $\operatorname{min}_{i = l} b_{i}$.

Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l, r) (1 ≤ l ≤ r ≤ n) (so he will make exactly n(n + 1) / 2 queries) and counts how many times their answers coincide, thus for how many pairs $\operatorname{max}_{i = l}^{r} a_{i} = \operatorname{min}_{i = l} b_{i}$ is satisfied.

How many occasions will the robot count?

-----Input-----

The first line contains only integer n (1 ≤ n ≤ 200 000).

The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the sequence a.

The third line contains n integer numbers b_1, b_2, ..., b_{n} ( - 10^9 ≤ b_{i} ≤ 10^9) — the sequence b.

-----Output-----

Print the only integer number — the number of occasions the robot will count, thus for how many pairs $\operatorname{max}_{i = l}^{r} a_{i} = \operatorname{min}_{i = l} b_{i}$ is satisfied.

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

Output
2

Input
3
3 3 3
1 1 1

Output
0

-----Note-----

The occasions in the first sample case are:

1.l = 4,r = 4 since max{2} = min{2}.

2.l = 4,r = 5 since max{2, 1} = min{2, 3}.

There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1.

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

from bisect import bisect

HISENTINEL = 10**9 + 1
LOSENTINEL = -HISENTINEL

def main():
    length = int(input())
    a = [int(fld) for fld in input().strip().split()]
    b = [int(fld) for fld in input().strip().split()]
    print(countmaxminsubseq(a, b))

def countmaxminsubseq(a, b):
    leq, lgt = getleftbounds(a, b, 0)
    req, rgt = getleftbounds(reversed(a), reversed(b), 1)
    req = reverseindex(req)
    rgt = reverseindex(rgt)
    count = 0
    for i, (leq1, lgt1, req1, rgt1) in enumerate(zip(leq, lgt, req, rgt)):
        count += (leq1 - lgt1)*(rgt1 - i) + (i - leq1)*(rgt1 - req1)
    return count

def getleftbounds(a, b, bias):
    astack = [(HISENTINEL, -1)]
    bstack = [(LOSENTINEL, -1)]
    leqarr, lgtarr = [], []
    for i, (aelt, belt) in enumerate(zip(a, b)):
        while astack[-1][0] < aelt + bias:
            astack.pop()
        lgt = astack[-1][1]
        while bstack[-1][0] > belt:
            bstack.pop()
        if belt < aelt:
            leq = lgt = i
        elif belt == aelt:
            leq = i
            istack = bisect(bstack, (aelt, -2)) - 1
            lgt = max(lgt, bstack[istack][1])
        else:
            istack = bisect(bstack, (aelt, i)) - 1
            val, pos = bstack[istack]
            if val < aelt:
                lgt = leq = max(lgt, pos)
            else:
                leq = pos
                istack = bisect(bstack, (aelt, -2)) - 1
                val, pos = bstack[istack]
                lgt = max(lgt, pos)
                leq = max(leq, lgt)

        leqarr.append(leq)
        lgtarr.append(lgt)
        astack.append((aelt, i))
        bstack.append((belt, i))
    return leqarr, lgtarr

def reverseindex(rind):
    pivot = len(rind) - 1
    return [pivot - i for i in reversed(rind)]

main()


I found an interesting problem on https://codeforces.com/problemset/problem/689/E:
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that $f(\varnothing) = 0$). You are given two integers n and k and n closed intervals [l_{i}, r_{i}] on OX axis and you have to find: $\sum_{1 \leq i_{1} < i_{2} < \ldots < i_{k} \leq n} f([ l_{i_{1}}, r_{i_{1}} ] \cap [ l_{i_{2}}, r_{i_{2}} ] \cap \ldots \cap [ l_{i_{k}}, r_{i_{k}} ])$

In other words, you should find the sum of the number of integer points in the intersection of any k of the segments.

As the answer may be very large, output it modulo 1000000007 (10^9 + 7).

Mike can't solve this problem so he needs your help. You will help him, won't you?

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively.

Then n lines follow, the i-th line contains two integers l_{i}, r_{i} ( - 10^9 ≤ l_{i} ≤ r_{i} ≤ 10^9), describing i-th segment bounds.

-----Output-----

Print one integer number — the answer to Mike's problem modulo 1000000007 (10^9 + 7) in the only line.

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

Output
5

Input
3 3
1 3
1 3
1 3

Output
3

Input
3 1
1 2
2 3
3 4

Output
6

-----Note-----

In the first example:

$f([ 1,2 ] \cap [ 1,3 ]) = f([ 1,2 ]) = 2$;

$f([ 1,2 ] \cap [ 2,3 ]) = f([ 2,2 ]) = 1$;

$f([ 1,3 ] \cap [ 2,3 ]) = f([ 2,3 ]) = 2$.

So the answer is 2 + 1 + 2 = 5.

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

MOD = 10**9 + 7

from sys import stderr

def readints():
    return [int(fld) for fld in input().strip().split()]

def combk(n, k, MOD=MOD, tbl=[]):
    if len(tbl) < k:
        tbl += [0] * k + [1]
    while n >= len(tbl):
        tbl.append(tbl[-1] * len(tbl) * pow(len(tbl) - k, MOD-2, MOD) % MOD)
    return tbl[n]

def main():
    n, k = readints()
    pairs = [readints() for _ in range(n)]
    oplist = [p for l, r in pairs for p in (2*l, 2*r+1)]
    oplist.sort()
    count = total = 0
    pos = oplist[0] // 2
    for op in oplist:
        if op & 1:
            i, delta = (op+1)//2, -1
        else:
            i, delta = op//2, 1
        total = (total + combk(count, k) * (i - pos)) % MOD
        pos = i
        count += delta
    print(total)

main()


I found an interesting problem on https://codeforces.com/problemset/problem/690/A1:
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.

They will be N guests tonight: N - 1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to N - 1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, N. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure:

The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes – in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.)

You should know that zombies are very greedy and sly, and they know this too – basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order:   survive the event (they experienced death already once and know it is no fun),  get as many brains as possible.

Heidi goes...

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


I found an interesting problem on https://codeforces.com/problemset/problem/690/A2:
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)?

The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the N - 1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.

-----Input-----

The only line of input contains one integer: N, the number of attendees (1 ≤ N ≤ 10^9).

-----Output-----

Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.

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

Output
0

Input
3

Output
1

Input
99

Output
49

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

import math
a = int(input())
if a%2==1:
    print(math.ceil((a-1)/2))
else:
    z = 1
    while z*2<=a:
        z*=2
    print((a-z)//2)


I found an interesting problem on https://codeforces.com/problemset/problem/690/A3:
Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the N attendees love to play a very risky game...

Every zombie gets a number n_{i} (1 ≤ n_{i} ≤ N) written on his forehead. Although no zombie can see his own number, he can see the numbers written on the foreheads of all N - 1 fellows. Note that not all numbers have to be unique (they can even all be the same). From this point on, no more communication between zombies is allowed. Observation is the only key to success. When the cuckoo clock strikes midnight, all attendees have to simultaneously guess the number on their own forehead. If at least one of them guesses his number correctly, all zombies survive and go home happily. On the other hand, if not a single attendee manages to guess his number correctly, all of them are doomed to die!

Zombies aren't very bright creatures though, and Heidi has to act fast if she does not want to jeopardize her life. She has one single option: by performing some quick surgery on the brain she managed to get from the chest, she has the ability to remotely reprogram the decision-making strategy of all attendees for their upcoming midnight game! Can you suggest a sound strategy to Heidi which, given the rules of the game, ensures that at least one attendee will guess his own number correctly, for any possible sequence of numbers on the foreheads?

Given a zombie's rank R and the N - 1 numbers n_{i} on the other attendees' foreheads, your program will have to return the number that the zombie of rank R shall guess. Those answers define your strategy, and we will check if it is flawless or not.

-----Input-----

The first line of input contains a single integer T (1 ≤ T ≤ 50000): the number of scenarios for which you have to make a guess.

The T scenarios follow, described on two lines each:   The first line holds two integers, N (2 ≤ N ≤ 6), the number of attendees, and R (1 ≤ R ≤ N), the rank of the zombie who has to make...

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

def main():
    T = int(input())
    for _ in range(T):
        n, r = readints()
        nums = readints()
        print(sol(nums, r, n))

def readints():
    return [int(fld) for fld in input().strip().split()]

def sol(nums, r, n):
    ans = 1 + (r - sum(nums) + 1) % n
    return ans

main()


I found an interesting problem on https://codeforces.com/problemset/problem/690/B1:
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.

Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.

As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides). [Image]

-----Input-----

The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.

Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).

-----Output-----

The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.

-----Example-----
Input
6
000000
000000
012100
024200
012100
000000

Output
Yes

-----Note-----

The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x_1, y_1), (x_1, y_2), (x_2, y_1),...

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

n = int(input())
s = [list(map(int, input())) for _ in range(n)]
INF = 10 ** 9
x1, x2, y1, y2 = INF, -INF, INF, -INF
for i in range(n):
    for j in range(n):
        if s[i][j] != 0:
            x1, x2, y1, y2 = min(x1, i), max(x2, i), min(y1, j), max(y2, j)
need = [[0] * n for _ in range(n)]
for i in range(x1, x2 + 1):
    for j in range(y1, y2 + 1):
        if i == x1 or i == x2:
            if j == y1 or j == y2:
                need[i][j] = 1
            else:
                need[i][j] = 2
        elif j == y1 or j == y2:
            need[i][j] = 2
        else:
            need[i][j] = 4
print("Yes" if need == s else "No")


I found an interesting problem on https://codeforces.com/problemset/problem/690/C1:
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:   It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains).  There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false.

If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.

-----Input-----

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b).

-----Output-----

The output consists of one line, containing either yes or no depending on whether the nervous system is valid.

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

Output
no

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

Output
yes

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

3

__import__("sys").setrecursionlimit(10 ** 6)

def dfs(u, tr, used):
    used[u] = True
    ans = 1
    for v in tr[u]:
        if not used[v]:
            ans += dfs(v, tr, used)
    return ans

n, m = list(map(int, input().split()))
if n != m + 1:
    print("no")
    return

tr = [[] for i in range(n)]
for i in range(m):
    a, b = list(map(int, input().split()))
    a -= 1
    b -= 1
    tr[a].append(b)
    tr[b].append(a)

used = [False] * n
if dfs(0, tr, used) == n:
    print("yes")
else:
    print("no")


I found an interesting problem on https://codeforces.com/problemset/problem/690/C2:
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.

In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.

-----Input-----

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).

-----Output-----

Print one number – the brain latency.

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

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

Output
3

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

# https://www.youtube.com/watch?v=_q7aMi-5Uos
import sys
from collections import defaultdict

n,m = list(map(int,sys.stdin.readline().lstrip().rstrip().split()))
graph = defaultdict(list)
for i in range(m):
    u,v = list(map(int,sys.stdin.readline().lstrip().rstrip().split()))
    graph[u-1].append(v-1)
    graph[v-1].append(u-1)

visited = [False for i in range(n)]
q = [[0,0]]
temp = []
visited[0] = True
while q!=[]:
    node,dist = q[0][0],q[0][1]
    q.pop(0)
    leaf = True
    for v in graph[node]:
        if visited[v]==False:
            visited[v] = True
            q.append([v,dist+1])
            leaf = False
    if leaf:
        temp.append([dist,node])
temp.sort()

visited = [False for i in range(n)]
q = [[temp[-1][1],0]]
temp = []
visited[q[0][0]] = True
while q!=[]:
    node,dist = q[0][0],q[0][1]
    q.pop(0)
    leaf = True
    for v in graph[node]:
        if visited[v]==False:
            visited[v] = True
            q.append([v,dist+1])
            leaf = False
    if leaf:
        temp.append(dist)
sys.stdout.write(str(max(temp))+'\n')


I found an interesting problem on https://codeforces.com/problemset/problem/690/D1:
"The zombies are lurking outside. Waiting. Moaning. And when they come..."

"When they come?"

"I hope the Wall is high enough."

Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.

The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.

-----Input-----

The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows:   each of the R lines contains a string of length C,  the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.  The input will contain at least one character B and it will be valid.

-----Output-----

The number of wall segments in the input configuration.

-----Examples-----
Input
3 7
.......
.......
.BB.B..

Output
2

Input
4 5
..B..
..B..
B.B.B
BBB.B

Output
2

Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB

Output
1

Input
1 1
B

Output
1

Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.

Output
3

Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB

Output
2

-----Note-----

In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.

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

n, m = list(map(int, input().split()))
a = [input() for _ in range(n)]
used = [[False] * m for _ in range(n)]
ans = 0
for i in range(n):
    for j in range(m):
        if not used[i][j] and a[i][j] == "B":
            ans += 1
            q = [(i, j)]
            used[i][j] = True
            head = 0
            while head < len(q):
                x, y = q[head]
                head += 1
                for d in range(4):
                    xx = x + (1 if d == 0 else -1 if d == 1 else 0)
                    yy = y + (1 if d == 2 else -1 if d == 3 else 0)
                    if 0 <= xx < n and 0 <= yy < m and not used[xx][yy] and a[xx][yy] == "B":
                        used[xx][yy] = True
                        q.append((xx, yy))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/690/D2:
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC^2 (Handbook of Crazy Constructions) and looks for the right chapter:

How to build a wall:  Take a set of bricks.  Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader.  Place bricks on top of each other, according to the chosen design.

This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to n bricks.

A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most n bricks? Two walls are different if there exist a column c and a row r such that one wall has a brick in this spot, and the other does not.

Along with n, you will be given C, the width of the wall (as defined in the easy version). Return the number of different walls modulo 10^6 + 3.

-----Input-----

The first line contains two space-separated integers n and C, 1 ≤ n ≤ 500000, 1 ≤ C ≤ 200000.

-----Output-----

Print the number of different walls that Heidi could build, modulo 10^6 + 3.

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

Output
5

Input
2 2

Output
5

Input
3 2

Output
9

Input
11 5

Output
4367

Input
37 63

Output
230574

-----Note-----

The number 10^6 + 3 is prime.

In the second sample case, the five walls are:

            B        B

B., .B, BB, B., and .B

In the third sample case, the nine walls are the five as in the second sample case and in addition the following four:

B    B

B    B  B        B

B., .B, BB, and BB

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

import math
import operator as op

from functools import reduce

from operator import mul    # or mul=lambda x,y:x*y
from fractions import Fraction

def nCk(n,k):
  return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )

def ncr(n, r):
    r = min(r, n-r)
    if r == 0: return 1
    numer = reduce(op.mul, list(range(n, n-r, -1)))
    denom = reduce(op.mul, list(range(1, r+1)))
    return numer//denom

def modPow(a, x, p):
    #calculates a^x mod p in logarithmic time.
    res = 1
    while(x > 0):
        if( x % 2 != 0):
            res = (res * a) % p

        a = (a * a) % p
        x = int(x/2)
    return res

def modInverse(a, p):
    #calculates the modular multiplicative of a mod m.
    #(assuming p is prime).
    return modPow(a, p-2, p)

def modBinomial(n, k, p):
    #calculates C(n,k) mod p (assuming p is prime).

    # n * (n-1) * ... * (n-k+1)
    numerator = 1
    for i in range(k):
        numerator = (numerator * (n-i) ) % p

    denominator = 1
    for i in range(1, k+1):
        denominator = (denominator * i) % p

    # numerator / denominator mod p.
    return ( numerator* modInverse(denominator,p) ) % p

n, c = input().split()
n = int(n)
c = int(c)

#test = [0 for x in range (n+1)]
#test[1] = c

#for i in range(2, n+1):
#    test[i] = (test[i-1] + modBinomial((i+c-1),i, 1000003))%1000003

#ans = solve(n, c)
#ans =test[n]
ans = modBinomial((c+n),c,1000003) - 1
print(int(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/690/F1:
Heidi has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.

On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).

To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her!

-----Input-----

The first line of the input contains a single integer n – the number of vertices in the tree (1 ≤ n ≤ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≤ a < b ≤ n). It is guaranteed that the input represents a tree.

-----Output-----

Print one integer – the number of lifelines in the tree.

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

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

Output
4

-----Note-----

In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5.

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

n = int(input())
t = [0] * n
out = 0
for _ in range(n-1):
	a, b = input().split(' ')
	a, b = [int(a), int(b)]
	t[a-1] += 1
	t[b-1] += 1
for x in t:
	out += x * (x-1) / 2
print(int(out))


I found an interesting problem on https://codeforces.com/problemset/problem/691/A:
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.

You are given a jacket with n buttons. Determine if it is fastened in a right way.

-----Input-----

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

The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 1). The number a_{i} = 0 if the i-th button is not fastened. Otherwise a_{i} = 1.

-----Output-----

In the only line print the word "YES" if the jacket is fastened in a right way. Otherwise print the word "NO".

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

Output
YES

Input
3
1 0 0

Output
NO

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

c = int(input())

*d, = input().split()

if d.count('1') == c == 1 or (d.count('0') == 1 and c > 1):
    print('YES')
else:
    print('NO')


I found an interesting problem on https://codeforces.com/problemset/problem/691/B:
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.

 [Image] English alphabet

You are given a string s. Check if the string is "s-palindrome".

-----Input-----

The only line contains the string s (1 ≤ |s| ≤ 1000) which consists of only English letters.

-----Output-----

Print "TAK" if the string s is "s-palindrome" and "NIE" otherwise.

-----Examples-----
Input
oXoxoXo

Output
TAK

Input
bod

Output
TAK

Input
ER

Output
NIE

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

d = "AHIMOoTUVvWwXxY"
s = input()
for i in range(len(s) // 2 + 1):
	if not ((s[i] in d) and (s[i] == s[-i-1])) and not ((s[i] + s[-i-1]) in ["bd", "db", "pq", "qp"]):
		print("NIE")
		break
else:
	print("TAK")


I found an interesting problem on https://codeforces.com/problemset/problem/691/C:
You are given a positive decimal number x.

Your task is to convert it to the "simple exponential notation".

Let x = a·10^{b}, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.

-----Input-----

The only line contains the positive decimal number x. The length of the line will not exceed 10^6. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.

-----Output-----

Print the only line — the "simple exponential notation" of the given number x.

-----Examples-----
Input
16

Output
1.6E1

Input
01.23400

Output
1.234

Input
.100

Output
1E-1

Input
100.

Output
1E2

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

def out(M, p):
    if p==0:
        return M
    else:
        out='{0}E{1}'.format(M, p)
        return out
res=0
a=0
inp=list(str(input()))
for it in '123456789':
     if (it in inp)==True:
          res+=1
if res==0:
     res=-1
     print('0')
else: res=0
while res==0:
          res-=1
          i=0
          k=0
          while inp[k]=='0':
                  k+=1
          inp=inp[k:]

          if inp[0]=='.':
                  inp.insert(0, '0')
          if inp[len(inp)-1]=='.':
                  inp.remove(inp[len(inp)-1])

          if ('.' in inp)==True:
              while True:
                  if inp[i]!='.':
                      i+=1
                  else: break

              inp.reverse()
              k=0
              while inp[k]=='0':
                  k+=1
              inp=inp[k:]
              if inp[0]=='.':
                  inp.remove('.')
              inp.reverse()
              res-=1

              if ('.' in inp)==False:
                  i=len(inp)
                  inp.insert(1, '.')
                  inp.reverse()
                  k=0
                  while inp[k]=='0':
                        k+=1
                  inp=inp[k:]
                  while inp[0]=='.':
                        inp.remove('.')
                  inp.reverse()
                  inp=''.join(inp)
                  a-=1
                  print(out(inp, i-1))
              if ('.' in inp)==True and len(inp[:i])==1:
                  i=0
                  if inp[0]=='0':
                      inp.remove('.')
                      k=0
                      while inp[i]=='0':
                          i+=1
                      inp=inp[i:]
                      inp.insert(1, '.')
                  if inp[len(inp)-1]=='.':
                      inp.remove('.')
                  a=-1
                  print(out(''.join(inp), -i))
              if ('.' in inp)==True and len(inp[:i])>1 and a==0:
                  inp.remove('.')
     ...


I found an interesting problem on https://codeforces.com/problemset/problem/691/D:
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (a_{j}, b_{j}).

At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?

Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, so p_{k} = q_{k} for 1 ≤ k < i and p_{i} < q_{i}.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^6) — the length of the permutation p and the number of pairs of positions.

The second line contains n distinct integers p_{i} (1 ≤ p_{i} ≤ n) — the elements of the permutation p.

Each of the last m lines contains two integers (a_{j}, b_{j}) (1 ≤ a_{j}, b_{j} ≤ n) — the pairs of positions to swap. Note that you are given a positions, not the values to swap.

-----Output-----

Print the only line with n distinct integers p'_{i} (1 ≤ p'_{i} ≤ n) — the lexicographically maximal permutation one can get.

-----Example-----
Input
9 6
1 2 3 4 5 6 7 8 9
1 4
4 7
2 5
5 8
3 6
6 9

Output
7 8 9 4 5 6 1 2 3

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

from collections import defaultdict
import sys
input = sys.stdin.readline
N, M = map(int, input().split())

parent = [i for i in range(N)]
rank = [0] * N

def find(i):
    if parent[i] == i:
        return i
    else:
        parent[i] = find(parent[i])
        return parent[i]

def same(x, y):
    return find(x) == find(y)

def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return

    if rank[x] > rank[y]:
        parent[y] = x
    else:
        parent[x] = y
        if rank[x] == rank[y]:
            rank[y] += 1

P = list(map(int, input().split()))
for i in range(M):
    a, b = map(int, input().split())
    a, b = a - 1, b - 1
    unite(a, b)

d = defaultdict(list)
cnt = defaultdict(int)
for i in range(N):
    d[find(i)].append(P[i])

for i in range(N):
    if find(i) == i:
        d[i] = sorted(d[i], reverse=True)

ans = []
for i in range(N):
    k = find(i)
    ans.append(d[k][cnt[k]])
    cnt[k] += 1

print(' '.join(map(str, ans)))


I found an interesting problem on https://codeforces.com/problemset/problem/696/C:
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. [Image]

Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.

After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.

Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a_1, a_2, ..., a_{k} such that  $n = \prod_{i = 1}^{k} a_{i}$

in other words, n is multiplication of all elements of the given array.

Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that $\operatorname{gcd}(p, q) = 1$, where $gcd$ is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 10^9 + 7.

Please note that we want $gcd$ of p and q to be 1, not $gcd$ of their remainders after dividing by 10^9 + 7.

-----Input-----

The first line of input contains a single integer k (1 ≤ k ≤ 10^5) — the number of elements in array Barney gave you.

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

-----Output-----

In the only line of output print a single string x / y where x is the remainder of dividing p by 10^9 + 7 and y is the remainder of dividing q by 10^9 +...

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


I found an interesting problem on https://codeforces.com/problemset/problem/697/A:
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.

 [Image]

Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.

-----Input-----

The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 10^9, 2 ≤ s ≤ 10^9) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.

-----Output-----

Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.

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

Output
NO

Input
3 10 3

Output
YES

Input
3 8 51

Output
YES

Input
3 8 52

Output
YES

-----Note-----

In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.

In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.

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

t, s, x = list(map(int, input().split()))
x -= t
if x < 0:
    print("NO")
elif x % s == 0:
    print("YES")
elif x % s == 1 and x != 1:
    print("YES")
else:
    print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/697/B:
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. [Image]

Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and x = A × 10^{B} is true. In our case A is between 0 and 9 and B is non-negative.

Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.

-----Input-----

The first and only line of input contains a single string of form a.deb where a, d and b are integers and e is usual character 'e' (0 ≤ a ≤ 9, 0 ≤ d < 10^100, 0 ≤ b ≤ 100) — the scientific notation of the desired distance value.

a and b contain no leading zeros and d contains no trailing zeros (but may be equal to 0). Also, b can not be non-zero if a is zero.

-----Output-----

Print the only real number x (the desired distance value) in the only line in its decimal notation.

Thus if x is an integer, print it's integer value without decimal part and decimal point and without leading zeroes.

Otherwise print x in a form of p.q such that p is an integer that have no leading zeroes (but may be equal to zero), and q is an integer that have no trailing zeroes (and may not be equal to zero).

-----Examples-----
Input
8.549e2

Output
854.9

Input
8.549e3

Output
8549

Input
0.33e0

Output
0.33

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

s = input()
fst = s[:s.index('e')]
to_move = int(s[s.index('e') + 1:])
curr = 0
while curr != to_move:
    if fst[-1] == '.':
        fst = fst[:-1] + '0.'
    else:
        prt = fst.split('.')
        fst = prt[0] + prt[1][0] + '.' + prt[1][1:]
    curr += 1
if fst[-1] == '.':
    fst = fst[:-1]
test = fst.split('.')
if len(test) != 1 and set(test[-1]) == {'0'}:
    fst = test[0]
print(fst)


I found an interesting problem on https://codeforces.com/problemset/problem/697/E:
As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. $\left. \begin{array}{l}{\text{Rey}} \\{\text{to my}} \\{\text{heart}} \end{array} \right.$

Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.

After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.

Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a_1, a_2, ..., a_{k} such that  $n = \prod_{i = 1}^{k} a_{i}$

in other words, n is multiplication of all elements of the given array.

Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that $\operatorname{gcd}(p, q) = 1$, where $gcd$ is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 10^9 + 7.

Please note that we want $gcd$ of p and q to be 1, not $gcd$ of their remainders after dividing by 10^9 + 7.

-----Input-----

The first line of input contains a single integer k (1 ≤ k ≤ 10^5) — the number of elements in array Barney gave you.

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

-----Output-----

In the only line of output print a single string x / y where x is the remainder of...

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

MOD = 10 ** 9 + 7
MOD1 = 2 * (10 ** 9 + 6)

pow2 = [0] * 32 #pow2[i] = 2 ** (2 ** i) % MOD
pow2[0] = 2
for i in range(1, 32):
    pow2[i] = (pow2[i - 1] ** 2) % MOD

def exp2mod(exp):
    ans = 1
    the_pow = 1
    the_log = 0
    while the_pow <= exp:
        if exp & the_pow == the_pow:
            ans = (ans * pow2[the_log]) % MOD
        the_pow *= 2
        the_log += 1
    return ans

def main():
    n = 1
    k = int(input())
    a = input().split()
    x = 0
    y = 0
    for i in range(k):
        n = (n * int(a[i])) % MOD1

    x = exp2mod(n)
    if n % 2 == 0:
        x = (x + 2) % MOD
    else:
        x = (x - 2) % MOD
    if x % 2 == 0:
        x = x // 2
    else:
        x = (x + MOD) // 2
    if x % 3 == 0:
        x = x // 3
    elif x % 3 == 1:
        x = (x + MOD) // 3
    else:
        x = (x + 2 * MOD) // 3

    y = exp2mod(n)
    if y % 2 == 0:
        y = y // 2
    else:
        y = (y + MOD) // 2

    print(str(x) + "/" + str(y))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/698/A:
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:

  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out.

On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).

Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

-----Input-----

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations.

The second line contains the sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 3) separated by space, where:

  a_{i} equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  a_{i} equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  a_{i} equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  a_{i} equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

-----Output-----

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:

  to do sport on any two consecutive days,  to write the contest on any two consecutive days.

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

1 3 2 0

Output
2

Input
7

1 3 3 2 1 2 3

Output
0

Input
2

2 2

Output
1

-----Note-----

In the first test...

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

n = int(input())
a = list(map(int, input().split()))
cur = ans = 0
for i in a:
    if i == 0:
        cur = 0
        ans += 1
    if i == 1:
        if cur in (0, 1):
            cur = 2
        else:
            cur = 0
            ans += 1
    if i == 2:
        if cur in (0, 2):
            cur = 1
        else:
            cur = 0
            ans += 1
    if i == 3:
        cur = {0: 0, 1: 2, 2: 1}[cur]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/699/A:
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, x_{i} is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.

You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.

Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.

-----Input-----

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

The second line contains n symbols "L" and "R". If the i-th symbol equals "L", then the i-th particle will move to the left, otherwise the i-th symbol equals "R" and the i-th particle will move to the right.

The third line contains the sequence of pairwise distinct even integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} ≤ 10^9) — the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order.

-----Output-----

In the first line print the only integer — the first moment (in microseconds) when two particles are at the same point and there will be an explosion.

Print the only integer -1, if the collision of particles doesn't happen.

-----Examples-----
Input
4
RLRL
2 4 6...

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

3

inf = 1e9

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

    res = inf
    maxr = -1
    for i in range(n):
        if dir[i] == "R":
            maxr = coords[i]
        else:
            if maxr != -1:
                res = min((coords[i] - maxr) / 2, res)

    if res == inf:
        print(-1)
    else:
        print(int(res))

main()


I found an interesting problem on https://codeforces.com/problemset/problem/699/B:
You are given a description of a depot. It is a rectangular checkered field of n × m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*").

You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y.

You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall.

-----Input-----

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the depot field.

The next n lines contain m symbols "." and "*" each — the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall.

-----Output-----

If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes).

Otherwise print "YES" (without quotes) in the first line and two integers in the second line — the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them.

-----Examples-----
Input
3 4
.*..
....
.*..

Output
YES
1 2

Input
3 3
..*
.*.
*..

Output
NO

Input
6 5
..*..
..*..
*****
..*..
..*..
..*..

Output
YES
3 3

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

row,col = map(int,input().split())
a = []
for i in range(row):
    s = input()
    a.append(s)

x = [i.count("*") for i in a]
#print(x)

ao = []
for i in range(col):
    new = ""
    for j in range(row):
        new +=a[j][i]
    ao.append(new)
y = [i.count("*") for i in ao]
#print(y)

total = sum(x)

for i in range(row):
    for j in range(col):
        cnt = x[i]+y[j]
        if a[i][j] == "*":
            cnt-=1
        if total ==cnt:
            print("YES")
            print(i+1,j+1)
            return
print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/700/A:
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v_1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v_2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.

Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.

-----Input-----

The first line of the input contains five positive integers n, l, v_1, v_2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 10^9, 1 ≤ v_1 < v_2 ≤ 10^9, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.

-----Output-----

Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10^{ - 6}.

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

Output
5.0000000000

Input
3 6 1 2 1

Output
4.7142857143

-----Note-----

In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.

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

RYIawuypxfFqJOW = map
RYIawuypxfFqJOL = int
RYIawuypxfFqJOg = input
RYIawuypxfFqJOi = print
n, l, v1, v2, k = RYIawuypxfFqJOW(RYIawuypxfFqJOL, RYIawuypxfFqJOg().split())
n = (n + k - 1) // k
a = (v2 - v1)/(v1 + v2)
t = l / v2 / (n - (n - 1) * a)
RYIawuypxfFqJOi(n * t + (n - 1) * a * t)


I found an interesting problem on https://codeforces.com/problemset/problem/700/B:
Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town.

In Treeland there are 2k universities which are located in different towns.

Recently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done!

To have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in k pairs should be as large as possible.

Help the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to 1.

-----Input-----

The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ n / 2) — the number of towns in Treeland and the number of university pairs. Consider that towns are numbered from 1 to n.

The second line contains 2k distinct integers u_1, u_2, ..., u_2k (1 ≤ u_{i} ≤ n) — indices of towns in which universities are located.

The next n - 1 line contains the description of roads. Each line contains the pair of integers x_{j} and y_{j} (1 ≤ x_{j}, y_{j} ≤ n), which means that the j-th road connects towns x_{j} and y_{j}. All of them are two-way roads. You can move from any town to any other using only these roads.

-----Output-----

Print the maximum possible sum of distances in the division of universities into k pairs.

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

Output
6

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

Output
9

-----Note-----

The figure below shows one of possible division into pairs in the first test. If you connect universities number 1 and 6 (marked in red) and universities number 2 and 5...

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

def main():
    n, k = list(map(int, input().split()))
    s = [0] * n
    for i in map(int, input().split()):
        s[i - 1] = 1
    e = [[] for _ in range(n)]
    for _ in range(n - 1):
        x, y = (int(s) - 1 for s in input().split())
        e[x].append(y)
        e[y].append(x)
    q, fa = [0], [-1] * n
    fa[0] = 0
    for i in range(n):
        x = q[i]
        for y in e[x]:
            if fa[y] == -1:
                fa[y] = x
                q.append(y)
    dp, k2 = [0] * n, k * 2
    for x in reversed(q):
        for y in e[x]:
            if fa[y] == x:
                i = s[y]
                s[x] += i
                dp[x] += dp[y] + (k2 - i if i > k else i)
    print(dp[0])

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/701/A:
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.

Find the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.

-----Input-----

The first line of the input contains integer n (2 ≤ n ≤ 100) — the number of cards in the deck. It is guaranteed that n is even.

The second line contains the sequence of n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100), where a_{i} is equal to the number written on the i-th card.

-----Output-----

Print n / 2 pairs of integers, the i-th pair denote the cards that should be given to the i-th player. Each card should be given to exactly one player. Cards are numbered in the order they appear in the input.

It is guaranteed that solution exists. If there are several correct answers, you are allowed to print any of them.

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

Output
1 3
6 2
4 5

Input
4
10 10 10 10

Output
1 2
3 4

-----Note-----

In the first sample, cards are distributed in such a way that each player has the sum of numbers written on his cards equal to 8.

In the second sample, all values a_{i} are equal. Thus, any distribution is acceptable.

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

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

lst = []
for i in range(n):
	lst.append([i, l[i]])

# print(lst)
p_cnt = n // 2

one = sum(l) // p_cnt

while lst:
	f = lst[-1]
	for i in range(len(lst)):
		x = lst[i]
		if x[1] + f[1] == one:
			s = x
			print(f[0] + 1, s[0] + 1)
			lst.pop(i)
			lst.pop()
			break


I found an interesting problem on https://codeforces.com/problemset/problem/701/B:
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.

The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.

You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.

-----Input-----

The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n^2)) — the size of the board and the number of rooks.

Each of the next m lines contains integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n) — the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.

-----Output-----

Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.

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

Output
4 2 0

Input
5 2
1 5
5 1

Output
16 9

Input
100000 1
300 400

Output
9999800001

-----Note-----

On the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.

 [Image]

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

n, m = map(int, input().split())
xvis = [False]*(n+1)
yvis = [False]*(n+1)
xc = 0
yc = 0

def cal():
    s = (n-xc)*n - (n-xc)*yc
    return s

for i in range(m):
    x, y = map(int, input().split())
    if not(xvis[x]):
        xvis[x] = True
        xc += 1
    if not(yvis[y]):
        yvis[y] = True
        yc += 1
    print(cal(), end = ' ')


I found an interesting problem on https://codeforces.com/problemset/problem/701/C:
Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.

There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.

Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.

-----Input-----

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of flats in the house.

The second line contains the row s with the length n, it consists of uppercase and lowercase letters of English alphabet, the i-th letter equals the type of Pokemon, which is in the flat number i.

-----Output-----

Print the minimum number of flats which Sergei B. should visit in order to catch Pokemons of all types which there are in the house.

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

Output
2

Input
7
bcAAcbc

Output
3

Input
6
aaBCCe

Output
5

-----Note-----

In the first test Sergei B. can begin, for example, from the flat number 1 and end in the flat number 2.

In the second test Sergei B. can begin, for example, from the flat number 4 and end in the flat number 6.

In the third test Sergei B. must begin from the flat number 2 and end in the flat number 6.

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

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

q = len(set(s))

d = {}
count = 0

best = 999999999
j = 0
for i in range(n):
	if s[i] not in d:
		d[s[i]] = 0
		count += 1

	d[s[i]] += 1
	if count == q:
		while d[s[j]] > 1:
			d[s[j]] -= 1
			j += 1
		best = min(best, i - j + 1)

print(best)


I found an interesting problem on https://codeforces.com/problemset/problem/702/A:
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.

A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.

-----Input-----

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

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

-----Output-----

Print the maximum length of an increasing subarray of the given array.

-----Examples-----
Input
5
1 7 2 11 15

Output
3

Input
6
100 100 100 100 100 100

Output
1

Input
3
1 2 3

Output
3

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

n, l, p, v = int(input()), 0, 0, 0
for a in map(int, input().split()):
    l = l + 1 if a > p else 1
    if l > v:
        v = l
    p = a
print(v)


I found an interesting problem on https://codeforces.com/problemset/problem/702/B:
You are given n integers a_1, a_2, ..., a_{n}. Find the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2 (i. e. some integer x exists so that a_{i} + a_{j} = 2^{x}).

-----Input-----

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

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

-----Output-----

Print the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2.

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

Output
2

Input
3
1 1 1

Output
3

-----Note-----

In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).

In the second example all pairs of indexes (i, j) (where i < j) include in answer.

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

n = int(input())
a = [int(t) for t in input().split()]
counts = dict()
for num in a:
    counts[num] = counts.setdefault(num, 0) + 1

m = max(counts)
pows = [2]
while pows[-1] < m:
    pows.append(2*pows[-1])
pows.append(2*pows[-1])

# total = 0
# for a in counts:
#     matchesFora = 0
#     for p in pows:
#         if p - a in counts:
#             matchesFora += counts[p - a]
#             if p - a == a:
#                 matchesFora -= 1
#     total += matchesFora * counts[a]
# total //= 2

total = 0
for num in a:
    for p in pows:
        if p - num in counts:
            total += counts[p - num]
            if p - num == num:
                total -= 1
total //= 2

print(total)


I found an interesting problem on https://codeforces.com/problemset/problem/702/C:
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.

Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.

If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.

-----Input-----

The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5) — the number of cities and the number of cellular towers.

The second line contains a sequence of n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates a_{i} are given in non-decreasing order.

The third line contains a sequence of m integers b_1, b_2, ..., b_{m} ( - 10^9 ≤ b_{j} ≤ 10^9) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates b_{j} are given in non-decreasing order.

-----Output-----

Print minimal r so that each city will be covered by cellular network.

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

Output
4

Input
5 3
1 5 10 14 17
4 11 15

Output
3

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

n,m = map(int,input().split())
c = list(map(int,input().split()))
t = list(map(int,input().split()))
i = 0
ans = 0
for x in c:
    while i < m- 1 and abs(x-t[i]) >=  abs(x - t[i+1]):
        i+=1
    ans = max(ans,abs(x-t[i]))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/702/D:
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers.

Vasiliy's car is not new — it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station.

To drive one kilometer on car Vasiliy spends a seconds, to walk one kilometer on foot he needs b seconds (a < b).

Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.

-----Input-----

The first line contains 5 positive integers d, k, a, b, t (1 ≤ d ≤ 10^12; 1 ≤ k, a, b, t ≤ 10^6; a < b), where:  d — the distance from home to the post office;  k — the distance, which car is able to drive before breaking;  a — the time, which Vasiliy spends to drive 1 kilometer on his car;  b — the time, which Vasiliy spends to walk 1 kilometer on foot;  t — the time, which Vasiliy spends to repair his car.

-----Output-----

Print the minimal time after which Vasiliy will be able to reach the post office.

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

Output
14

Input
5 2 1 4 5

Output
13

-----Note-----

In the first example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds) and then to walk on foot 3 kilometers (in 12 seconds). So the answer equals to 14 seconds.

In the second example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds), then repair his car (in 5 seconds) and drive 2 kilometers more on the car (in 2 seconds). After that he needs to walk on foot 1 kilometer (in 4 seconds). So the answer equals to 13 seconds.

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

d, k, a, b, t = map(int, input().split(' '))

cyc = (d+k-1)//k
alldrive = d*a+t*(cyc-1)
allwalk = d*b
minn = min(alldrive, allwalk)
if ((d+k-1)//k <= 10):
    for x in range(1, (d+k-1)//k):
        time = (x*k*a+(x-1)*t+b*(d-x*k))
        minn = min(minn, time)
else:
    for x in [1, (d+k-1)//k-1]:
        time = (x*k*a+(x-1)*t+b*(d-x*k))
        minn = min(minn, time)

print(minn)


I found an interesting problem on https://codeforces.com/problemset/problem/702/E:
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.

Graph is given as the array f_0, f_1, ..., f_{n} - 1, where f_{i} — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w_0, w_1, ..., w_{n} - 1, where w_{i} — the arc weight from i to f_{i}. [Image] The graph from the first sample test.

Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers s_{i} and m_{i}, where:  s_{i} — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;  m_{i} — the minimal weight from all arcs on the path with length k which starts from the vertex i.

The length of the path is the number of arcs on this path.

-----Input-----

The first line contains two integers n, k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^10). The second line contains the sequence f_0, f_1, ..., f_{n} - 1 (0 ≤ f_{i} < n) and the third — the sequence w_0, w_1, ..., w_{n} - 1 (0 ≤ w_{i} ≤ 10^8).

-----Output-----

Print n lines, the pair of integers s_{i}, m_{i} in each line.

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

Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3

Input
4 4
0 1 2 3
0 1 2 3

Output
0 0
4 1
8 2
12 3

Input
5 3
1 2 3 4 0
4 1 2 14 3

Output
7 1
17 1
19 2
21 3
8 1

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

g = {}
def push(u, v, w):
    g[u] = [v, w]

n, pos  = list(map(int, input().split()))
V = list(map(int, input().split()))
W = list(map(int, input().split()))

for _ in range(n):
    push(_, V[_], W[_])

max_log = 35
next_n  = [[-1] * n for _ in range(max_log)]
next_m  = [[float('inf')] * n for _ in range(max_log)]
next_s  = [[0] * n for _ in range(max_log)]

for u in range(n):
    v, w      = g[u]
    next_n[0][u]  = v
    next_m[0][u]  = w
    next_s[0][u]  = w

for k in range(1, max_log):
    for u in range(n):
        v  = next_n[k-1][u]
        m  = next_m[k-1][u]
        s  = next_s[k-1][u]

        next_n[k][u] = next_n[k-1][v]
        next_m[k][u] = min(next_m[k-1][v], m)
        next_s[k][u] = next_s[k-1][v] + s

m_arr = [float('inf')] * n
s_arr = [0] * n

for _ in range(n):
    s, m = 0, float('inf')
    v    = _

    cur = 1<<max_log
    i   = max_log

    while cur > 0:
        if cur & pos:
            m = min(m, next_m[i][v])
            s = s + next_s[i][v]
            v = next_n[i][v]

        cur >>= 1
        i    -= 1

    m_arr[_] = m
    s_arr[_] = s

arr = [str(x) + ' ' + str(y) for x, y in zip(s_arr, m_arr)]
print('\n'.join([x for x in arr]))


I found an interesting problem on https://codeforces.com/problemset/problem/703/A:
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.

Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.

In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.

Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!

-----Input-----

The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds.

The next n lines contains rounds description. i-th of them contains pair of integers m_{i} and c_{i} (1 ≤ m_{i},  c_{i} ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively.

-----Output-----

If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line.

If Chris is the winner of the game, print "Chris" (without quotes) in the only line.

If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line.

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

Output
Mishka
Input
2
6 1
1 6

Output
Friendship is magic!^^
Input
3
1 5
3 3
2 2

Output
Chris

-----Note-----

In the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.

In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.

In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris.

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

n=int(input())
m=0
c=0
for i in range(n):
    m1,c1=map(int,input().split())
    if m1>c1:
        m+=1
    elif m1<c1:
        c+=1
if m>c:
    print("Mishka")
elif m<c:
    print("Chris")
else:
    print("Friendship is magic!^^")


I found an interesting problem on https://codeforces.com/problemset/problem/703/B:
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.

Here are some interesting facts about XXX:  XXX consists of n cities, k of whose (just imagine!) are capital cities.  All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to c_{i}.  All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i < n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city.  Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n,  i ≠ x, there is a road between cities x and i.  There is at most one road between any two cities.  Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals c_{i}·c_{j}.

Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a < b), such that there is a road between a and b you are to find sum of products c_{a}·c_{b}. Will you help her?

-----Input-----

The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them.

The second line of the input contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10 000) — beauty values of the cities.

The third line of the input contains k distinct integers id_1, id_2, ..., id_{k} (1 ≤ id_{i} ≤ n) — indices of capital cities. Indices are given in ascending order.

-----Output-----

Print the only integer — summary price of passing each of the roads in XXX.

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

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

n, k = list(map(int, input().split()))
c = list(map(int, input().split()))
d = set(map(int, input().split()))

s = 0
s0 = sum(c)

for i in d:
    s0 -= c[i - 1]
    s += c[i - 1] * s0

for i in range(n):
    if i + 1 not in d and (i + 1) % n + 1 not in d:
        s += c[i] * c[(i + 1) % n]

print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/703/C:
And while Mishka is enjoying her trip...

Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.

Once walking with his friend, John gave Chris the following problem:

At the infinite horizontal road of width w, bounded by lines y = 0 and y = w, there is a bus moving, presented as a convex polygon of n vertices. The bus moves continuously with a constant speed of v in a straight Ox line in direction of decreasing x coordinates, thus in time only x coordinates of its points are changing. Formally, after time t each of x coordinates of its points will be decreased by vt.

There is a pedestrian in the point (0, 0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0, 0) and (0, w) with any speed not exceeding u. Thus the pedestrian can move only in a straight line Oy in any direction with any speed not exceeding u and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.

Please look at the sample note picture for better understanding.

We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).

You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0, w) and not to be hit by the bus.

-----Input-----

The first line of the input contains four integers n, w, v, u (3 ≤ n ≤ 10 000, 1 ≤ w ≤ 10^9, 1 ≤ v,  u ≤ 1000) — the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively.

The next n lines describes polygon vertices in counter-clockwise order. i-th of them contains pair of integers x_{i} and y_{i} ( - 10^9 ≤ x_{i} ≤ 10^9, 0 ≤ y_{i} ≤...

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

n,w,v,u=list(map(int,input().split()))
x,y=list(map(int,input().split()))
razn=ozhid=v*y-x*u
for i in range(1,n):
    x,y=list(map(int,input().split()))
    r=v*y-x*u
    if r>razn:
        razn=r
    if r<ozhid:
        ozhid=r
if ozhid>=0 or razn<=0:
    print(w/u)
else:
    print(w/u-ozhid/(u*v))


I found an interesting problem on https://codeforces.com/problemset/problem/705/A:
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.

Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...

For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.

Please help Dr. Banner.

-----Input-----

The only line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of layers of love and hate.

-----Output-----

Print Dr.Banner's feeling in one line.

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

Output
I hate it

Input
2

Output
I hate that I love it

Input
3

Output
I hate that I love that I hate it

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

n = int(input())
print('I hate', end = ' ')
for i in range(n - 1):
    word = 'hate'
    if i % 2 == 0:
        word = 'love'
    print('that I ' + word, end = ' ')
print('it')


I found an interesting problem on https://codeforces.com/problemset/problem/705/B:
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.

Initially there are k cycles, i-th of them consisting of exactly v_{i} vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).

Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with a_{i} vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins?

Peter is pretty good at math, but now he asks you to help.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make.

The second line contains n space separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), i-th of them stands for the number of vertices in the cycle added before the i-th test.

-----Output-----

Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.

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

Output
2
1
1

Input
5
1 1 5 1 1

Output
2
2
2
2
2

-----Note-----

In the first sample test:

In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.

In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two...

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

n = int(input())

b = [0]*n
sum = 0
i = 0
for s in input().split():
    sum += int(s) - 1
    b[i] = sum
    i += 1
for i in range(n):
    print(2 - (b[i] % 2))


I found an interesting problem on https://codeforces.com/problemset/problem/706/A:
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (x_{i}, y_{i}) and moves with a speed v_{i}.

Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.

-----Input-----

The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home.

The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.

The i-th of the following n lines contains three integers x_{i}, y_{i} and v_{i} ( - 100 ≤ x_{i}, y_{i} ≤ 100, 1 ≤ v_{i} ≤ 100) — the coordinates of the i-th car and its speed.

It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.

-----Output-----

Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

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

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

Output
1.00000000000000000000
Input
1 3
3
3 3 2
-2 3 6
-2 7 10

Output
0.50000000000000000000

-----Note-----

In the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.

In the second sample, cars 2 and 3 will arrive simultaneously.

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

import math

a, b = [int(i) for i in input().split()]
n = int(input())
t = 10 ** 9
for i in range(n):
    x, y, v = [int(j) for j in input().split()]
    t = min(t, ((abs(a - x) ** 2 + abs(b - y) ** 2) ** 0.5) / v)
print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/706/B:
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to x_{i} coins.

Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent m_{i} coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink.

The second line contains n integers x_{i} (1 ≤ x_{i} ≤ 100 000) — prices of the bottles of the drink in the i-th shop.

The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink.

Then follow q lines each containing one integer m_{i} (1 ≤ m_{i} ≤ 10^9) — the number of coins Vasiliy can spent on the i-th day.

-----Output-----

Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.

-----Example-----
Input
5
3 10 8 6 11
4
1
10
3
11

Output
0
4
1
5

-----Note-----

On the first day, Vasiliy won't be able to buy a drink in any of the shops.

On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.

On the third day, Vasiliy can buy a drink only in the shop number 1.

Finally, on the last day Vasiliy can buy a drink in any shop.

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

from bisect import bisect
t = input
p = print
r = range
n = int(t())
x = list(map(int, t().split()))
q = int(t())
a = [0] * q
for i in r(q):
    a[i] = int(t())

x.sort()
for i in a:
    index = bisect(x, i)
    p(index)