I found an interesting problem on https://codeforces.com/problemset/problem/279/C:
You've got an array, consisting of n integers a_1, a_2, ..., a_{n}. Also, you've got m queries, the i-th query is described by two integers l_{i}, r_{i}. Numbers l_{i}, r_{i} define a subsegment of the original array, that is, the sequence of numbers a_{l}_{i}, a_{l}_{i} + 1, a_{l}_{i} + 2, ..., a_{r}_{i}. For each query you should check whether the corresponding segment is a ladder.

A ladder is a sequence of integers b_1, b_2, ..., b_{k}, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1 ≤ x ≤ k), that the following inequation fulfills: b_1 ≤ b_2 ≤ ... ≤ b_{x} ≥ b_{x} + 1 ≥ b_{x} + 2... ≥ b_{k}. Note that the non-decreasing and the non-increasing sequences are also considered ladders.

-----Input-----

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of array elements and the number of queries. The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where number a_{i} stands for the i-th array element.

The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the boundaries of the subsegment of the initial array.

The numbers in the lines are separated by single spaces.

-----Output-----

Print m lines, in the i-th line print word "Yes" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word "No" (without the quotes) otherwise.

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

Output
Yes
Yes
No
Yes
No
Yes

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

[n, q]=list(map(int, input().split()))
arr=list(map(int, input().split()))
interval=[idx for idx in range(n)]
l ,r = 0, 1
while(l<=r and r<n):
    while(r<n and arr[r]>=arr[r-1]):
        r+=1
    last=r
    while(r<n and arr[r]<=arr[r-1]):
        if(arr[r]!=arr[last]):
            last=r
        r+=1
    for idx in range(l, r):
        interval[idx]=max(interval[idx], r-1)
    l=last

ans=[]
for _ in range(q):
    [l, r]=list(map(int, input().split()))
    if(interval[l-1]>=r-1):
        ans.append('Yes')
    else:
        ans.append('No')
for x in ans:
    print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/279/D:
You've got a positive integer sequence a_1, a_2, ..., a_{n}. All numbers in the sequence are distinct. Let's fix the set of variables b_1, b_2, ..., b_{m}. Initially each variable b_{i} (1 ≤ i ≤ m) contains the value of zero. Consider the following sequence, consisting of n operations.

The first operation is assigning the value of a_1 to some variable b_{x} (1 ≤ x ≤ m). Each of the following n - 1 operations is assigning to some variable b_{y} the value that is equal to the sum of values that are stored in the variables b_{i} and b_{j} (1 ≤ i, j, y ≤ m). At that, the value that is assigned on the t-th operation, must equal a_{t}. For each operation numbers y, i, j are chosen anew.

Your task is to find the minimum number of variables m, such that those variables can help you perform the described sequence of operations.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 23). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{k} ≤ 10^9).

It is guaranteed that all numbers in the sequence are distinct.

-----Output-----

In a single line print a single number — the minimum number of variables m, such that those variables can help you perform the described sequence of operations.

If you cannot perform the sequence of operations at any m, print -1.

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

Output
2

Input
3
3 6 5

Output
-1

Input
6
2 4 8 6 10 18

Output
3

-----Note-----

In the first sample, you can use two variables b_1 and b_2 to perform the following sequence of operations.  b_1 := 1;  b_2 := b_1 + b_1;  b_1 := b_1 + b_2;  b_1 := b_1 + b_1;  b_1 := b_1 + b_2.

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

def Solve(x,B):
    if((X,x,B) in Mem):
        return Mem[(X,x,B)]
    if(len(B)>X):
        return False
    if(x==len(L)):
        return True
    if(Form(L[x],B)):
        A=list(B)
        for e in range(len(B)):
            r=A[e]
            A[e]=L[x]
            if(Solve(x+1,tuple(sorted(A)))):
                Mem[(X,x,B)]=True
                return True
            A[e]=r
        A+=[L[x]]
        if(Solve(x+1,tuple(sorted(A)))):
            Mem[(X,x,B)]=True
            return True
    Mem[(X,x,B)]=False
    return False

def Form(x,B):
    for i in range(len(B)):
        for j in range(i,len(B)):
            if(B[i]+B[j]==x):
                return True
    return False

n=int(input())
L=list(map(int,input().split()))
done=False
Mem={}
for X in range(1,n+1):
    if(Solve(1,(L[0],))):
        print(X)
        done=True
        break
if(not done):
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/279/E:
Valera considers a number beautiful, if it equals 2^{k} or -2^{k} for some integer k (k ≥ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible.

Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.

-----Input-----

The first line contains string s (1 ≤ |s| ≤ 10^6), that is the binary representation of number n without leading zeroes (n > 0).

-----Output-----

Print a single integer — the minimum amount of beautiful numbers that give a total of n.

-----Examples-----
Input
10

Output
1

Input
111

Output
2

Input
1101101

Output
4

-----Note-----

In the first sample n = 2 is a beautiful number.

In the second sample n = 7 and Valera can decompose it into sum 2^3 + ( - 2^0).

In the third sample n = 109 can be decomposed into the sum of four summands as follows: 2^7 + ( - 2^4) + ( - 2^2) + 2^0.

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

t = input()
j = t[0]
d, s = 0, int(j)
for i in t[1: ]:
    if j != i:
        if d == 1: d, s = 0, s + 1
        else: d = 1
        j = i
    else: d = 1
print(s + (d and j == '1'))


I found an interesting problem on https://codeforces.com/problemset/problem/280/A:
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α. [Image]

Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.

-----Input-----

The first line contains three integers w, h, α (1 ≤ w, h ≤ 10^6; 0 ≤ α ≤ 180). Angle α is given in degrees.

-----Output-----

In a single line print a real number — the area of the region which belongs to both given rectangles.

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

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

Output
0.828427125

Input
6 4 30

Output
19.668384925

-----Note-----

The second sample has been drawn on the picture above.

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

from math import cos, pi, sin, atan
W, H, b = map(float, input().split())
a = (b/180)*pi

if (W < H):
    X = W
    W = H
    H = X

if (a > 0.5*pi):
    a = 0.5*pi - (a - 0.5*pi)

opp = W*H
if (a == 0):
    eindopp = W*H
else:
    if a > (atan(H/W)*2):
        Schuin = H/sin(a)
        eindopp = Schuin*H
    else:
        y = -2*cos(a)-cos(a)**2-1+sin(a)**2
        hks = (W*sin(a)-H*cos(a)-H)/y
        hgs = (H-hks-hks*cos(a))/sin(a)

        eindopp = opp - hks*sin(a)*hks*cos(a) - hgs*sin(a)*hgs*cos(a)

print(round(eindopp,9))


I found an interesting problem on https://codeforces.com/problemset/problem/281/A:
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.

Note, that during capitalization all the letters except the first one remains unchanged.

-----Input-----

A single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 10^3.

-----Output-----

Output the given word after capitalization.

-----Examples-----
Input
ApPLe

Output
ApPLe

Input
konjac

Output
Konjac

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/281/B:
You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction [Image] whose denominator is no more than n.

Formally, you should find such pair of integers a, b (1 ≤ b ≤ n; 0 ≤ a) that the value $|\frac{x}{y} - \frac{a}{b}|$ is as minimal as possible.

If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.

-----Input-----

A single line contains three integers x, y, n (1 ≤ x, y, n ≤ 10^5).

-----Output-----

Print the required fraction in the format "a/b" (without quotes).

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

Output
2/5

Input
7 2 4

Output
7/2

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

import math
x, y, n = map(int, input().split())
best = 0, 0
mingap = 10**9
eps = 1e-15
for i in range(1, n+1):
	m = (i*x)/y
	m1 = math.floor(m)
	m2 = math.ceil(m)
	gap1 = abs(x/y - m1/i)
	gap2 = abs(x/y - m2/i)
	if gap1<mingap-eps:
		mingap = gap1
		best = m1, i
	if gap2<mingap-eps:
		mingap = gap2
		best = m2, i
print(*best, sep='/')


I found an interesting problem on https://codeforces.com/problemset/problem/282/A:
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.

The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:

  Operation ++ increases the value of variable x by 1.  Operation -- decreases the value of variable x by 1.

A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.

A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.

You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme.

Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.

-----Output-----

Print a single integer — the final value of x.

-----Examples-----
Input
1
++X

Output
1

Input
2
X++
--X

Output
0

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

n=input()
n=int(n)
x=0
for i in range(n):
    s=input()
    if('+' in s):
        x+=1
    else:
        x-=1
print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/282/B:
The Bitlandians are quite weird people. They have very peculiar customs.

As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.

The kids are excited because just as is customary, they're going to be paid for the job!

Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.

Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.

Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^6) — the number of eggs.

Next n lines contain two integers a_{i} and g_{i} each (0 ≤ a_{i}, g_{i} ≤ 1000; a_{i} + g_{i} = 1000): a_{i} is the price said by A. for the i-th egg and g_{i} is the price said by G. for the i-th egg.

-----Output-----

If it is impossible to assign the painting, print "-1" (without quotes).

Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as S_{a}, and the money Uncle J. must pay G. for the painting as S_{g}, then this inequality must hold: |S_{a}  -  S_{g}|  ≤  500.

If there are several solutions, you are allowed to print any of them.

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

Output
AG

Input
3
400 600
400 600
400 600

Output
AGA

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

import sys

def main():
    n = int(sys.stdin.readline())

    a_sum = 0
    b_sum = 0
    while n > 0:
        r = tuple(map(int, sys.stdin.readline().rstrip().split(' ')))
        if a_sum + r[0] <= b_sum + 500:
            sys.stdout.write('A')
            a_sum += r[0]
        else:
            sys.stdout.write('G')
            b_sum += r[1]
        n -= 1

main()


I found an interesting problem on https://codeforces.com/problemset/problem/282/C:
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.

A Bitlandish string is a string made only of characters "0" and "1".

BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.

The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.

So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.

You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.

-----Input-----

The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths.

It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 10^6.

-----Output-----

Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.

-----Examples-----
Input
11
10

Output
YES

Input
1
01

Output
NO

Input
000
101

Output
NO

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

a = input()
b = input()

if len(a) != len(b):
   print('NO')
elif a == b:
   print('YES')
else:
   s = '0'*len(a)
   if a == s or b == s:
      print('NO')
   else:
      print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/282/D:
Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games!

Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games.

BitLGM and BitAryo are playing yet another of their crazy-looking genius-needed Bitlandish games. They've got a sequence of n non-negative integers a_1, a_2, ..., a_{n}. The players make moves in turns. BitLGM moves first. Each player can and must do one of the two following actions in his turn:

  Take one of the integers (we'll denote it as a_{i}). Choose integer x (1 ≤ x ≤ a_{i}). And then decrease a_{i} by x, that is, apply assignment: a_{i} = a_{i} - x.  Choose integer x $(1 \leq x \leq \operatorname{min}_{i = 1} a_{i})$. And then decrease all a_{i} by x, that is, apply assignment: a_{i} = a_{i} - x, for all i.

The player who cannot make a move loses.

You're given the initial sequence a_1, a_2, ..., a_{n}. Determine who wins, if both players plays optimally well and if BitLGM and BitAryo start playing the described game in this sequence.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 3).

The next line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} < 300).

-----Output-----

Write the name of the winner (provided that both players play optimally well). Either "BitLGM" or "BitAryo" (without the quotes).

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

Output
BitLGM

Input
2
1 2

Output
BitAryo

Input
3
1 2 1

Output
BitLGM

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

from math import *
n=int(input())
if n==3:
    li=list(map(int,input().split()))
    ans=0
    flag=0
    for i in li:
        ans^=i
    if ans==0:
        print("BitAryo")
    else:
        print("BitLGM")
elif n==2:
    li=list(map(int,input().split()))
    li.sort()
    phi=(1+sqrt(5))/2
    ch=[0]*(785)
    for i in range(300):
        a=floor(phi*i)
        b=floor((phi**2)*i)
        ch[a]=b
        ch[b]=a
    if ch[li[0]]==li[1]:
        print("BitAryo")
    else:
        print("BitLGM")
else:
    li=int(input())
    if li==0:
        print("BitAryo")
    else:
        print("BitLGM")


I found an interesting problem on https://codeforces.com/problemset/problem/284/A:
The cows have just learned what a primitive root is! Given a prime p, a primitive root $\operatorname{mod} p$ is an integer x (1 ≤ x < p) such that none of integers x - 1, x^2 - 1, ..., x^{p} - 2 - 1 are divisible by p, but x^{p} - 1 - 1 is.

Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots $\operatorname{mod} p$.

-----Input-----

The input contains a single line containing an integer p (2 ≤ p < 2000). It is guaranteed that p is a prime.

-----Output-----

Output on a single line the number of primitive roots $\operatorname{mod} p$.

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

Output
1

Input
5

Output
2

-----Note-----

The only primitive root $\operatorname{mod} 3$ is 2.

The primitive roots $\operatorname{mod} 5$ are 2 and 3.

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

from fractions import gcd

tt=0

#phi(p-1)

x=int(input())

x-=1

for i in range(1, x+1):

    if gcd(x,i)==1:

        tt+=1

print(tt)


I found an interesting problem on https://codeforces.com/problemset/problem/284/B:
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".

Find the number of cows that can currently show their hands without affecting any betting decisions.

-----Input-----

The first line contains a single integer, n (2 ≤ n ≤ 2·10^5). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".

-----Output-----

The first line should contain a single integer denoting the number of players that can currently show their hands.

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

Output
4

Input
3
AFI

Output
1

-----Note-----

In the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.

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

from collections import defaultdict, deque, Counter, OrderedDict
from bisect import insort, bisect_right, bisect_left
import threading, sys

def main():
    n = int(input())
    s = input()
    a = s.count('A')
    i = s.count('I')
    ans = 0
    if i == 0:
        ans = a
    else:
        if i == 1:
            ans = 1
    print(ans)

def __starting_point():
    """sys.setrecursionlimit(400000)
    threading.stack_size(40960000)"""
    thread = threading.Thread(target=main)
    thread.start()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/285/A:
Permutation p is an ordered set of integers p_1,  p_2,  ...,  p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1,  p_2,  ...,  p_{n}.

The decreasing coefficient of permutation p_1, p_2, ..., p_{n} is the number of such i (1 ≤ i < n), that p_{i} > p_{i} + 1.

You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.

-----Input-----

The single line contains two space-separated integers: n, k (1 ≤ n ≤ 10^5, 0 ≤ k < n) — the permutation length and the decreasing coefficient.

-----Output-----

In a single line print n space-separated integers: p_1, p_2, ..., p_{n} — the permutation of length n with decreasing coefficient k.

If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.

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

Output
1 5 2 4 3

Input
3 0

Output
1 2 3

Input
3 2

Output
3 2 1

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

n,k=list(map(int,input().split()))
i=1
while i<(n-k):
	print(i,end='')
	print(' ',end='')
	i+=1
i=n
while i>n-k-1:
	print(i,end='')
	print(' ',end='')
	i-=1


I found an interesting problem on https://codeforces.com/problemset/problem/285/B:
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.

First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p_1, the glass from the second position to position p_2 and so on. That is, a glass goes from position i to position p_{i}. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.

After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.

-----Input-----

The first line contains three integers: n, s, t (1 ≤ n ≤ 10^5; 1 ≤ s, t ≤ n) — the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the shuffling operation parameters. It is guaranteed that all p_{i}'s are distinct.

Note that s can equal t.

-----Output-----

If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.

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

Output
3

Input
4 3 3
4 1 3 2

Output
0

Input
4 3 4
1 2 3 4

Output
-1

Input
3 1 3
2 1 3

Output
-1

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

rd=lambda: list(map(int, input().split()))
n,s,t=rd()
A=rd()
cur=s
ans=0
for i in range(n):
   if(cur==t):
      print(ans);
      return
   cur=A[cur-1]
   ans=ans+1
print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/285/C:
Permutation p is an ordered set of integers p_1,  p_2,  ...,  p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1,  p_2,  ...,  p_{n}.

You have a sequence of integers a_1, a_2, ..., a_{n}. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 3·10^5) — the size of the sought permutation. The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9).

-----Output-----

Print a single number — the minimum number of moves.

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

Output
2

Input
3
-1 -1 2

Output
6

-----Note-----

In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).

In the second sample you need 6 moves to build permutation (1, 3, 2).

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

n = int(input())
A = sorted(list(map(int, input().split())))
cnt = 0
for i in range(n):
    cnt += abs(A[i] - (i + 1))
print(cnt)


I found an interesting problem on https://codeforces.com/problemset/problem/285/D:
Permutation p is an ordered set of integers p_1,  p_2,  ...,  p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1,  p_2,  ...,  p_{n}.

Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n}. Petya calls the sum of permutations a and b such permutation c of length n, where c_{i} = ((a_{i} - 1 + b_{i} - 1) mod n) + 1 (1 ≤ i ≤ n).

Operation $x \text{mod} y$ means taking the remainder after dividing number x by number y.

Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs.

As the answer can be rather large, print the remainder after dividing it by 1000000007 (10^9 + 7).

-----Input-----

The single line contains integer n (1 ≤ n ≤ 16).

-----Output-----

In the single line print a single non-negative integer — the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (10^9 + 7).

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

Output
18

Input
5

Output
1800

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/285/E:
Permutation p is an ordered set of integers p_1,  p_2,  ...,  p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1,  p_2,  ...,  p_{n}.

We'll call position i (1 ≤ i ≤ n) in permutation p_1, p_2, ..., p_{n} good, if |p[i] - i| = 1. Count the number of permutations of size n with exactly k good positions. Print the answer modulo 1000000007 (10^9 + 7).

-----Input-----

The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 0 ≤ k ≤ n).

-----Output-----

Print the number of permutations of length n with exactly k good positions modulo 1000000007 (10^9 + 7).

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

Output
1

Input
2 1

Output
0

Input
3 2

Output
4

Input
4 1

Output
6

Input
7 4

Output
328

-----Note-----

The only permutation of size 1 has 0 good positions.

Permutation (1, 2) has 0 good positions, and permutation (2, 1) has 2 positions.

Permutations of size 3:

 (1, 2, 3) — 0 positions

 $(1,3,2)$ — 2 positions

 $(2,1,3)$ — 2 positions

 $(2,3,1)$ — 2 positions

 $(3,1,2)$ — 2 positions

 (3, 2, 1) — 0 positions

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/287/A:
In the city of Ultima Thule job applicants are often offered an IQ test.

The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 × 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed.

Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 × 2 square, consisting of cells of the same color.

-----Input-----

Four lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.

-----Output-----

Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.

-----Examples-----
Input
####
.#..
####
....

Output
YES

Input
####
....
####
....

Output
NO

-----Note-----

In the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column.

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

def getField():
    field = []
    for i in range(0, 4):
        field.append(input())
    return field
def canPass(field):
    for i in range(0, 3):
        for j in range(0,3):
            if field[i][j] == field[i + 1][j] == field[i + 1][j+1]:
                return True
    return False
def canPassTotal(field):
    res = False
    for i in range(0, 4):
        res = res or canPass(field)
        field = rot(field)
    return res
def rot(mat):
    mat = [mat[i] for i in range(len(mat) - 1, -1, -1)]
    t = [[x[i] for x in mat] for i in range(0,len(mat[0]))];
    return t

ans = {'True':'YES', 'False':'NO'}
print(ans[str(canPassTotal(getField()))])


I found an interesting problem on https://codeforces.com/problemset/problem/287/B:
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters.

A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. [Image] The figure shows a 4-output splitter

Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible.

Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.

-----Input-----

The first line contains two space-separated integers n and k (1 ≤ n ≤ 10^18, 2 ≤ k ≤ 10^9).

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

-----Output-----

Print a single integer — the minimum number of splitters needed to build the pipeline. If it is impossible to build a pipeline with the given splitters, print -1.

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

Output
2

Input
5 5

Output
1

Input
8 4

Output
-1

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/288/A:
Little penguin Polo adores strings. But most of all he adores strings of length n.

One day he wanted to find a string that meets the following conditions:  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s_1s_2... s_{n}, then the following inequality holds, s_{i} ≠ s_{i} + 1(1 ≤ i < n).  Among all strings that meet points 1 and 2, the required string is lexicographically smallest.

Help him find such string or state that such string doesn't exist.

String x = x_1x_2... x_{p} is lexicographically less than string y = y_1y_2... y_{q}, if either p < q and x_1 = y_1, x_2 = y_2, ... , x_{p} = y_{p}, or there is such number r (r < p, r < q), that x_1 = y_1, x_2 = y_2, ... , x_{r} = y_{r} and x_{r} + 1 < y_{r} + 1. The characters of the strings are compared by their ASCII codes.

-----Input-----

A single line contains two positive integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

-----Output-----

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

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

Output
ababacd

Input
4 7

Output
-1

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

# coding: utf-8
letter = [chr(ord('a')+i) for i in range(26)]
n, k = [int(i) for i in input().split()]
if k>n or (k==1 and n>1):
    print(-1)
    return
if k==1:
    print('a')
    return
ans = [letter[i%2] for i in range(n-k+2)]
ans += [letter[2+i] for i in range(k-2)]
print(''.join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/288/B:
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer p_{i} (1 ≤ p_{i} ≤ n).

Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house p_{x}), then he goes to the house whose number is written on the plaque of house p_{x} (that is, to house p_{p}_{x}), and so on.

We know that:  When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.  When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.  When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.

You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (10^9 + 7).

-----Input-----

The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.

-----Output-----

In a single line print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7).

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

Output
54

Input
7 4

Output
1728

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/288/C:
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.

For permutation p = p_0, p_1, ..., p_{n}, Polo has defined its beauty — number $(0 \oplus p_{0}) +(1 \oplus p_{1}) + \cdots +(n \oplus p_{n})$.

Expression $x \oplus y$ means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor".

Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.

-----Input-----

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

-----Output-----

In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m.

If there are several suitable permutations, you are allowed to print any of them.

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

Output
20
0 2 1 4 3

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

n = int(input())
p = [i for i in range(n + 1)]

k = 1
while(2 * k <= n):
  k *= 2
m = n + 1
while m > 0:
  while k >= m:
    k //= 2
  for i in range(m - k):
    if k - i - 1 >= 0:
      p[k + i], p[k - i - 1] = p[k - i - 1], p[k + i]
  m = k - i - 1

print(n * (n + 1))
print(' '.join(map(str, p)))


I found an interesting problem on https://codeforces.com/problemset/problem/289/A:
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r).

He has a set that consists of n integer segments: [l_1; r_1], [l_2; r_2], ..., [l_{n}; r_{n}]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].

The value of a set of segments that consists of n segments [l_1; r_1], [l_2; r_2], ..., [l_{n}; r_{n}] is the number of integers x, such that there is integer j, for which the following inequality holds, l_{j} ≤ x ≤ r_{j}.

Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.

-----Input-----

The first line contains two integers n and k (1 ≤ n, k ≤ 10^5). Each of the following n lines contain a segment as a pair of integers l_{i} and r_{i} ( - 10^5 ≤ l_{i} ≤ r_{i} ≤ 10^5), separated by a space.

It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(r_{i}, r_{j}) < max(l_{i}, l_{j}).

-----Output-----

In a single line print a single integer — the answer to the problem.

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

Output
2

Input
3 7
1 2
3 3
4 7

Output
0

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

q=lambda:map(int,input().split())
n,k=q()
a=[]
while(n):
    a+=[q()]
    n-=1
print((k-sum(r-l+1 for l,r in a)%k)%k)


I found an interesting problem on https://codeforces.com/problemset/problem/289/B:
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as a_{ij}.

In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

-----Input-----

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 10^4) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element a_{ij} (1 ≤ a_{ij} ≤ 10^4).

-----Output-----

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

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

Output
4

Input
1 2 7
6 7

Output
-1

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

import re
import itertools
from collections import Counter, deque

class Task:
    a = []
    d = 0
    answer = 0

    def getData(self):
        n, m, self.d = [int(x) for x in input().split(' ')]
        for _ in range(n):
            self.a += [int(x) for x in input().split(' ')]
        #inFile = open('input.txt', 'r')
        #inFile.readline().rstrip()
        #self.childs = inFile.readline().rstrip()

    def solve(self):
        a = self.a

        for x in a:
            if x % self.d != a[0] % self.d:
                self.answer = -1
                return

        a = [x // self.d for x in a]
        a.sort()

        d = [sum(a)] + [0 for _ in range(1, a[-1] + 1)]

        lessCurrentLevel = 0
        counter = Counter(a)

        for level in range(1, a[-1] + 1):
            lessCurrentLevel += counter[level - 1]
            d[level] = d[level - 1] + lessCurrentLevel - \
                    (len(a) - lessCurrentLevel)
        self.answer = min(d)

    def solve2(self):
        a, d = self.a, self.d
        for i in range(1, len(a)):
            if a[i] % d != a[0] % d:
                self.answer = -1
                return
        a = [x // d for x in a]
        d = [abs(a[0] - i) for i in range(10000 + 1)]
        for i in range(1, len(a)):
            for j in range(0, len(d)):
                d[j] += abs(a[i] - j)
        self.answer = min(d)

    def printAnswer(self):
        print(self.answer)
        #print(re.sub('[\[\],]', '', str(self.answer)))
        #outFile = open('output.txt', 'w')
        #outFile.write(self.answer)

task = Task()
task.getData()
task.solve()
task.printAnswer()


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

The input contains a single integer a (1 ≤ a ≤ 40).

-----Output-----

Output a single string.

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

Output
Adams

Input
8

Output
Van Buren

Input
29

Output
Harding

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

presidents = "Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson", "Van Buren", "Harrison", "Tyler", "Polk", "Taylor", "Fillmore", "Pierce", "Buchanan", "Lincoln", "Johnson", "Grant", "Hayes", "Garfield", "Arthur", "Cleveland", "Harrison", "Cleveland", "McKinley", "Roosevelt", "Taft", "Wilson", "Harding", "Coolidge", "Hoover", "Roosevelt", "Truman", "Eisenhower", "Kennedy", "Johnson", "Nixon", "Ford", "Carter", "Reagan"
print(presidents[int(input()) - 1])


I found an interesting problem on https://codeforces.com/problemset/problem/290/B:
[Image]

-----Input-----

The input contains two integers a_1, a_2 (0 ≤ a_{i} ≤ 32), separated by a single space.

-----Output-----

Output a single integer.

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

Output
0

Input
3 7

Output
0

Input
13 10

Output
1

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/290/C:
HAI

I HAS A TUX

GIMMEH TUX

I HAS A FOO ITS 0

I HAS A BAR ITS 0

I HAS A BAZ ITS 0

I HAS A QUZ ITS 1

TUX IS NOW A NUMBR

IM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0

I HAS A PUR

GIMMEH PUR

PUR IS NOW A NUMBR

FOO R SUM OF FOO AN PUR

BAR R SUM OF BAR AN 1

BOTH SAEM BIGGR OF PRODUKT OF FOO AN QUZ AN PRODUKT OF BAR BAZ AN PRODUKT OF FOO AN QUZ

O RLY?

YA RLY

BAZ R FOO

QUZ R BAR

OIC

IM OUTTA YR LOOP

BAZ IS NOW A NUMBAR

VISIBLE SMOOSH QUOSHUNT OF BAZ QUZ

KTHXBYE

-----Input-----

The input contains between 1 and 10 lines, i-th line contains an integer number x_{i} (0 ≤ x_{i} ≤ 9).

-----Output-----

Output a single real number. The answer is considered to be correct if its absolute or relative error does not exceed 10^{ - 4}.

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

Output
0.666667

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

foo = baz = 0
quz = 1
for bar in range(1, int(input()) + 1):
    foo += int(input())
    if foo * quz < baz * bar: break
    baz, quz = foo, bar
print(baz / quz)


I found an interesting problem on https://codeforces.com/problemset/problem/290/D:
[Image]

-----Input-----

The first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase.

The second line of the input is an integer between 0 and 26, inclusive.

-----Output-----

Output the required string.

-----Examples-----
Input
AprilFool
14

Output
AprILFooL

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

x = "abcdefghijklmnopqrstuvwxyz"
X = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
z = list(input())
n = int(input())
for i in range(len(z)):
    if(z[i] in x):
        k = x.index(z[i]) + 1
    else:
        k = X.index(z[i]) + 1
    if(k <= n):
        z[i] = z[i].upper()
    else:
        z[i] = z[i].lower()
ans = "".join(z)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/290/E:
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ...

-----Input-----

The only line of the input is a string between 1 and 10^6 characters long.

-----Output-----

Output "Yes" or "No".

-----Examples-----
Input
HHHH

Output
Yes

Input
HQHQH

Output
No

Input
HHQHHQH

Output
No

Input
HHQQHHQQHH

Output
Yes

-----Note-----

The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience.

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

a = input()
b = []
h = ''
c = 0
for i in a:
	if i == 'Q':
		c += 1
if c == 0:
	print('Yes')
	return
r = -1
for i in range(1001):
	if i*i == c:
		r = i
		break
if r == -1:
	print('No')
	return
h = [a.split('Q')[0], a.split('Q')[-1]]
c = [len(h[0]), len(h[1])]
if c[0] % 2 != 0 or c[1] % 2 != 0:
	print('No')
	return
c[0] //= 2
c[1] //= 2
resp = ''
i = c[0]
while True:
	if i >= len(a):
		break
	if r == 0 and a[i] == 'Q':
		break
	resp += a[i]
	if r == 0 and a[i] == 'H':
		c[1] -= 1
	if c[1] == 0 and r == 0:
		break
	if a[i] == 'Q':
		r -= 1
	if r == -1:
		print('No')
		return
	i += 1

def hq(a):
	resp = ''
	for i in a:
		if i == 'H':
			resp += 'H'
		else:
			resp += a
	return resp

if a == hq(resp):
	print('Yes')
else:
	print('No')


I found an interesting problem on https://codeforces.com/problemset/problem/291/A:
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.

One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.

Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.

Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^3) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id_1, id_2, ..., id_{n} (0 ≤ id_{i} ≤ 10^9). Number id_{i} equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.

Consider the secretaries indexed from 1 to n in some way.

-----Output-----

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

-----Examples-----
Input
6
0 1 7 1 7 10

Output
2

Input
3
1 1 1

Output
-1

Input
1
0

Output
0

-----Note-----

In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.

In the second test sample the described situation is impossible as conferences aren't allowed.

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

n=int(input())
s=input().split()
for i in range(n):
    s[i]=int(s[i])
ans=0
done=False
for i in range(n):
    if(s[i]==0):
        continue
    n=s[i+1:].count(s[i])
    if(n==1):
        ans+=1
    elif(n>1):
        print(-1)
        done=True
        break

if(not done):
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/291/B:
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.

In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.

To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).

It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.

You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given...

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

s = input()

inside = False
lexeme = []
for c in s:
    if c == '"':
        if inside:
            inside = False
            print("%s>" % ''.join(lexeme))
            lexeme = []
        else:
            lexeme = ['<']
            inside = True
    elif c == ' ':
        if inside:
            lexeme.append(c)
        elif len(lexeme):
            print("%s>" % ''.join(lexeme))
            lexeme = []
    else:
        if len(lexeme):
            lexeme.append(c)
        else:
            lexeme = ['<', c]
if len(lexeme):
    print("%s>" % ''.join(lexeme))


I found an interesting problem on https://codeforces.com/problemset/problem/291/C:
The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.

Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.

Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.

The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.

To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.

Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.

-----Input-----

The first line contains two...

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

import math
import re
from fractions import Fraction
from collections import Counter

class Task:
    ips = []
    k = 0
    answer = ''

    def __init__(self):
        n, self.k = [int(x) for x in input().split()]
        self.ips = ['' for _ in range(n)]
        for i in range(len(self.ips)):
            self.ips[i] = input()

    def solve(self):
        ips, k = self.ips, self.k
        ipAsNumbers = []
        for currentIp in ips:
            number = 0
            parts = currentIp.split('.')
            for i in range(0, len(parts)):
                number += int(parts[i]) * 2**(32 - (i + 1) * 8)
            ipAsNumbers += [number]

        mask = 0
        for i in range(31, -1, -1):
            mask += 2**i
            netAddresses = set()
            for ip in ipAsNumbers:
                netAddresses.add(mask & ip)
            if len(netAddresses) == k:
                mask = bin(mask)[2:]
                self.answer = '.'.join([str(int(mask[i : i + 8], 2)) \
                    for i in range(0, len(mask), 8)])
                return
        self.answer = '-1'

    def printAnswer(self):
        print(self.answer)
        #for line in self.answer:
        #    print(line)

task = Task()
task.solve()
task.printAnswer()


I found an interesting problem on https://codeforces.com/problemset/problem/292/A:
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.

For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers t_{i} and c_{i} — the receiving time (the second) and the number of the text messages, correspondingly.

Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:

  If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.  If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.

Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^3) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers t_{i} and c_{i} (1 ≤ t_{i}, c_{i} ≤ 10^6) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.

It is...

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

n = int(input())
arr = []
for _ in range(n):
    arr.append([int(i) for i in input().split()])
arr.sort(key=lambda x: x[0])
queue_size = 0
time = 0
max_queue_size = 0
last_time = 0
for t, c in arr:
    # print("Queue:", queue_size, "Time:", time)
    sent = t - last_time
    queue_size = max(0, queue_size - sent)
    queue_size += c
    time = t
    max_queue_size = max(max_queue_size, queue_size)
    last_time = time
print(time + queue_size, max_queue_size)


I found an interesting problem on https://codeforces.com/problemset/problem/292/B:
This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.

Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computers

Polycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.

Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.

Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. [Image] (1) — bus, (2) — ring, (3) — star

You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown.

-----Input-----

The first line contains two space-separated integers n and m (4 ≤ n ≤ 10^5; 3 ≤ m ≤ 10^5) — the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's...

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

mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
n,m=f()
l=[0]*n
for _ in range(m):
    a,b=f()
    l[a-1]+=1
    l[b-1]+=1
l.sort()
if l[0]==1 and l[1]==1 and all(i==2 for i in l[2:]):
    print('bus topology')
elif all(i==2 for i in l):
    print('ring topology')
elif all(i==1 for i in l[:n-1]) and l[-1]==n-1:
    print('star topology')
else:
    print('unknown topology')


I found an interesting problem on https://codeforces.com/problemset/problem/292/E:
We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.

More formally, you've got two arrays of integers a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n} of length n. Also, you've got m queries of two types:  Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute b_{y} + q = a_{x} + q for all integer q (0 ≤ q < k). The given operation is correct — both subsegments do not touch unexistent elements.  Determine the value in position x of array b, that is, find value b_{x}.

For each query of the second type print the result — the value of the corresponding element of array b.

-----Input-----

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 10^5) — the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10^9). The third line contains an array of integers b_1, b_2, ..., b_{n} (|b_{i}| ≤ 10^9).

Next m lines contain the descriptions of the queries. The i-th line first contains integer t_{i} — the type of the i-th query (1 ≤ t_{i} ≤ 2). If t_{i} = 1, then the i-th query means the copying operation. If t_{i} = 2, then the i-th query means taking the value in array b. If t_{i} = 1, then the query type is followed by three integers x_{i}, y_{i}, k_{i} (1 ≤ x_{i}, y_{i}, k_{i} ≤ n) — the parameters of the copying query. If t_{i} = 2, then the query type is followed by integer x_{i} (1 ≤ x_{i} ≤ n) — the position in array b.

All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.

-----Output-----

For each second type query print the result on a single line.

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

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

import sys
'''
SEGMENT TREE
Assign
'''
class SegmTree():
    '''
    - modify elements on interval
    - get single element
    '''
    def __init__(self, size):
        N = 1
        while N < size:
            N <<= 1
        self.N = N
        self.tree = [0] * (2*N)

    def modify_range(self, l, r, value):
        l += self.N
        r += self.N
        while l < r:
            if l & 1:
                self.tree[l] = value
                l += 1
            if r & 1:
                r -= 1
                self.tree[r] = value
            l >>= 1
            r >>= 1

    def query(self, i):
        i += self.N
        latest_change = self.tree[i]
        p = i
        while p > 1:
            p >>= 1
            latest_change = max(latest_change, self.tree[p])
        return latest_change

# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (list(map(int, line.split())) for line in sys.stdin)
input = reader.__next__

n, m = input()
a = list(input())
b = list(input())
st = SegmTree(n)
request = [None] * (m + 1)
for i in range(1, m+1):
    t, *arg = input()
    if t == 1:
        x, y, k = request[i] = arg
        st.modify_range(y-1, y-1+k, i)
    else:
        pos = arg[0] - 1
        req_id = st.query(pos)
        if req_id > 0:
            x, y, k = request[req_id]
            ans = a[x+(pos-y)]
        else:
            ans = b[pos]
        sys.stdout.write(f'{ans}\n')

# inf.close()


I found an interesting problem on https://codeforces.com/problemset/problem/293/A:
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.

Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.

Let's represent Yaroslav's word as s = s_1s_2... s_2n. Similarly, let's represent Andrey's word as t = t_1t_2... t_2n. Then, if Yaroslav choose number k during his move, then he is going to write out character s_{k} on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character t_{r} on the piece of paper.

The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.

You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^6). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word.

It is guaranteed that both words consist of 2·n characters "0" and "1".

-----Output-----

Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the...

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

ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,a1,a2=ii(),input(),input()
locs = [0]*4
for i in range(2*n):
	locs[int(a1[i])+2*int(a2[i])]+=1
rm = min(locs[1],locs[2])
locs[1]-=rm
locs[2]-=rm
locs[3]=locs[3]&1
if locs[1]:
	print("First")
else:
	if locs[3]:
		if locs[2]==0:
			print("First")
		elif locs[2]<3:
			print("Draw")
		else:
			print("Second")
	else:
		if locs[2]<2:
			print("Draw")
		else:
			print("Second")


I found an interesting problem on https://codeforces.com/problemset/problem/294/A:
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are a_{i} oskols sitting on the i-th wire. $40$

Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away.

Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.

-----Input-----

The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a_1, a_2, ..., a_{n}, (0 ≤ a_{i} ≤ 100).

The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers x_{i} and y_{i}. The integers mean that for the i-th time Shaass shoot the y_{i}-th (from left) bird on the x_{i}-th wire, (1 ≤ x_{i} ≤ n, 1 ≤ y_{i}). It's guaranteed there will be at least y_{i} birds on the x_{i}-th wire at that moment.

-----Output-----

On the i-th line of the output print the number of birds on the i-th wire.

-----Examples-----
Input
5
10 10 10 10 10
5
2 5
3 13
2 12
1 13
4 6

Output
0
12
5
0
16

Input
3
2 4 1
1
2 2

Output
3
0
3

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

n = int (input())
a = list(map(int, input().split()))
m = int (input())
for i in range(m):
    x,y = map(int, input().split())
    x-= 1
    if x > 0 :
        a[x - 1] += y - 1
    if x < n - 1 :
        a[x + 1] += a[x] - y
    a[x] = 0
for i in range(n):
    print(a[i])


I found an interesting problem on https://codeforces.com/problemset/problem/294/B:
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is t_{i} and its pages' width is equal to w_{i}. The thickness of each book is either 1 or 2. All books have the same page heights. $1$

Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. [Image]

Help Shaass to find the minimum total thickness of the vertical books that we can achieve.

-----Input-----

The first line of the input contains an integer n, (1 ≤ n ≤ 100). Each of the next n lines contains two integers t_{i} and w_{i} denoting the thickness and width of the i-th book correspondingly, (1 ≤ t_{i} ≤ 2, 1 ≤ w_{i} ≤ 100).

-----Output-----

On the only line of the output print the minimum total thickness of the vertical books that we can achieve.

-----Examples-----
Input
5
1 12
1 3
2 15
2 5
2 1

Output
5

Input
3
1 10
2 1
2 4

Output
3

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

3

n = int(input())
t = []
w = []
n1, n2 = 0, 0
for i in range(n):
    x, y = list(map(int, input().split()))
    t.append(x)
    w.append(y)
    n1 += x == 1
    n2 += x == 2

w1 = []
w2 = []
for i in range(n):
    if t[i] == 1:
        w1.append(w[i])
    else:
        w2.append(w[i])
w1.sort(reverse=True)
w2.sort(reverse=True)

ans = 201
for i in range(201):
    for j in range(min(i // 2, n2) + 1):
        k = min(n1, i - 2 * j)
        thickness = 2 * j + k
        if thickness >= sum(w1[k:]) + sum(w2[j:]):
            ans = min(ans, thickness)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/294/C:
There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on.

He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (10^9 + 7).

-----Input-----

The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on.

-----Output-----

In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (10^9 + 7).

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

Output
1

Input
4 2
1 4

Output
2

Input
11 2
4 8

Output
6720

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

import math

def solve( n, list1):
    list1.sort()
    inf = int(1e9 + 7)
    t1 = [list1[0] - 1, n - list1[-1]]
    t2 = []
    for i in range(1, len(list1)):
        t2.append((list1[i] - list1[i - 1] - 1))

    num1 = 1
    for i in range(n - len(list1)):
        num1 = num1 * (i + 1)
        num1 = num1 % inf
    num2 = 1
    num2 = math.factorial(t1[0]) % inf
    num2 = num2 % inf
    num2 = num2 * math.factorial(t1[1]) % inf
    num2 = num2 % inf
    for i in range(len(t2)):
        num2 = num2 * math.factorial(t2[i])
        num2 = num2 % inf
    num2 = pow(num2, inf - 2, inf)
    num3 = 1
    for i in range(len(t2)):
        if t2[i] - 1 < 0:
            continue
        num3 = (num3 * pow(2, t2[i] - 1, inf)) % inf

    num1 = num1 * num2
    num1 = num1 % inf
    num1 = num1 * num3
    num1 = num1 % inf

    return int(num1)
n,m = map(int,input().split())
list1 = list(map(int,input().split()))
print(solve(n,list1))


I found an interesting problem on https://codeforces.com/problemset/problem/295/C:
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold people with the total weight of at most k kilograms.

Greg immediately took a piece of paper and listed there the weights of all people in his group (including himself). It turned out that each person weights either 50 or 100 kilograms. Now Greg wants to know what minimum number of times the boat needs to cross the river to transport the whole group to the other bank. The boat needs at least one person to navigate it from one bank to the other. As the boat crosses the river, it can have any non-zero number of passengers as long as their total weight doesn't exceed k.

Also Greg is wondering, how many ways there are to transport everybody to the other side in the minimum number of boat rides. Two ways are considered distinct if during some ride they have distinct sets of people on the boat.

Help Greg with this problem.

-----Input-----

The first line contains two integers n, k (1 ≤ n ≤ 50, 1 ≤ k ≤ 5000) — the number of people, including Greg, and the boat's weight limit. The next line contains n integers — the people's weights. A person's weight is either 50 kilos or 100 kilos.

You can consider Greg and his friends indexed in some way.

-----Output-----

In the first line print an integer — the minimum number of rides. If transporting everyone to the other bank is impossible, print an integer -1.

In the second line print the remainder after dividing the number of ways to transport the people in the minimum number of rides by number 1000000007 (10^9 + 7). If transporting everyone to the other bank is impossible, print integer 0.

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

Output
1
1

Input
3 100
50 50 100

Output
5
2

Input
2 50
50 50

Output
-1
0

-----Note-----

In the first test Greg walks...

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

from collections import deque

n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
c50 = sum([1 for i in a if i == 50])
c100 = sum([1 for i in a if i == 100])
c = [[0] * 51 for i in range(51)]
c[0][0] = 1
c[1][0] = 1
c[1][1] = 1
for x in range(2, 51):
    for y in range(x + 1):
        c[x][y] = c[x - 1][y - 1] + c[x - 1][y]
d = [[[[0, float('inf')] for l in range(2)] for i in range(c100 + 1)] for j in range(c50 + 1)]
# d[i][j][c] ответ, когда мы переправили i по 50 кг и j по 100 кг и лодка на берегу c
d[0][0][0][0] = 1
d[0][0][0][1] = 0
q = deque()
q.append([0, 0, 0])
while len(q) > 0:
    i, j, shore = q.popleft()
    for fifty in range(c50 - i + 1 if shore == 0 else i + 1):
        for hundreds in range(c100 - j + 1 if shore == 0 else j + 1):
            if fifty * 50 + hundreds * 100 > k or fifty + hundreds == 0:
                continue
            i1 = i + fifty if shore == 0 else i - fifty
            j1 = j + hundreds if shore == 0 else j - hundreds
            if d[i1][j1][1 ^ shore][1] > d[i][j][shore][1] + 1:
                d[i1][j1][1 ^ shore][1] = d[i][j][shore][1] + 1
                d[i1][j1][1 ^ shore][0] = 0
                q.append((i1, j1, 1 ^ shore))
            if d[i1][j1][1 ^ shore][1] < d[i][j][shore][1] + 1:
                continue
            koeff = (c[c50 - i][fifty] if shore == 0 else c[i][fifty]) * (
                c[c100 - j][hundreds] if shore == 0 else c[j][hundreds])
            d[i1][j1][1 ^ shore][0] += d[i][j][shore][0] * koeff
            d[i1][j1][1 ^ shore][0] %= 10 ** 9 + 7
if d[c50][c100][1][1] == float('inf'):
    print(-1)
    print(0)
else:
    print(d[c50][c100][1][1])
    print(d[c50][c100][1][0])


I found an interesting problem on https://codeforces.com/problemset/problem/296/A:
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.

Help Yaroslav.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000) — the array elements.

-----Output-----

In the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.

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

Output
YES

Input
3
1 1 2

Output
YES

Input
4
7 7 7 7

Output
NO

-----Note-----

In the first sample the initial array fits well.

In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.

In the third sample Yarosav can't get the array he needs.

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

n = int(input())
c = {}
for x in (int(x) for x in input().split()):
    c[x] = 1 if x not in c else c[x] + 1
val = sum(1 for x in c if c[x] > (n + 1) // 2)
print('NO' if val else 'YES')


I found an interesting problem on https://codeforces.com/problemset/problem/296/B:
Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≤ i, j ≤ n), such that s_{i} > w_{i} and s_{j} < w_{j}. Here sign s_{i} represents the i-th digit of string s, similarly, w_{j} represents the j-th digit of string w.

A string's template is a string that consists of digits and question marks ("?").

Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers.

Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (10^9 + 7).

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5) — the length of both templates. The second line contains the first template — a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format.

-----Output-----

In a single line print the remainder after dividing the answer to the problem by number 1000000007 (10^9 + 7).

-----Examples-----
Input
2
90
09

Output
1

Input
2
11
55

Output
0

Input
5
?????
?????

Output
993531194

-----Note-----

The first test contains no question marks and both strings are incomparable, so the answer is 1.

The second test has no question marks, but the given strings are comparable, so the answer is 0.

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

from functools import reduce

n = int(input())

s1, s2 = str(input()), str(input())

b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False)

b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False)

s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)])

ans1 = reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (ord(s2[i]) - ord('0') + 1) if s1[i] == '?' else (10 - ord(s1[i]) + ord('0')) if s2[i] == '?' else 1 for i in range(n)], 1)

ans2 = reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (10 - ord(s2[i]) + ord('0')) if s1[i] == '?' else (ord(s1[i]) - ord('0')) + 1 if s2[i] == '?' else 1 for i in range(n)], 1)

ans3 = reduce(lambda x, y: (x * y) % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)

print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and not b2) * ans3) % 1000000007)

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/298/B:
The polar bears are going fishing. They plan to sail from (s_{x}, s_{y}) to (e_{x}, e_{y}). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1).

Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (e_{x}, e_{y})?

-----Input-----

The first line contains five integers t, s_{x}, s_{y}, e_{x}, e_{y} (1 ≤ t ≤ 10^5,  - 10^9 ≤ s_{x}, s_{y}, e_{x}, e_{y} ≤ 10^9). The starting location and the ending location will be different.

The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

-----Output-----

If they can reach (e_{x}, e_{y}) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

-----Examples-----
Input
5 0 0 1 1
SESNW

Output
4

Input
10 5 3 3 6
NENSWESNEE

Output
-1

-----Note-----

In the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.

In the second sample, they cannot sail to the destination.

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

t, sx, sy, ex, ey = map(int, input().split())
d = {'W':max(0, sx - ex), 'E':max(0, ex - sx), 'N':max(0, ey - sy), 'S':max(0, sy - ey)}
for (i, c) in enumerate(input(), 1):
  if d[c] > 0:
    d[c] -= 1
  if any(d.values()) == False:
    print(i)
    break
else:
  print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/299/A:
Ksusha is a beginner coder. Today she starts studying arrays. She has array a_1, a_2, ..., a_{n}, consisting of n positive integers.

Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!

-----Input-----

The first line contains integer n (1 ≤ n ≤ 10^5), showing how many numbers the array has. The next line contains integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the array elements.

-----Output-----

Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1.

If there are multiple answers, you are allowed to print any of them.

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

Output
2

Input
5
2 1 3 1 6

Output
1

Input
3
2 3 5

Output
-1

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

from sys import stdin
def read(): return list(map(int, stdin.readline().split()))

read()
a = list(read())
x = min(a)
for y in a:
  if y % x != 0:
    x = -1
    break

print(x)


I found an interesting problem on https://codeforces.com/problemset/problem/299/B:
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1.

Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.

Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k.

Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?

-----Input-----

The first line contains two integers n and k (2 ≤ n ≤ 3·10^5, 1 ≤ k ≤ 3·10^5). The next line contains n characters — the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#".

It is guaranteed that the first and the last characters equal ".".

-----Output-----

Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).

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

Output
YES

Input
5 2
.#.#.

Output
YES

Input
7 3
.#.###.

Output
NO

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

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

print("NO" if "#"*k in input() else "YES")


I found an interesting problem on https://codeforces.com/problemset/problem/300/A:
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:

  The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set.

Help Vitaly. Divide the given array.

-----Input-----

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10^3) — the array elements.

-----Output-----

In the first line print integer n_1 (n_1 > 0) — the number of elements in the first set. Then print n_1 numbers — the elements that got to the first set.

In the next line print integer n_2 (n_2 > 0) — the number of elements in the second set. Then print n_2 numbers — the elements that got to the second set.

In the next line print integer n_3 (n_3 > 0) — the number of elements in the third set. Then print n_3 numbers — the elements that got to the third set.

The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

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

Output
1 -1
1 2
1 0

Input
4
-1 -2 -3 0

Output
1 -1
2 -3 -2
1 0

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

# coding: utf-8
n = int(input())
a = []
b = []
c = []
for i in input().split():
    i = int(i)
    if i < 0:
        a.append(i)
    elif i == 0:
        b.append(i)
    else:
        c.append(i)
if len(c) == 0:
    c.append(a.pop())
    c.append(a.pop())
if len(a)%2==0:
    b.append(a.pop())
print(len(a),' '.join([str(i) for i in a]))
print(len(c),' '.join([str(i) for i in c]))
print(len(b),' '.join([str(i) for i in b]))


I found an interesting problem on https://codeforces.com/problemset/problem/300/C:
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number.

For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't.

Now Vitaly is wondering, how many excellent numbers of length exactly n are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (10^9 + 7).

A number's length is the number of digits in its decimal representation without leading zeroes.

-----Input-----

The first line contains three integers: a, b, n (1 ≤ a < b ≤ 9, 1 ≤ n ≤ 10^6).

-----Output-----

Print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7).

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

Output
1

Input
2 3 10

Output
165

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

ans = 0
mod = 1000000007
a, b, n = map(int, input().split())
s = set()
for x in range(2, 1 << 8):
    z = 0
    while x > 1:
        z = z * 10 + (a, b)[x & 1]
        x >>= 1
    s.add(z)
f = [1] * (n + 1)
for i in range(1, n + 1):
    f[i] = f[i - 1] * i % mod
for x in range(n + 1):
    if x * a + (n - x) * b in s:
        ans += pow(f[x] * f[n - x], mod - 2, mod)
        ans %= mod
print(ans * f[n] % mod)


I found an interesting problem on https://codeforces.com/problemset/problem/301/A:
Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.

Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?

Help Yaroslav.

-----Input-----

The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

-----Output-----

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

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

Output
150

Input
2
-1 -100 -1

Output
100

-----Note-----

In the first sample you do not need to change anything. The sum of elements equals 150.

In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.

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

n = int(input())

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

c = list(map(abs, a))

if len(list(filter(lambda x: x < 0, a))) & 1 and n + 1 & 1:

  print(sum(c) - 2 * min(c))

else:

  print(sum(c))


I found an interesting problem on https://codeforces.com/problemset/problem/302/A:
Eugeny has array a = a_1, a_2, ..., a_{n}, consisting of n integers. Each integer a_{i} equals to -1, or to 1. Also, he has m queries:  Query number i is given as a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n).  The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum a_{l}_{i} + a_{l}_{i} + 1 + ... + a_{r}_{i} = 0, otherwise the response to the query will be integer 0.

Help Eugeny, answer all his queries.

-----Input-----

The first line contains integers n and m (1 ≤ n, m ≤ 2·10^5). The second line contains n integers a_1, a_2, ..., a_{n} (a_{i} = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n).

-----Output-----

Print m integers — the responses to Eugene's queries in the order they occur in the input.

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

Output
0
1
0

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

Output
0
1
0
1
0

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

n, m = map(int, input().split())
a_plus = input().split().count('1')
a_min = min(a_plus, n - a_plus) * 2
res = []
for i in range(m):
    l, r = map(int, input().split())
    length = r - l + 1
    res += ['0'] if length % 2 or length > a_min else ['1']
print('\n'.join(res))


I found an interesting problem on https://codeforces.com/problemset/problem/302/B:
Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of t_{i} minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i c_{i} times. Eugeny's play list is organized as follows: first song number 1 plays c_1 times, then song number 2 plays c_2 times, ..., in the end the song number n plays c_{n} times.

Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.

Help Eugeny and calculate the required numbers of songs.

-----Input-----

The first line contains two integers n, m (1 ≤ n, m ≤ 10^5). The next n lines contain pairs of integers. The i-th line contains integers c_{i}, t_{i} (1 ≤ c_{i}, t_{i} ≤ 10^9) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 10^9 $(\sum_{i = 1}^{n} c_{i} \cdot t_{i} \leq 10^{9})$.

The next line contains m positive integers v_1, v_2, ..., v_{m}, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time v_{i}, when the music doesn't play any longer. It is guaranteed that v_{i} < v_{i} + 1 (i < m).

The moment of time v_{i} means that Eugeny wants to know which song was playing during the v_{i}-th munite from the start of listening to the playlist.

-----Output-----

Print m integers — the i-th number must equal the number of the song that was playing during the v_{i}-th minute after Eugeny started listening to the play list.

-----Examples-----
Input
1 2
2 8
1 16

Output
1
1

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

Output
1
1
2
2
3
4
4
4
4

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

import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return list(map(int, minp().split()))

n, m = mints()
a = [0]
s = 0
for i in range(n):
	c,t = mints()
	s += c*t
	a.append(s)
j = 0
for i in mints():
	while not (i-1 >= a[j] and i-1 < a[j+1]):
		j += 1
	print(j+1)


I found an interesting problem on https://codeforces.com/problemset/problem/303/A:
Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.

A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if $\forall i(1 \leq i \leq n), a_{i} + b_{i} \equiv c_{i} \operatorname{mod} n$. The sign a_{i} denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing a_{i} + b_{i} by n and dividing c_{i} by n are equal.

Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?

-----Input-----

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

-----Output-----

If no Lucky Permutation Triple of length n exists print -1.

Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line — permutation b, the third — permutation c.

If there are multiple solutions, print any of them.

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

Output
1 4 3 2 0
1 0 2 4 3
2 4 0 1 3

Input
2

Output
-1

-----Note-----

In Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds:  $1 + 1 \equiv 2 \equiv 2 \operatorname{mod} 5$;  $4 + 0 \equiv 4 \equiv 4 \operatorname{mod} 5$;  $3 + 2 \equiv 0 \equiv 0 \operatorname{mod} 5$;  $2 + 4 \equiv 6 \equiv 1 \operatorname{mod} 5$;  $0 + 3 \equiv 3 \equiv 3 \operatorname{mod} 5$.

In Sample 2, you can easily notice that no lucky permutation triple exists.

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

n = int(input())
if n % 2 == 0:
  print(-1)
else:
  print(*range(n))
  print(*range(n))
  print(*map(lambda x: x * 2 % n, range(n)))


I found an interesting problem on https://codeforces.com/problemset/problem/303/B:
You are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers (x, y) (0 ≤ x ≤ n, 0 ≤ y ≤ m).

Your task is to find a maximum sub-rectangle on the grid (x_1, y_1, x_2, y_2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 ≤ x_1 ≤ x ≤ x_2 ≤ n, 0 ≤ y_1 ≤ y ≤ y_2 ≤ m, $\frac{x_{2} - x_{1}}{y_{2} - y_{1}} = \frac{a}{b}$.

The sides of this sub-rectangle should be parallel to the axes. And values x_1, y_1, x_2, y_2 should be integers. [Image]

If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x_1, y_1, x_2, y_2), so we can choose the lexicographically minimum one.

-----Input-----

The first line contains six integers n, m, x, y, a, b (1 ≤ n, m ≤ 10^9, 0 ≤ x ≤ n, 0 ≤ y ≤ m, 1 ≤ a ≤ n, 1 ≤ b ≤ m).

-----Output-----

Print four integers x_1, y_1, x_2, y_2, which represent the founded sub-rectangle whose left-bottom point is (x_1, y_1) and right-up point is (x_2, y_2).

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

Output
1 3 9 7

Input
100 100 52 50 46 56

Output
17 8 86 92

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/304/A:
In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:

 In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).

The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the Pythagorean equation:

a^2 + b^2 = c^2

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides.

 [Image]

Given n, your task is to count how many right-angled triangles with side-lengths a, b and c that satisfied an inequality 1 ≤ a ≤ b ≤ c ≤ n.

-----Input-----

The only line contains one integer n (1 ≤ n ≤ 10^4) as we mentioned above.

-----Output-----

Print a single integer — the answer to the problem.

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

Output
1

Input
74

Output
35

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

from math import gcd

n = int(input())
k = 0
num = n*n
for a in range(2, int((n+1)**0.5)+2):
  for b in range((a&1)+1, a, 2):
    z = (a**2 + b**2)
    if z > num:
      break
    if gcd(a, b) == 1:
      k += int(n/z)
print(k)