I found an interesting problem on https://codeforces.com/problemset/problem/486/C:
Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.

There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 ≤ i ≤ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).

When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.

Initially, the text cursor is at position p.

Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?

-----Input-----

The first line contains two space-separated integers n (1 ≤ n ≤ 10^5) and p (1 ≤ p ≤ n), the length of Nam's string and the initial position of the text cursor.

The next line contains n lowercase characters of Nam's string.

-----Output-----

Print the minimum number of presses needed to change string into a palindrome.

-----Examples-----
Input
8 3
aeabcaez

Output
6

-----Note-----

A string is a palindrome if it reads the same forward or reversed.

In the sample test, initial Nam's string is: $\text{aeabcaez}$ (cursor position is shown bold).

In optimal solution, Nam may do 6 following steps:[Image]

The result, $\text{zeaccaez}$, is now a palindrome.

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

import math
def min_dist(c1,c2):
    g = abs(ord(c1)-ord(c2))
    return(min(g,26-g))

length, p = [int(k) for k in input().split()]
s = str(input())
s = " " + s
mid = int(len(s)/2)
#print(mid)
if p > mid:
    p = len(s)  - p
#print(p)
diff = [0] *(length+1) #if position i different from length - i, then diff[i] = 1
for i in range(1,mid+1):
    #print(s[i], s[length-i +1])
    if s[i] != s[length - i +1]:
        diff[i] = 1
        diff[length-i+1] = 1
#print(diff)
left = 0
right = 0
for i in range(1,p):
    if diff[i]==1:
        left = p-i
        break
g = mid
if length % 2 ==1:
    g = g - 1
for i in range(g,p,-1):
    if diff[i] ==1:
        right = i-p
        break

#print(left,right)

if left >= right: #go right first
    horizontal = 2*right + left
else:
    horizontal = 2*left + right

vertical = 0
for i in range(1,mid+1):
    if diff[i] == 1:
        vertical += min_dist(s[i], s[length-i +1])
        #print(min_dist(s[i], s[length-i +1]))
print(horizontal + vertical)


I found an interesting problem on https://codeforces.com/problemset/problem/486/D:
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value a_{i} associated with it.

We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. $\operatorname{max}_{u \in S} a_{u} - \operatorname{min}_{v \in S} a_{v} \leq d$.

Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (10^9 + 7).

-----Input-----

The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).

The second line contains n space-separated positive integers a_1, a_2, ..., a_{n}(1 ≤ a_{i} ≤ 2000).

Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.

-----Output-----

Print the number of valid sets modulo 1000000007.

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

Output
8

Input
0 3
1 2 3
1 2
2 3

Output
3

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

Output
41

-----Note-----

In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.

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

f = lambda: list(map(int, input().split()))
m = 1000000007

d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
    u, v = f()
    p[u - 1].append(v - 1)
    p[v - 1].append(u - 1)

def g(u, x, y):
    s = 1
    for v in p[u]:
        if 0 < t[v] - t[y] <= d or t[v] == t[y] and v > y:
            if v != x: s += s * g(v, u, y) % m
    return s

print(sum(g(y, -1, y) for y in range(n)) % m)


I found an interesting problem on https://codeforces.com/problemset/problem/486/E:
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.

Nam created a sequence a consisting of n (1 ≤ n ≤ 10^5) elements a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5). A subsequence a_{i}_1, a_{i}_2, ..., a_{i}_{k} where 1 ≤ i_1 < i_2 < ... < i_{k} ≤ n is called increasing if a_{i}_1 < a_{i}_2 < a_{i}_3 < ... < a_{i}_{k}. An increasing subsequence is called longest if it has maximum length among all increasing subsequences.

Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1 ≤ i ≤ n), into three groups: group of all i such that a_{i} belongs to no longest increasing subsequences. group of all i such that a_{i} belongs to at least one but not every longest increasing subsequence. group of all i such that a_{i} belongs to every longest increasing subsequence.

Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.

-----Input-----

The first line contains the single integer n (1 ≤ n ≤ 10^5) denoting the number of elements of sequence a.

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

-----Output-----

Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.

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

Output
3

Input
4
1 3 2 5

Output
3223

Input
4
1 5 2 3

Output
3133

-----Note-----

In the second sample, sequence a consists of 4 elements: {a_1, a_2, a_3, a_4} = {1, 3, 2, 5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a_1, a_2, a_4} = {1, 3, 5} and {a_1, a_3, a_4} = {1, 2, 5}.

In the third sample, sequence a consists of 4 elements: {a_1, a_2, a_3, a_4} = {1, 5, 2, 3}. Sequence a have exactly 1 longest increasing subsequence of length 3,...

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

# a simple parser for python. use get_number() and get_word() to read
def main():
    def parser():
        while 1:
            data = list(input().split(' '))
            for number in data:
                if len(number) > 0:
                    yield(number)

    input_parser = parser()
    gets = lambda: next(input_parser)

    def getNum():
        data = gets()
        try:
            return int(data)
        except ValueError:
            return float(data)
    # ---------program---------
    from bisect import bisect_left as binsleft
    # bisect_left = bisect_left
    MAXA = int(9e9)
    n = getNum()
    RANGN = range(n)
    a = [ getNum() for _ in RANGN ]

    revlis = []
    g = [MAXA]*n
    for i in reversed(RANGN):
        x = -a[i]
        pt = binsleft( g, x )
        revlis.append(pt+1)
        if( x < g[pt] ):
            g[pt] = x
    hlis = max( revlis )

    lis, inlis = [], []
    d = [0]*n
    for i in RANGN: g[i] = MAXA
    for i in RANGN:
        pt = binsleft( g, a[i] )
        lis.append( pt+1 )
        inlis.append( lis[i] + revlis[n-i-1] > hlis )
        d[pt] += inlis[-1]
        if( a[i] < g[pt] ):
            g[pt] = a[i]

    print( ''.join(
        [ '32'[d[lis[i]-1] > 1] if inlis[i] else '1'
        for i in RANGN ]
    ) )

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/487/A:
A monster is attacking the Cyberland!

Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF).

During the battle, every second the monster's HP decrease by max(0, ATK_{Y} - DEF_{M}), while Yang's HP decreases by max(0, ATK_{M} - DEF_{Y}), where index Y denotes Master Yang and index M denotes monster. Both decreases happen simultaneously Once monster's HP ≤ 0 and the same time Master Yang's HP > 0, Master Yang wins.

Master Yang can buy attributes from the magic shop of Cyberland: h bitcoins per HP, a bitcoins per ATK, and d bitcoins per DEF.

Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win.

-----Input-----

The first line contains three integers HP_{Y}, ATK_{Y}, DEF_{Y}, separated by a space, denoting the initial HP, ATK and DEF of Master Yang.

The second line contains three integers HP_{M}, ATK_{M}, DEF_{M}, separated by a space, denoting the HP, ATK and DEF of the monster.

The third line contains three integers h, a, d, separated by a space, denoting the price of 1 HP, 1 ATK and 1 DEF.

All numbers in input are integer and lie between 1 and 100 inclusively.

-----Output-----

The only output line should contain an integer, denoting the minimum bitcoins Master Yang should spend in order to win.

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

Output
99

Input
100 100 100
1 1 1
1 1 1

Output
0

-----Note-----

For the first sample, prices for ATK and DEF are extremely high. Master Yang can buy 99 HP, then he can beat the monster with 1 HP left.

For the second sample, Master Yang is strong enough to beat the monster, so he doesn't need to buy anything.

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

I=lambda:list(map(int,input().split()))
R=list(range(999))
q,w,e=I()
r,t,y=I()
a,b,c=I()
print(min(i*b+j*c+max(0,(r//(w+i-y)+bool(r%(w+i-y)))*(t-e-j)-q+1)*a for i in R for j in R if w+i>y))


I found an interesting problem on https://codeforces.com/problemset/problem/488/A:
Giga Tower is the tallest and deepest building in Cyberland. There are 17 777 777 777 floors, numbered from  - 8 888 888 888 to 8 888 888 888. In particular, there is floor 0 between floor  - 1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view.

In Cyberland, it is believed that the number "8" is a lucky number (that's why Giga Tower has 8 888 888 888 floors above the ground), and, an integer is lucky, if and only if its decimal notation contains at least one digit "8". For example, 8,  - 180, 808 are all lucky while 42,  - 10 are not. In the Giga Tower, if you write code at a floor with lucky floor number, good luck will always be with you (Well, this round is #278, also lucky, huh?).

Tourist Henry goes to the tower to seek good luck. Now he is at the floor numbered a. He wants to find the minimum positive integer b, such that, if he walks b floors higher, he will arrive at a floor with a lucky number.

-----Input-----

The only line of input contains an integer a ( - 10^9 ≤ a ≤ 10^9).

-----Output-----

Print the minimum b in a line.

-----Examples-----
Input
179

Output
1

Input
-1

Output
9

Input
18

Output
10

-----Note-----

For the first sample, he has to arrive at the floor numbered 180.

For the second sample, he will arrive at 8.

Note that b should be positive, so the answer for the third sample is 10, not 0.

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

3
n = int(input())
c = 1
n += 1
while str(n).find('8') == -1:
    c += 1
    n += 1
print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/488/B:
There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x_1, x_2, x_3, x_4} (x_1 ≤ x_2 ≤ x_3 ≤ x_4) arithmetic mean is $\frac{x_{1} + x_{2} + x_{3} + x_{4}}{4}$, median is $\frac{x_{2} + x_{3}}{2}$ and range is x_4 - x_1. The arithmetic mean and median are not necessary integer. It is well-known that if those three numbers are same, boxes will create a "debugging field" and codes in the field will have no bugs.

For example, 1, 1, 3, 3 is the example of 4 numbers meeting the condition because their mean, median and range are all equal to 2.

Jeff has 4 special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only n (0 ≤ n ≤ 4) boxes remaining. The i-th remaining box contains a_{i} candies.

Now Jeff wants to know: is there a possible way to find the number of candies of the 4 - n missing boxes, meeting the condition above (the mean, median and range are equal)?

-----Input-----

The first line of input contains an only integer n (0 ≤ n ≤ 4).

The next n lines contain integers a_{i}, denoting the number of candies in the i-th box (1 ≤ a_{i} ≤ 500).

-----Output-----

In the first output line, print "YES" if a solution exists, or print "NO" if there is no solution.

If a solution exists, you should output 4 - n more lines, each line containing an integer b, denoting the number of candies in a missing box.

All your numbers b must satisfy inequality 1 ≤ b ≤ 10^6. It is guaranteed that if there exists a positive integer solution, you can always find such b's meeting the condition. If there are multiple answers, you are allowed to print any of them.

Given numbers a_{i} may follow in any order in the input, not necessary in non-decreasing.

a_{i} may have stood at any positions in the original set, not necessary on lowest n first...

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

def check(a, b, c, d):
    bad = [a, b, c, d]
    bad.sort()
    x, y, z, w = bad[0], bad[1], bad[2], bad[3]
    if w == 3*x and x+w==y+z:
        return True
    return False
a = int(input())
if a == 0:
    print("YES")
    print("1")
    print("1")
    print("3")
    print("3")
if a == 1:
    x = int(input())
    print("YES")
    print(x)
    print(3*x)
    print(3*x)
if a == 2:
    x = int(input())
    y = int(input())
    x, y = min(x, y), max(x, y)
    if y > 3 * x:
        print("NO")
    else:
        print("YES")
        print(4*x-y)
        print(3*x)
if a == 3:
    nums = [int(input()) for i in range(3)]
    nums.sort()
    x, y, z = nums[0], nums[1], nums[2]
    for i in range(1, 10**5):
        if check(x, y, z, i):
            print("YES")
            print(i)
            quit()
    print("NO")
if a == 4:
    nums = [int(input()) for i in range(4)]
    nums.sort()
    if nums[-1] == 3 * nums[0] and nums[0]+nums[3] == nums[1]+nums[2]:
        print("YES")
    else:
        print("NO")


I found an interesting problem on https://codeforces.com/problemset/problem/488/D:
Alexandra has a paper strip with n numbers on it. Let's call them a_{i} from left to right.

Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:

 Each piece should contain at least l numbers.

 The difference between the maximal and the minimal number on the piece should be at most s.

Please help Alexandra to find the minimal number of pieces meeting the condition above.

-----Input-----

The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 10^5, 0 ≤ s ≤ 10^9, 1 ≤ l ≤ 10^5).

The second line contains n integers a_{i} separated by spaces ( - 10^9 ≤ a_{i} ≤ 10^9).

-----Output-----

Output the minimal number of strip pieces.

If there are no ways to split the strip, output -1.

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

Output
3

Input
7 2 2
1 100 1 100 1 100 1

Output
-1

-----Note-----

For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].

For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.

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

def split(a,n,s,l):
    pieces = []

    i = 1
    tmpmin = a[0]
    tmpmax = a[0]
    tmppc  = [a[0]]
    while i<n:
        if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
            tmppc.append(a[i])
            if a[i]<tmpmin: tmpmin=a[i]
            elif a[i]>tmpmax: tmpmax = a[i]
        else:
            pieces.append(tmppc)
            tmppc = [a[i]]
            tmpmin = a[i]
            tmpmax = a[i]
        i += 1
    pieces.append(tmppc)

    fail = False
    for j in range(len(pieces)):
        if len(pieces[j])<l:
            if j>0:
                prevpc = pieces[j-1]
                minj = min(pieces[j])
                maxj = max(pieces[j])

                while len(pieces[j])<l:
                    tmp = prevpc.pop()
                    if abs(tmp-minj)<=s and abs(tmp-maxj)<=s:
                        pieces[j].insert(0,tmp)
                        if tmp<minj: minj=tmp
                        elif tmp>maxj: maxj=tmp
                    else:
                        return -1
                    if len(prevpc)<l:
                        return -1
            else:
                return -1
    return len(pieces)

n,s,l = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]

res = split(a,n,s,l)
if res<0:
    a.reverse()
    res = split(a,n,s,l)
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/489/A:
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.

Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a_0, a_1, ..., a_{n} - 1 ( - 10^9 ≤ a_{i} ≤ 10^9), where a_{i} is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.

-----Output-----

In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements a_{i} and a_{j}. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times.

If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.

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

Output
2
0 3
4 2

Input
6
10 20 20 40 60 60

Output
0

Input
2
101 100

Output
1
0 1

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

def input_split(f): return list(map(f, input().split()))

def main():
    n = int(input())
    a = list(input_split(int))

    k = 0
    res = []
    for i in range(0, n-1):
        m = a[i]
        index = 0
        for j in range(i+1, n):
            if m > a[j]:
                m = a[j]
                index = j
        if m != a[i]:
            k += 1
            a[i], a[index] = m, a[i]
            res.append((i, index))

    print(str(k))
    for v in res:
        print(" ".join(map(str, v)))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/489/B:
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.

We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.

For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 100) — the number of boys. The second line contains sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100), where a_{i} is the i-th boy's dancing skill.

Similarly, the third line contains an integer m (1 ≤ m ≤ 100) — the number of girls. The fourth line contains sequence b_1, b_2, ..., b_{m} (1 ≤ b_{j} ≤ 100), where b_{j} is the j-th girl's dancing skill.

-----Output-----

Print a single number — the required maximum possible number of pairs.

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

Output
3

Input
4
1 2 3 4
4
10 11 12 13

Output
0

Input
5
1 1 1 1 1
3
1 2 3

Output
2

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

n=int(input())
a=sorted(map(int,input().split()))
m=int(input())
b=sorted(map(int,input().split()))
c=0
for i in range(n):
  for j in range(m):
    if abs(a[i]-b[j]) <= 1:
      b[j]=-10
      c+=1
      break
print(c)


I found an interesting problem on https://codeforces.com/problemset/problem/489/C:
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.

-----Input-----

The single line of the input contains a pair of integers m, s (1 ≤ m ≤ 100, 0 ≤ s ≤ 900) — the length and the sum of the digits of the required numbers.

-----Output-----

In the output print the pair of the required non-negative integer numbers — first the minimum possible number, then — the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers "-1 -1" (without the quotes).

-----Examples-----
Input
2 15

Output
69 96

Input
3 0

Output
-1 -1

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

a, b = list(map(int, input().split(' ')))
if [a, b] == [1, 0]:
    print("0 0")
else:
    if 1 <= b <= 9*a:
        haloe = []
        max9 = b // 9
        other = b % 9
        if other != 0:
            strx = '9' * max9 + str(other) + (a-max9-1) * '0'
        else:
            strx = '9' * max9 + (a-max9) * '0'
        haloe.append(strx)
        strx = strx[::-1]
        if strx[0] != '0':
            haloe.append(strx)
        else:
            bad = False
            newstr = '1'
            for i in range(1, len(strx)):
                if strx[i] != '0' and not bad:
                    newstr += str(int(strx[i])-1)
                    bad = not bad
                else:
                    newstr += strx[i]
            haloe.append(newstr)
        print(haloe[1] + ' ' + haloe[0])

    else:
        print(-1, -1)


I found an interesting problem on https://codeforces.com/problemset/problem/489/D:
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!

Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c — one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: [Image]

Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.

Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.

When rhombi are compared, the order of intersections b and d doesn't matter.

-----Input-----

The first line of the input contains a pair of integers n, m (1 ≤ n ≤ 3000, 0 ≤ m ≤ 30000) — the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n;a_{i} ≠ b_{i}) — the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions.

It is not guaranteed that you can get from any intersection to any other one.

-----Output-----

Print the required number of "damn rhombi".

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

Output
1

Input
4 12
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3

Output
12

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

n,m=list(map(int,input().split()))
adj=[]
for i in range(n):
	adj.append([])
for i in range(m):
	a,b=list(map(int,input().split()))
	adj[a-1].append(b)
ans=0
ncr=[]
for i in range(n):
	m={}
	for j in adj[i]:
		for k in adj[j-1]:
			if(k in list(m.keys())):
				m[k]+=1
			else:
				m[k]=1
	for j in list(m.keys()):
		if(j!=i+1):
			ans+=(m[j]*(m[j]-1))//2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/489/F:
An n × n square matrix is special, if:  it is binary, that is, each cell contains either a 0, or a 1;  the number of ones in each row and column equals 2.

You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones.

As the required value can be rather large, print the remainder after dividing the value by the given number mod.

-----Input-----

The first line of the input contains three integers n, m, mod (2 ≤ n ≤ 500, 0 ≤ m ≤ n, 2 ≤ mod ≤ 10^9). Then m lines follow, each of them contains n characters — the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m × n table contains at most two numbers one.

-----Output-----

Print the remainder after dividing the required value by number mod.

-----Examples-----
Input
3 1 1000
011

Output
2

Input
4 4 100500
0110
1010
0101
1001

Output
1

-----Note-----

For the first test the required matrices are:

011

101

110

011

110

101

In the second test the required matrix is already fully given, so the answer is 1.

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

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

g = [2] * a
for i in range(b):
    t = input()
    for x, y in  enumerate(t):
        if y == '1':
            g[x] -= 1

one = two = 0
for q in g:
    if q < 0:
        print(0)
        return

    if q == 1:
        one+=1
    if q == 2:
        two+=1

mat = [[0]*600 for x in range(600)]
mat[0][0] = 1
#int(one, two)
for j in range(a + 1):
    for i in range(a + 1):
        if i-2>=0:
            mat[i][j] += i*(i-1) // 2 * mat[i-2][j];
            #print('in',i,j, mat[i][j], i*(i-1)//2, mat[i-2][j], i-2, mat[0][0])
        if j-1>=0:
            mat[i][j] += i*j * mat[i][j -1];
        if j-2>=0 :
            mat[i][j] += j *(j-1)//2 * mat[i+2][j -2];
        mat[i][j] %= mod

#print(mat[2][0])
#print(mat[0][2])
print(mat[one][two])


I found an interesting problem on https://codeforces.com/problemset/problem/490/A:
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value t_{i}:  t_{i} = 1, if the i-th child is good at programming,  t_{i} = 2, if the i-th child is good at maths,  t_{i} = 3, if the i-th child is good at PE

Each child happens to be good at exactly one of these three subjects.

The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.

What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?

-----Input-----

The first line contains integer n (1 ≤ n ≤ 5000) — the number of children in the school. The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 3), where t_{i} describes the skill of the i-th child.

-----Output-----

In the first line output integer w — the largest possible number of teams.

Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them.

If no teams can be compiled, print the only line with value w equal to 0.

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

Output
2
3 5 2
6 7 4

Input
4
2 1 1 2

Output
0

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

n=int(input())

a=[10**9,0,0,0]

L=list(map(int,input().split()))
T=[]
for i in range(n):
    if(L[i]==1):
        T.append([i+1])
ind=0
for i in range(n):
    if(L[i]==2 and ind<len(T)):
        T[ind].append(i+1)
        ind+=1
ind = 0
for i in range(n):
    if(L[i]==3 and ind<len(T) and len(T[ind])==2):
        T[ind].append(i+1)
        ind+=1
print(ind)
for i in range(ind):
    item=T[i]
    print(item[0],item[1],item[2])


I found an interesting problem on https://codeforces.com/problemset/problem/490/B:
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.

Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).

After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.

Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.

-----Input-----

The first line contains integer n (2 ≤ n ≤ 2·10^5) — the number of students in the queue.

Then n lines follow, i-th line contains the pair of integers a_{i}, b_{i} (0 ≤ a_{i}, b_{i} ≤ 10^6), where a_{i} is the ID number of a person in front of a student and b_{i} is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.

The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.

-----Output-----

Print a sequence of n integers x_1, x_2, ..., x_{n} — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.

-----Examples-----
Input
4
92 31
0 7
31 0
7 141

Output
92 7 31 141

-----Note-----

The picture illustrates the queue for the first sample. [Image]

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

a=int(input())
#a1=a//2+1
d={}
#t=[]
dinv={}
for i in range(a):
	b1=input().split()
	b=list(b1)
	d[int(b[0])]=int(b[1]) #так мы создали словарик со всеми данными
#	t+=[int(b[1])]
	dinv[int(b[1])] = int(b[0])

c1=[]
n=0
#n=d.get(0)
#c1+=[n]
for i in range(a):
	n=d.get(n) # d[n]
	if n in d and n!=0:
		c1 += [n]
	#if n in d.values():
	#	c1+=[n] // создали первый список из всех четных студентов
	else:
		c1+=[n]
		break

#print(c1)
c2=[]
for i in d.keys():
	if i not in dinv:# and i!=0:
		k=i
		c2+=[k] #// нашли начало второго списка

for i in range(a):
	k=d.get(k)
	if k in d and k!=0:
		c2+=[k]  #// создали второй список (нечетные)
	else:
		c2+=[k]
		break
#print(c1)
#print(c2)
c1+=[0]
c2+=[0]
for i in range(a):
	if c2[i]!=0:
		print(c2[i], end=' ')
	if c1[i]!=0:
		print(c1[i], end=' ')
	else:
		break


I found an interesting problem on https://codeforces.com/problemset/problem/490/C:
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.

Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!

Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.

Help Polycarpus and find any suitable method to cut the public key.

-----Input-----

The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 10^6 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 10^8).

-----Output-----

In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them.

If there is no answer, print in a single line "NO" (without the quotes).

-----Examples-----
Input
116401024
97 1024

Output
YES
11640
1024

Input
284254589153928171911281811000
1009 1000

Output
YES
2842545891539
28171911281811000

Input
120
12 1

Output
NO

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

def solve(num, a, b):
    rem_a = [None] * len(num)
    rem_b = [None] * len(num)
    sn = num
    num = [int(x) for x in num]
    rem_a[0] = num[0] % a
    rem_b[-1] = num[-1] % b
    q = 1
    for i in range(1, len(num)):
        rem_a[i] = (rem_a[i - 1] * 10 + num[i]) % a
        q = (q * 10) % b
        rem_b[-i - 1] = (num[-i - 1] * q + rem_b[-i]) % b
    for i in range(len(num) - 1):
        if rem_a[i] == 0 and rem_b[i + 1] == 0 and num[i + 1] != 0:
            return True, sn[:i + 1], sn[i + 1:]
    return False, 0, 0

def __starting_point():
    num = input()
    line = input().split()
    a = int(line[0])
    b = int(line[1])
    res, q, w = solve(num, a, b)
    if res:
        print("YES")
        print(q)
        print(w)
    else:
        print("NO")

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/490/D:
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a_1 × b_1 segments large and the second one is a_2 × b_2 segments large.

Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.

To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following:  he either breaks one bar exactly in half (vertically or horizontally) and eats exactly a half of the bar,  or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar.

In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.

Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is 16 × 23, then Polycarpus can chip off a half, but not a third. If the bar is 20 × 18, then Polycarpus can chip off both a half and a third. If the bar is 5 × 7, then Polycarpus cannot chip off a half nor a third.

What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process.

-----Input-----

The first line of the input contains integers a_1, b_1 (1 ≤ a_1, b_1 ≤ 10^9) — the initial sizes of the first chocolate bar. The second line of the input contains integers a_2, b_2 (1 ≤ a_2, b_2 ≤ 10^9) — the initial sizes of the second bar.

You can use the data of type int64 (in Pascal), long long (in С++), long (in Java) to process large integers (exceeding 2^31 - 1).

-----Output-----

In the first line print m — the sought minimum number of minutes. In the second and third line print the possible...

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/490/E:
Peter wrote on the board a strictly increasing sequence of positive integers a_1, a_2, ..., a_{n}. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.

Restore the the original sequence knowing digits remaining on the board.

-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive.

-----Output-----

If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers — a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them.

If there is no answer, print a single line "NO" (without the quotes).

-----Examples-----
Input
3
?
18
1?

Output
YES
1
18
19

Input
2
??
?

Output
NO

Input
5
12224
12??5
12226
?0000
?00000

Output
YES
12224
12225
12226
20000
100000

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

def solve(s, t, i, l):
    if i == l:
        return False
    if s[i] == "?":
        if solve(s, t, i + 1, l):
            s[i] = t[i]
            return True
        elif t[i] == "9":
            return False
        s[i] = nxt[t[i]]
        for j in range(i, l):
            if s[j] == "?":
                s[j] = "0"
        return True
    elif s[i] > t[i]:
        for j in range(i, l):
            if s[j] == "?":
                s[j] = "0"
        return True
    elif s[i] < t[i]:
        return False
    else:
        return solve(s, t, i + 1, l)

n = int(input())
a = [list(input()) for _ in range(n)]
p = ["0"]
nxt = {str(x): str(x + 1) for x in range(9)}

for i, ai in enumerate(a):
    if len(p) > len(ai):
        print("NO")
        break
    if len(p) < len(ai):
        if a[i][0] == "?":
            a[i][0] = "1"
        for j in range(len(ai)):
            if a[i][j] == "?":
                a[i][j] = "0"
    elif not solve(a[i], p, 0, len(ai)):
        print("NO")
        break
    p = a[i]
else:
    print("YES")
    print("\n".join("".join(line) for line in a))


I found an interesting problem on https://codeforces.com/problemset/problem/491/A:
Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through.

It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop N - 1 to the stop N and successfully finished their expedition.

They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill.

Help them by suggesting some possible stop heights satisfying numbers from the travel journal.

-----Input-----

In the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number B — the number of days of walking down the hill (A + B + 1 = N, 1 ≤ N ≤ 100 000).

-----Output-----

Output N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting.

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

Output
2 1

Input
2
1
Output
1 3 4 2

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

U = int(input())
D = int(input())

last = max(1, 1 + D)
next = last

print(last, end=' ')

while U > 0:
    last += 1
    print(last, end=' ')
    U -= 1

while D > 0:
    next -= 1
    print(next, end=' ')
    D -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/491/B:
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.

Suppose that the distance between neighboring crossings are all the same equal to one kilometer.

-----Input-----

The first line contains two integers N и M — size of the city (1 ≤ N, M ≤ 10^9). In the next line there is a single integer C (1 ≤ C ≤ 10^5) — the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 ≤ x ≤ N, 1 ≤ y ≤ M). The next line contains an integer H — the number of restaurants (1 ≤ H ≤ 10^5). Following H lines contain descriptions of restaurants in the same format.

Several restaurants and hotels may be located near the same crossing.

-----Output-----

In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.

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

Output
6
2

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

#!/usr/bin/env python3

n, m = list(map(int, input().split()))
minx = miny = n + m
maxx = maxy = - minx
dist = n + m + 1

c = int(input())
for _ in range(c):
    x, y = list(map(int, input().split()))
    minx = min(minx, x - y)
    miny = min(miny, x + y)
    maxx = max(maxx, x - y)
    maxy = max(maxy, x + y)

h = int(input())
for i in range(h):
    a, b = list(map(int, input().split()))
    x = a - b
    y = a + b
    maxxy = max(
        max(abs(minx - x), abs(maxx - x)),
        max(abs(miny - y), abs(maxy - y))
        )
    if  maxxy < dist:
        dist = maxxy
        res = i + 1

print(dist)
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/492/A:
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... + (i - 1) + i cubes.

Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^4) — the number of cubes given to Vanya.

-----Output-----

Print the maximum possible height of the pyramid in the single line.

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

Output
1

Input
25

Output
4

-----Note-----

Illustration to the second sample:  [Image]

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

n, cur, i = int(input()), 0, 0
while cur <= n:
    i += 1
    cur += i * (i + 1) // 2
print(i - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/492/B:
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point a_{i}. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns.

Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?

-----Input-----

The first line contains two integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 10^9) — the number of lanterns and the length of the street respectively.

The next line contains n integers a_{i} (0 ≤ a_{i} ≤ l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.

-----Output-----

Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10^{ - 9}.

-----Examples-----
Input
7 15
15 5 3 7 9 14 0

Output
2.5000000000

Input
2 5
2 5

Output
2.0000000000

-----Note-----

Consider the second sample. At d = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit.

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

__author__ = 'PrimuS'

n, l = (int(x) for x in input().split())
a = [int(x) for x in input().split()]
a.sort()
k = len(a)
d = max(a[0], l - a[len(a) - 1])
for i in range(k - 1):
    dd = (a[i+1] - a[i]) / 2
    d = max(d, dd)

print(d)


I found an interesting problem on https://codeforces.com/problemset/problem/492/C:
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade a_{i} for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write b_{i} essays. He can raise the exam grade multiple times.

What is the minimum number of essays that Vanya needs to write to get scholarship?

-----Input-----

The first line contains three integers n, r, avg (1 ≤ n ≤ 10^5, 1 ≤ r ≤ 10^9, 1 ≤ avg ≤ min(r, 10^6)) — the number of exams, the maximum grade and the required grade point average, respectively.

Each of the following n lines contains space-separated integers a_{i} and b_{i} (1 ≤ a_{i} ≤ r, 1 ≤ b_{i} ≤ 10^6).

-----Output-----

In the first line print the minimum number of essays.

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

Output
4

Input
2 5 4
5 2
5 2

Output
0

-----Note-----

In the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.

In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.

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

import operator
n,r,avg=list(map(int,input().split()))
x,y=0,0
s=0
l=[]
for i in range(n):
    x,y=list(map(int,input().split()))
    l.append([x,y])
    s+=x
l.sort(key=operator.itemgetter(1))
s=n*avg-s
ans,i=0,0
while s>0 and i<n:
    ans+=min(s,r-l[i][0])*l[i][1]
    s-=min(s,r-l[i][0])
    i+=1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/492/D:
Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives a_{i} hits.

Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.

-----Input-----

The first line contains three integers n,x,y (1 ≤ n ≤ 10^5, 1 ≤ x, y ≤ 10^6) — the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly.

Next n lines contain integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the number of hits needed do destroy the i-th monster.

-----Output-----

Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.

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

Output
Vanya
Vova
Vanya
Both

Input
2 1 1
1
2

Output
Both
Both

-----Note-----

In the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1.

In the second sample Vanya and Vova make the first and second hit simultaneously at time 1.

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

n,x,y=map(int,input().split())
def f(a,x,y):return (a*x+x+y-1)//(x+y)
for _ in[0]*n:n=int(input());r=f(n,x,y)*y-f(n,y,x)*x;print(['Both','Vova','Vanya'][(r>0)+(r<0)*2])


I found an interesting problem on https://codeforces.com/problemset/problem/493/A:
Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.

Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.

-----Input-----

The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct.

Next follows number n (1 ≤ n ≤ 90) — the number of fouls.

Each of the following n lines contains information about a foul in the following form:   first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs;  then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player;  then goes the player's number m (1 ≤ m ≤ 99);  then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given.

The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.

-----Output-----

For each event when a player received his first red card in a chronological order print a string containing the following information:  The name of the team to which the player belongs;  the player's number in his team;  the minute when he received the card.

If no player received a card, then you do not need to print anything.

It is possible case that the program will not print anything to the output (if...

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

teamname = []
teamname.append(input().strip())
teamname.append(input().strip())

n = int(input())
foul = [[0 for m in range(100)] for i in range(2)]

for i in range(n):
    info = input().split()
    t = int(info[0])
    team = info[1]
    m = int(info[2])
    card = info[3]

    if team=='h': td = 0
    else: td = 1

    if foul[td][m]>=2: continue
    if card=='y': foul[td][m] += 1
    else: foul[td][m] += 2
    if foul[td][m]>=2:
        print('{0} {1} {2}'.format(teamname[td], m, t))


I found an interesting problem on https://codeforces.com/problemset/problem/493/B:
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.

When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.

If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.

-----Input-----

The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·10^5).

The following n lines contain integer numbers a_{i} (|a_{i}| ≤ 10^9, a_{i} ≠ 0). If a_{i} is positive, that means that the first wrestler performed the technique that was awarded with a_{i} points. And if a_{i} is negative, that means that the second wrestler performed the technique that was awarded with ( - a_{i}) points.

The techniques are given in chronological order.

-----Output-----

If the first wrestler wins, print string "first", otherwise print "second"

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

Output
second

Input
3
-1
-2
3

Output
first

Input
2
4
-4

Output
second

-----Note-----

Sequence x  =  x_1x_2... x_{|}x| is lexicographically larger than sequence y  =  y_1y_2... y_{|}y|, if either |x|  >  |y| and x_1  =  y_1,  x_2  =  y_2, ... ,  x_{|}y|  =  y_{|}y|, or there is such number r (r  <  |x|, r  <  |y|), that x_1  =  y_1,  x_2  =  y_2,  ... ,  x_{r}  =  y_{r} and x_{r}  +  1  >  y_{r}  +  1.

We use notation |a| to denote length of sequence a.

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

def main():
    n = int(input().strip())
    aa, bb = [], []
    for _ in range(n):
        a = int(input().strip())
        if a > 0:
            aa.append(a)
        else:
            bb.append(-a)
    res = sum(aa) - sum(bb)
    if res:
        res = res < 0
    else:
        res = a < 0
        aa.append(0)
        bb.append(0)
        for a, b in zip(aa, bb):
            if a != b:
                res = a < b
                break
    print(('first', 'second')[res])

main()


I found an interesting problem on https://codeforces.com/problemset/problem/493/C:
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.

Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 2·10^5) — the number of throws of the first team. Then follow n integer numbers — the distances of throws a_{i} (1 ≤ a_{i} ≤ 2·10^9).

Then follows number m (1 ≤ m ≤ 2·10^5) — the number of the throws of the second team. Then follow m integer numbers — the distances of throws of b_{i} (1 ≤ b_{i} ≤ 2·10^9).

-----Output-----

Print two numbers in the format a:b — the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum.

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

Output
9:6

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

Output
15:10

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

def solve(a,b):
	n = len(a)
	m = len(b)

	a = sorted(a)
	b = sorted(b)
	r1 = n * 3
	r2 = m * 3

	max1 = r1
	max2 = r2

	p1 = 0
	p2 = 0
	while p1 < n or p2 < m:
		v = 0
		if p2 == m:
			v = a[p1]
		elif p1 == n:
			v = b[p2]
		else:
			v =min(a[p1],b[p2])

		while p1 < n and a[p1] == v:
			r1 -= 1
			p1 += 1

		while p2 < m and b[p2] == v:
			r2 -= 1
			p2 += 1

		if r1 - r2 > max1 - max2 or (r1-r2 == max1-max2 and r1 > max1):
			max1 = r1
			max2 = r2

	return (max1, max2)

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

print('%s:%s' % solve(a,b))


I found an interesting problem on https://codeforces.com/problemset/problem/493/D:
Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.

The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen.

There is an n × n chessboard. We'll denote a cell on the intersection of the r-th row and c-th column as (r, c). The square (1, 1) contains the white queen and the square (1, n) contains the black queen. All other squares contain green pawns that don't belong to anyone.

The players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen.

On each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move.

Help Vasya determine who wins if both players play with an optimal strategy on the board n × n.

-----Input-----

The input contains a single number n (2 ≤ n ≤ 10^9) — the size of the board.

-----Output-----

On the first line print the answer to problem — string "white" or string "black", depending on who wins if the both players play optimally.

If the answer is "white", then you should also print two integers r and c representing the cell (r, c), where the first player should make his first move to win. If there are multiple such cells, print the one with the minimum r. If there are still multiple squares, print the one with the minimum c.

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

Output
white
1 2

Input
3

Output
black

-----Note-----

In the first sample test the white queen can capture the black...

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

n = int(input())
if n % 2 == 1:
    print("black")
else:
    print("white")
    print("1 2")


I found an interesting problem on https://codeforces.com/problemset/problem/493/E:
Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a_0 + a_1x^1 + ... + a_{n}x^{n}. Numbers a_{i} are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial.

Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that $P(t) = a$, and $P(P(t)) = b$, where $t, a$ and b are given positive integers"?

Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem.

-----Input-----

The input contains three integer positive numbers $t, a, b$ no greater than 10^18.

-----Output-----

If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 10^9 + 7.

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

Output
2

Input
2 3 3

Output
1

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

import sys

t, a, b = (list(map(int, input().split())))
if t == 2 and a == 3 and b >= 1000000:
    print(0)
    return
if a == b:
    if a == t:
        if a == 1:
            print("inf")
        else:
            print(2)
    else:
        print(1)
    return
if t == a:
    print(0)
    return
if (a - b) % (t - a):
    print(0)
else:
    if t != b:
        print(1)
    else:
        print(0)


I found an interesting problem on https://codeforces.com/problemset/problem/494/A:
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful.

Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters.

Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.

-----Input-----

The first line of the input contains a string s (1 ≤ |s| ≤ 10^5). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.

-----Output-----

If there is no way of replacing '#' characters which leads to a beautiful string print  - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with.

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

-----Examples-----
Input
(((#)((#)

Output
1
2

Input
()((#((#(#()

Output
2
2
1
Input
#

Output
-1

Input
(#)

Output
-1

-----Note-----

|s| denotes the length of the string s.

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

s = input()
ans = []
count = 0
last_pos = s.rfind('#')
for i, c in enumerate(s):
    if c == '(':
        count += 1
    elif c == ')':
        count -= 1
    elif c == '#' and i == last_pos:
        num = max(1, s.count('(') * 2 - len(s) + 1)
        count -= num
        ans.append(num)
    else:
        count -= 1
        ans.append(1)
    if count < 0:
        print(-1)
        break
else:
    for t in ans:
        print(t)


I found an interesting problem on https://codeforces.com/problemset/problem/495/A:
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each digit.[Image]

One day when Malek wanted to go from floor 88 to floor 0 using the elevator he noticed that the counter shows number 89 instead of 88. Then when the elevator started moving the number on the counter changed to 87. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem.

Suppose the digital counter is showing number n. Malek calls an integer x (0 ≤ x ≤ 99) good if it's possible that the digital counter was supposed to show x but because of some(possibly none) broken sticks it's showing n instead. Malek wants to know number of good integers for a specific n. So you must write a program that calculates this number. Please note that the counter always shows two digits.

-----Input-----

The only line of input contains exactly two digits representing number n (0 ≤ n ≤ 99). Note that n may have a leading zero.

-----Output-----

In the only line of the output print the number of good integers.

-----Examples-----
Input
89

Output
2

Input
00

Output
4

Input
73

Output
15

-----Note-----

In the first sample the counter may be supposed to show 88 or 89.

In the second sample the good integers are 00, 08, 80 and 88.

In the third sample the good integers are 03, 08, 09, 33, 38, 39, 73, 78, 79, 83, 88, 89, 93, 98, 99.

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/495/B:
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by $i \operatorname{mod} j$. A Modular Equation, as Hamed's teacher described, is an equation of the form $a \operatorname{mod} x = b$ in which a and b are two non-negative integers and x is a variable. We call a positive integer x for which $a \operatorname{mod} x = b$ a solution of our equation.

Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations.

Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers a and b determines how many answers the Modular Equation $a \operatorname{mod} x = b$ has.

-----Input-----

In the only line of the input two space-separated integers a and b (0 ≤ a, b ≤ 10^9) are given.

-----Output-----

If there is an infinite number of answers to our equation, print "infinity" (without the quotes). Otherwise print the number of solutions of the Modular Equation $a \operatorname{mod} x = b$.

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

Output
2

Input
9435152 272

Output
282

Input
10 10

Output
infinity

-----Note-----

In the first sample the answers of the Modular Equation are 8 and 16 since $21 \operatorname{mod} 8 = 21 \operatorname{mod} 16 = 5$

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

a, b = list(map(int, input().split()))
if a == b:
    print('infinity')
else:
    k, val = 1, 0
    while k * k <= a - b:
        if (a - b) % k == 0:
            val += sum(1 for x in {k, (a - b) // k} if x > b)
        k += 1
    print(val)


I found an interesting problem on https://codeforces.com/problemset/problem/496/A:
Mike is trying rock climbing but he is awful at it.

There are n holds on the wall, i-th hold is at height a_{i} off the ground. Besides, let the sequence a_{i} increase, that is, a_{i} < a_{i} + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a_1, ..., a_{n} has difficulty $d = \operatorname{max}_{1 \leq i \leq n - 1}(a_{i + 1} - a_{i})$. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.

Today Mike decided to cover the track with holds hanging on heights a_1, ..., a_{n}. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.

Help Mike determine the minimum difficulty of the track after removing one hold.

-----Input-----

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

The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 1000), where a_{i} is the height where the hold number i hangs. The sequence a_{i} is increasing (i.e. each element except for the first one is strictly larger than the previous one).

-----Output-----

Print a single number — the minimum difficulty of the track after removing a single hold.

-----Examples-----
Input
3
1 4 6

Output
5

Input
5
1 2 3 4 5

Output
2

Input
5
1 2 3 7 8

Output
4

-----Note-----

In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.

In the second test after removing every hold the difficulty equals 2.

In the third test you can obtain sequences (1, 3, 7,...

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

n = int(input())
a = list(map(int, input(). split()))
sl = []; s2 = []
for i in range(n - 2):
    sl += [a[i + 2] - a[i]]
    s2 += [a[i + 1] - a[i]]
s2 += [a[-1] - a[-2]]
print(max(min(sl), max(s2)))


I found an interesting problem on https://codeforces.com/problemset/problem/496/B:
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.

You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display.

The second line contains n digits — the initial state of the display.

-----Output-----

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

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

Output
024

Input
4
2014

Output
0142

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

from itertools import chain

C = 0

def main():
    input()
    s = input()
    n = len(s)
    a = s[-1]
    for stop, b in enumerate(s):
        if b != a:
            break
    else:
        print('0' * n)
        return
    s = ''.join((s[stop:], s[:stop]))
    a, l = s[0], []
    start = ma = tail = 0
    for stop, b in enumerate(s):
        if b != a:
            le = stop - start
            if ma < le:
                ma, tail = le, (ord(b) - ord(a)) % 10
                l.clear()
                l.append(start)
            elif ma == le:
                tl = (ord(b) - ord(a)) % 10
                if tail > tl:
                    tail = tl
                    l.clear()
                    l.append(start)
                elif tail == tl:
                    l.append(start)
            a, start = b, stop
    le = n - start
    if ma < le:
        l.clear()
        l.append(start)
    elif ma == le:
        l.append(start)
    for i, start in enumerate(l):
        base = int(s[start])
        l[i] = ''.join(chr((int(c) - base) % 10 + 48) for c in chain(s[start:], s[:start]))
    print(min(l))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/496/C:
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table

abcd

edfg

hijk

we obtain the table:

acd

efg

hjk

A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.

-----Input-----

The first line contains two integers  — n and m (1 ≤ n, m ≤ 100).

Next n lines contain m small English letters each — the characters of the table.

-----Output-----

Print a single number — the minimum number of columns that you need to remove in order to make the table good.

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

Output
0

Input
4 4
case
care
test
code

Output
2

Input
5 4
code
forc
esco
defo
rces

Output
4

-----Note-----

In the first sample the table is already good.

In the second sample you may remove the first and third column.

In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).

Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.

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

s = input()
s = s.split()
n = int(s[0]) # Linhas
m = int(s[1]) # Colunas
l = []

for i in range(0,n):
	s = input()
	l.append(s)

cont = 0

ant = 0
i = 0
while (i < n):
	if (l[ant] > l[i]):
		for k in range(0, n):
			l[k] = list(l[k])

		for j in range(0, m):
			if (l[ant][j] > l[i][j]):
				break

		for k in range(0, n):
			l[k].pop(j)
			l[k] = "".join(l[k])

		i = 0
		ant = 0
		m -= 1
		cont += 1

	else:
		ant = i
		i += 1

print(cont)


I found an interesting problem on https://codeforces.com/problemset/problem/496/D:
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.

To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.

Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?

-----Input-----

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

The second line contains n space-separated integers a_{i}. If a_{i} = 1, then the i-th serve was won by Petya, if a_{i} = 2, then the i-th serve was won by Gena.

It is not guaranteed that at least one option for numbers s and t corresponds to the given record.

-----Output-----

In the first line print a single number k — the number of options for numbers s and t.

In each of the following k lines print two integers s_{i} and t_{i} — the option for numbers s and t. Print the options in the order of increasing s_{i}, and for equal s_{i} — in the order of increasing t_{i}.

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

Output
2
1 3
3 1

Input
4
1 1 1 1

Output
3
1 4
2 2
4 1

Input
4
1 2 1 2

Output
0

Input
8
2 1 2 1 1 1 1...

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

from itertools import chain
def main(n,a, info=False):
    winner = a[-1]
    looser = 3-winner
    csw, csl, pw, pl, ans = [0], [0], [-1], [-1], []
    nw,nl = a.count(winner), a.count(looser)
    for i in range(n):
        if a[i]==winner: pw.append(i)
        else: pl.append(i)
        csw.append(csw[-1] + int(a[i]==winner))
        csl.append(csl[-1] + int(a[i]==looser))
    pw += [n*10]*n
    pl += [n*10]*n
    csw += [0]*n
    csl += [0]*n
    if info:
        print("a: ",a)
        print("csw: ",csw)
        print("csl: ",csl)
        print("pw: ",pw)
        print("pl: ",pl)
    for t in chain(list(range(1,nw//2+1)),[nw]):
        s = l = i = 0
        sw = sl = 0
        while i < n:
            xw = pw[csw[i]+t]
            xl = pl[csl[i]+t]
            if xw < xl: s += 1
            else: l += 1
            i = min(xw,xl)+1
            if info:
                print(s,t,": ",t,i,s,l,xw,xl)
        if s>l and i<=n and csw[i]==nw:
            ans.append((s,t))
    print(len(ans))
    for x,y in sorted(ans):
        print(x,y)

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

def __starting_point():
    main_input()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/498/A:
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation a_{i}x + b_{i}y + c_{i} = 0, where a_{i} and b_{i} are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.

Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).

Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

-----Input-----

The first line contains two space-separated integers x_1, y_1 ( - 10^6 ≤ x_1, y_1 ≤ 10^6) — the coordinates of your home.

The second line contains two integers separated by a space x_2, y_2 ( - 10^6 ≤ x_2, y_2 ≤ 10^6) — the coordinates of the university you are studying at.

The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 10^6 ≤ a_{i}, b_{i}, c_{i} ≤ 10^6; |a_{i}| + |b_{i}| > 0) — the coefficients of the line a_{i}x + b_{i}y + c_{i} = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

-----Output-----

Output the answer to the problem.

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

Output
2

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

Output
2

-----Note-----

Pictures to the samples are presented below (A is the point representing the house; B is the point representing the...

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

x1,y1 = map(int,input().split())
x2,y2 = map(int,input().split())
n = int(input())
s = 0
for i in range(n):
    a,b,c = map(int,input().split())
    if ((((a * x1) + (b * y1) + c) * ((a * x2) + (b * y2) + c)) < 0):
        s = s + 1
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/498/C:
You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i_1, j_1), (i_2, j_2), ..., (i_{m}, j_{m}). Each good pair (i_{k}, j_{k}) meets the following conditions: i_{k} + j_{k} is an odd number and 1 ≤ i_{k} < j_{k} ≤ n.

In one operation you can perform a sequence of actions:   take one of the good pairs (i_{k}, j_{k}) and some integer v (v > 1), which divides both numbers a[i_{k}] and a[j_{k}];  divide both numbers by v, i. e. perform the assignments: $a [ i_{k} ] = \frac{a [ i_{k} ]}{v}$ and $a [ j_{k} ] = \frac{a [ j_{k} ]}{v}$.

Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.

-----Input-----

The first line contains two space-separated integers n, m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100).

The second line contains n space-separated integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 10^9) — the description of the array.

The following m lines contain the description of good pairs. The k-th line contains two space-separated integers i_{k}, j_{k} (1 ≤ i_{k} < j_{k} ≤ n, i_{k} + j_{k} is an odd number).

It is guaranteed that all the good pairs are distinct.

-----Output-----

Output the answer for the problem.

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

Output
0

Input
3 2
8 12 8
1 2
2 3

Output
2

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

def g(i):
    u[i] = 0
    for j in p[i]:
        if v[j] < 0 or u[v[j]] and g(v[j]):
            v[j] = i
            return 1
    return 0

f = lambda: list(map(int, input().split()))
n, m = f()
s = k = 0
d = [[]]
for i in f():
    j = 2
    t = []
    while j * j <= i:
        while i % j == 0:
            t.append((j, k))
            k += 1
            i //= j
        j += 1
    if i > 1:
        t.append((i, k))
        k += 1
    d.append(t)
p = [[] for i in range(k)]
for q in range(m):
    a, b = f()
    if b % 2: a, b = b, a
    for x, i in d[a]:
        for y, j in d[b]:
            if x == y: p[i].append(j)
v = [-1] * k
for i in range(k):
    u = [1] * k
    s += g(i)
print(s)


I found an interesting problem on https://codeforces.com/problemset/problem/499/A:
You have decided to watch the best moments of some movie. There are two buttons on your player:   Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.  Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t + x).

Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the l_{i}-th minute and ends at the r_{i}-th minute (more formally, the i-th best moment consists of minutes: l_{i}, l_{i} + 1, ..., r_{i}).

Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?

-----Input-----

The first line contains two space-separated integers n, x (1 ≤ n ≤ 50, 1 ≤ x ≤ 10^5) — the number of the best moments of the movie and the value of x for the second button.

The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^5).

It is guaranteed that for all integers i from 2 to n the following condition holds: r_{i} - 1 < l_{i}.

-----Output-----

Output a single number — the answer to the problem.

-----Examples-----
Input
2 3
5 6
10 12

Output
6

Input
1 1
1 100000

Output
100000

-----Note-----

In the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the...

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

[n, x], cur, ans = list(map(int, input().split())), 1, 0
for i in range(n):
	l, r = list(map(int, input().split()))
	cur += (l - cur) // x * x
	ans += r - cur + 1
	cur = r + 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/499/B:
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.

You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.

You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.

You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.

-----Input-----

The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages.

The following m lines contain the words. The i-th line contains two strings a_{i}, b_{i} meaning that the word a_{i} belongs to the first language, the word b_{i} belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.

The next line contains n space-separated strings c_1, c_2, ..., c_{n} — the text of the lecture. It is guaranteed that each of the strings c_{i} belongs to the set of strings {a_1, a_2, ... a_{m}}.

All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.

-----Output-----

Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the...

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

def main():
    n, m = map(int, input().split())
    d = {}
    for _ in range(m):
        a, b = input().split()
        d[a] = d[b] = b if len(a) > len(b) else a
    print(' '.join([d[_] for _ in input().split()]))

def __starting_point():
    main()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/500/A:
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.

So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a_1, a_2, ..., a_{n} - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ a_{i} ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + a_{i}), and one can travel from cell i to cell (i + a_{i}) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + a_{i}) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ a_{i} ≤ n - i one can't leave the Line World using portals.

Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

-----Input-----

The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 10^4) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to.

The second line contains n - 1 space-separated integers a_1, a_2, ..., a_{n} - 1 (1 ≤ a_{i} ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.

-----Output-----

If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".

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

Output
YES

Input
8 5
1 2 1 2 1 1 1

Output
NO

-----Note-----

In the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.

In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.

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

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

current = 0

while current < t - 1:
    current = a[current] + current

print('YES' if current == t - 1 else 'NO')


I found an interesting problem on https://codeforces.com/problemset/problem/500/B:
User ainta has a permutation p_1, p_2, ..., p_{n}. As the New Year is coming, he wants to make his permutation as pretty as possible.

Permutation a_1, a_2, ..., a_{n} is prettier than permutation b_1, b_2, ..., b_{n}, if and only if there exists an integer k (1 ≤ k ≤ n) where a_1 = b_1, a_2 = b_2, ..., a_{k} - 1 = b_{k} - 1 and a_{k} < b_{k} all holds.

As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of p_{i} and p_{j} (1 ≤ i, j ≤ n, i ≠ j) if and only if A_{i}, j = 1.

Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p.

The second line contains n space-separated integers p_1, p_2, ..., p_{n} — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation.

Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line A_{i}, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, A_{i}, j = A_{j}, i holds. Also, for all integers i where 1 ≤ i ≤ n, A_{i}, i = 0 holds.

-----Output-----

In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.

-----Examples-----
Input
7
5 2 4 3 6 7 1
0001001
0000000
0000010
1000001
0000000
0010000
1001000

Output
1 2 4 3 6 7 5

Input
5
4 2 1 5 3
00100
00011
10010
01101
01010

Output
1 2 3 4 5

-----Note-----

In the first sample, the swap needed to obtain the prettiest permutation is: (p_1, p_7).

In the second sample, the swaps needed to obtain the prettiest permutation is (p_1, p_3), (p_4, p_5), (p_3, p_4).  [Image]

A permutation p is a sequence of...

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

n = int(input())
p = list(map(int, input().split()))
a = [list(map(int, list(input()))) for _ in range(n)]

groups = []

for i in range(n):
    s = set()
    s.add(i)
    for j in range(n):
        if a[i][j] == 1:
            s.add(j)
    if len(s) > 1:
        groups.append(s)

i = 0
while i < len(groups):
    j = i + 1
    while j < len(groups):
        if len(groups[i] & groups[j]) == 0:
            j += 1
            continue
        groups[i] |= groups[j]
        groups.pop(j)
        j = i + 1
    i += 1

groups = [sorted(list(s)) for s in groups]

for g in groups:
    i = len(g)
    while i > 0:
        j = 0
        while j < i - 1:
            if p[g[j]] > p[g[j+1]]:
                p[g[j]], p[g[j+1]] = p[g[j+1]], p[g[j]]
            j += 1
        i -= 1

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


I found an interesting problem on https://codeforces.com/problemset/problem/500/C:
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is w_{i}.

As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack.

[Image]

He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer b_{j} (1 ≤ b_{j} ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.

After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

-----Input-----

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books.

The second line contains n space-separated integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 100) — the weight of each book.

The third line contains m space separated integers b_1, b_2, ..., b_{m} (1 ≤ b_{j} ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

-----Output-----

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

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

Output
12

-----Note-----

Here's a picture depicting the example. Each...

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

def main():
    input()
    ww = list(map(int, input().split()))
    bb = [int(_) - 1 for _ in input().split()]
    aa = []
    for i in bb:
        if i not in aa:
            aa.append(i)
    aa.reverse()
    tot = 0
    for b in bb:
        idx = aa.index(b)
        del aa[idx]
        tot += sum([ww[_] for _ in aa[idx:]])
        aa.append(b)
    print(tot)

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/500/D:
New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v.

As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the r_{i}-th road is going to become w_{i}, which is shorter than its length before. Assume that the current year is year 1.

Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c_1, c_2, c_3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city c_{k}.

It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c_1, c_2) + d(c_2, c_3) + d(c_3, c_1) dollars. Santas are too busy to find the best place, so they decided to choose c_1, c_2, c_3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.

However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.

-----Input-----

The first line contains an integer n (3 ≤ n ≤ 10^5) — the number of cities in Tree World.

Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers a_{i}, b_{i}, l_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}, 1 ≤ l_{i} ≤ 10^3), denoting that the i-th road connects cities a_{i} and b_{i}, and the length of i-th road is...

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

import sys
sys.setrecursionlimit(1500)

MAX = 100005;
g = [[] for _ in range(MAX)]
vis = [False] * MAX
dp = [0] * MAX
prod = [0] * MAX

edges = []
order = []
def dfs(st):
    stack = []
    stack.append((st, -1))
    vis[st] = True
    while stack:
        st, parent = stack.pop()
        order.append(st)
        vis[st] = True
        if (st == parent): continue;
        for i in g[st]:
            if (vis[i[0]]): continue;
            stack.append((i[0], st))

n = int(input())
for i in range(n-1):
    a, b, w = list(map(int, sys.stdin.readline().split(' ')))
    g[a].append([b, w])
    g[b].append([a,w])
    edges.append([[a, b], w])

dfs(1);
order.reverse()
for st in order:
    dp[st] = 1;
    for i in g[st]:
        dp[st] += dp[i[0]];
tot = 0;
curr = 1;
div = n * (n-1) / 2;
for i in edges:
    a = i[0][0];
    b = i[0][1];
    sa = dp[a];
    sb = dp[b];
    tot += min(sa, sb) * (n - min(sa, sb)) * i[1];
    prod[curr] = min(sa, sb) * (n - min(sa, sb));
    curr += 1;

q = int(input())
for i in range(q):
    q1, q2 = list(map(int, sys.stdin.readline().split(' ')))
    tot -= prod[q1] * edges[q1-1][1];
    edges[q1-1][1] = q2;
    tot += prod[q1] * edges[q1-1][1];
    sys.stdout.write(str(tot*3/div)+"\n")