I found an interesting problem on https://codeforces.com/problemset/problem/767/A:
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.

Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. [Image]

However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.

Write a program that models the behavior of Ankh-Morpork residents.

-----Input-----

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.

The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

-----Output-----

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

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

Output
3

2 1
Input
5
4 5 1 2 3

Output

5 4

3 2 1

-----Note-----

In the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

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

n = int(input())
arr = [0]+list(map(int, input().split()))
came = [False]*(n+2)
put = [False]*(n+2)
put[n+1], came[n+1] = True, True
for i in range(1,n+1):
	if put[arr[i]+1] == True:
		put[arr[i]] = True
		print(arr[i],end = ' ')
		k = arr[i]-1
		while came[k]:
			put[k] = True
			print(k,end = ' ')
			k -= 1
		print()
	else:
		came[arr[i]] = True
		print()


I found an interesting problem on https://codeforces.com/problemset/problem/767/B:
Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.

He knows that the receptionist starts working after t_{s} minutes have passed after midnight and closes after t_{f} minutes have passed after midnight (so that (t_{f} - 1) is the last minute when the receptionist is still working). The receptionist spends exactly t minutes on each person in the queue. If the receptionist would stop working within t minutes, he stops serving visitors (other than the one he already serves).

Vasya also knows that exactly n visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately. [Image] "Reception 1"

For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.

Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!

-----Input-----

The first line contains three integers: the point of time when the receptionist begins to work t_{s}, the point of time when the receptionist stops working t_{f} and the time the receptionist spends on each visitor t. The second line contains one integer n — the amount of visitors (0 ≤ n ≤ 100 000). The third...

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

s, e, t_per_v = list(map(int, input().split()))
e -= t_per_v
n = int(input())
if n > 0:
    visitors = list(map(int, input().split()))
else:
    visitors=[]

min_wait_time = float("inf")
min_arrive_time = -1
visitor_index = 0
t = s
while t <= e:
    # print(t, visitor_index)
    if visitor_index >= len(visitors) or visitors[visitor_index] > t:
        print(t)
        return
    wait_time = t - visitors[visitor_index]
    if wait_time < min_wait_time:
        min_wait_time = wait_time
        min_arrive_time = visitors[visitor_index]
    t += t_per_v
    visitor_index += 1
print(min_arrive_time - 1)


I found an interesting problem on https://codeforces.com/problemset/problem/768/A:
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.

With that begins the watch of Jon Snow. He is assigned the task to support the stewards.

This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.

Can you find how many stewards will Jon support?

-----Input-----

First line consists of a single integer n (1 ≤ n ≤ 10^5) — the number of stewards with Jon Snow.

Second line consists of n space separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) representing the values assigned to the stewards.

-----Output-----

Output a single integer representing the number of stewards which Jon will feed.

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

Output
0
Input
3
1 2 5

Output
1

-----Note-----

In the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.

In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

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

n = int(input())
k = list(map(int, input().split()))
mn = min(k)
mx = max(k)
ans = 0
for i in k:
    if (mn != i != mx):
        ans += 1
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/768/B:
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility.

Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position $\lfloor \frac{x}{2} \rfloor$, $x \operatorname{mod} 2$, $\lfloor \frac{x}{2} \rfloor$ sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.

Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?

-----Input-----

The first line contains three integers n, l, r (0 ≤ n < 2^50, 0 ≤ r - l ≤ 10^5, r ≥ 1, l ≥ 1) – initial element and the range l to r.

It is guaranteed that r is not greater than the length of the final list.

-----Output-----

Output the total number of 1s in the range l to r in the final sequence.

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

Output
4

Input
10 3 10

Output
5

-----Note-----

Consider first example:

$[ 7 ] \rightarrow [ 3,1,3 ] \rightarrow [ 1,1,1,1,3 ] \rightarrow [ 1,1,1,1,1,1,1 ] \rightarrow [ 1,1,1,1,1,1,1 ]$

Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4.

For the second example:

$[ 10 ] \rightarrow [ 1,0,1,1,1,0,1,0,1,0,1,1,1,0,1 ]$

Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5.

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

from math import log2

n, l, r = list(map(int, input().split()))
bn = list(map(int, list(bin(n)[2:])))
ans = 0
for i in range(l, r + 1):
    ans += bn[int(log2(i & -i))]
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/768/C:
Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number x, he might get soldiers of high strength. So, he decided to do the following operation k times:

 Arrange all the rangers in a straight line in the order of increasing strengths.

 Take the bitwise XOR (is written as $\oplus$) of the strength of each alternate ranger with x and update it's strength.

 Suppose, Jon has 5 rangers with strengths [9, 7, 11, 15, 5] and he performs the operation 1 time with x = 2. He first arranges them in the order of their strengths, [5, 7, 9, 11, 15]. Then he does the following:

 The strength of first ranger is updated to $5 \oplus 2$, i.e. 7.

 The strength of second ranger remains the same, i.e. 7.

 The strength of third ranger is updated to $9 \oplus 2$, i.e. 11.

 The strength of fourth ranger remains the same, i.e. 11.

 The strength of fifth ranger is updated to $15 \oplus 2$, i.e. 13.

 The new strengths of the 5 rangers are [7, 7, 11, 11, 13]

Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations k times. He wants your help for this task. Can you help him?

-----Input-----

First line consists of three integers n, k, x (1 ≤ n ≤ 10^5, 0 ≤ k ≤ 10^5, 0 ≤ x ≤ 10^3) — number of rangers Jon has, the number of times Jon will carry out the operation and Jon's favourite number respectively.

Second line consists of n integers representing the strengths of the rangers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^3).

-----Output-----

Output two integers, the maximum and the minimum strength of the rangers after performing the operation k times.

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

Output
13 7
Input
2 100000...

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

#!/usr/bin/env python3
from sys import stdin,stdout

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

n, k, x = ri()
a = []
a.append(list(ri()))

t = 0
j = 0
goout = 0
for j in range(0,k):
    a[j].sort()
    if j != 0:
        for t in range(j):
            if a[t] == a[j]:
                goout = 1
                break
    if goout:
        break
    a.append([a[j][i]^x if not i%2 else a[j][i] for i in range(n)])
else:
    a[k].sort()
    print(a[k][-1], a[k][0])
    return

m = t + (k-t)%(j-t)
print(a[m][-1], a[m][0])


I found an interesting problem on https://codeforces.com/problemset/problem/768/F:
Tarly has two different type of items, food boxes and wine barrels. There are f food boxes and w wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two stacks of wine barrels are together.

The height of a stack is defined as the number of items in the stack. Two stacks are considered different if either their heights are different or one of them contains food and other contains wine.

Jon Snow doesn't like an arrangement if any stack of wine barrels has height less than or equal to h. What is the probability that Jon Snow will like the arrangement if all arrangement are equiprobably?

Two arrangement of stacks are considered different if exists such i, that i-th stack of one arrangement is different from the i-th stack of the other arrangement.

-----Input-----

The first line of input contains three integers f, w, h (0 ≤ f, w, h ≤ 10^5) — number of food boxes, number of wine barrels and h is as described above. It is guaranteed that he has at least one food box or at least one wine barrel.

-----Output-----

Output the probability that Jon Snow will like the arrangement. The probability is of the form [Image], then you need to output a single integer p·q^{ - 1} mod (10^9 + 7).

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

Output
0

Input
1 2 1

Output
666666672

-----Note-----

In the first example f  =  1, w = 1 and h = 1, there are only two possible arrangement of stacks and Jon Snow doesn't like any of them.

In the second example f = 1, w = 2 and h = 1, there are three arrangements. Jon Snow likes the (1) and (3) arrangement. So the probabilty is $\frac{2}{3}$. [Image]

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

import sys
def factorial():
    nonlocal mod
    fac = [1] * int(3e5 + 1)
    for i in range(1, int(3e5)):
        fac[i] = i*fac[i-1] % mod
    return fac
def inverse(x):
    nonlocal mod
    return pow(x, mod-2, mod)
def C(n, r):
    nonlocal fac
    if n < 0 or n < r:
        return 0
    return fac[n]*inverse(fac[r])*inverse(fac[n-r]) % mod
def calc(f, w, h):
    nonlocal mod
    if w == 0:
        return 1
    ans = 0
    for k in range(1, min(w//(h+1),f+1)+1):
        ans += C(f+1, k) * C(w-k*h-1, k-1) % mod
        ans %= mod
    return ans
f, w, h = list(map(int,sys.stdin.readline().split(' ')))
mod = int(1e9 + 7)
fac = factorial()
cnt = calc(f, w, h)
sys.stdout.write(str(cnt*inverse(C(f+w, w)) % mod))


I found an interesting problem on https://codeforces.com/problemset/problem/769/A:
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university.

Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than x from the year of university entrance of this student, where x — some non-negative integer. A value x is not given, but it can be uniquely determined from the available data. Note that students don't join other groups.

You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.

-----Input-----

The first line contains the positive odd integer n (1 ≤ n ≤ 5) — the number of groups which Igor joined.

The next line contains n distinct integers a_1, a_2, ..., a_{n} (2010 ≤ a_{i} ≤ 2100) — years of student's university entrance for each group in which Igor is the member.

It is guaranteed that the input data is correct and the answer always exists. Groups are given randomly.

-----Output-----

Print the year of Igor's university entrance.

-----Examples-----
Input
3
2014 2016 2015

Output
2015

Input
1
2050

Output
2050

-----Note-----

In the first test the value x = 1. Igor entered the university in 2015. So he joined groups members of which are students who entered the university in 2014, 2015 and 2016.

In the second test the value x = 0. Igor entered only the group which corresponds to the year of his university entrance.

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

n=int(input())
a=[int(i) for i in input().split()]
a.sort()
print(a[n//2])


I found an interesting problem on https://codeforces.com/problemset/problem/769/B:
Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".

Not all students are equally sociable. About each student you know the value a_{i} — the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself.

In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages.

Your task is to make a plan of using private messages, so that:

  the student i sends no more than a_{i} messages (for all i from 1 to n);  all students knew the news about the credit (initially only Polycarp knew it);  the student can inform the other student only if he knows it himself.

Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.

In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.

-----Input-----

The first line contains the positive integer n (2 ≤ n ≤ 100) — the number of students.

The second line contains the sequence a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 100), where a_{i} equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.

-----Output-----

Print -1 to the first line if it is impossible to inform all students about credit.

Otherwise, in the first line print the integer k — the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can...

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

'''
def send_message(student):
	nonlocal data, last_student_that_knows, student_that_sends, number_of_messages, output
	for i in range(data[student]):
		if last_student_that_knows == amount_of_students - 1:
			break
		last_student_that_knows += 1
		number_of_messages += 1
		output.append("{0} {1}".format(student + 1, last_student_that_knows + 1))
		send_message(last_student_that_knows)
'''
############################################
amount_of_students = int(input())
data = input().split(" ")
students = []
for i in range(len(data)):
	data[i] = int(data[i])
	students.append(0)
students[0] = 1 #Поликарп знает
############################################

def max_unaware_student():
	nonlocal data, students, number_of_messages, output
	max = -1
	student = -1
	for i in range(len(data)):
		if data[i] > max and students[i] == 0: #если этот студент отправляет больше и он ещё не знает
			max = data[i]
			student = i
	return student

def send_message(student):
	nonlocal data, students, number_of_messages, output
	for i in range(data[student]):
		if min(students) == 1: #если незнающие кончились
			break
		number_of_messages += 1
		recipient = max_unaware_student()
		output.append("{0} {1}".format(student + 1, recipient + 1))
		students[recipient] = 1
		send_message(recipient)

output = []
number_of_messages = 0

send_message(0)

if min(students) == 0:
	print("-1")

else:
	print(number_of_messages)
	for i in output:
		print (i)


I found an interesting problem on https://codeforces.com/problemset/problem/769/C:
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.

Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).

Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".

In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.

-----Input-----

The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10^6) — the size of the maze and the length of the cycle.

Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.

-----Output-----

Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).

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

Output
RL

Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.

Output
DLDDLLLRRRUURU

Input
3 3 4
***
*X*
***

Output
IMPOSSIBLE

-----Note-----

In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less....

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

import math
from collections import deque

def main():
	n, m, k = list(map(int, input().split()))
	grid = ["" for _ in range(n)]
	x, y = 0, 0

	for i in range(n):
		grid[i] = input()
		if 'X' in grid[i]:
			x, y = i, grid[i].index('X')

	if k % 2 == 1:
		print("IMPOSSIBLE")
		return

	dx = [1, 0, 0, -1]
	dy = [0, -1, 1, 0]
	names = {(x1, y1): sym for x1, y1, sym in zip(dx, dy, "DLRU")}
	rev_names = {x1: y1 for x1, y1 in zip("DLRU", "URLD")}

	def ok(x, y):
		return (0 <= x < n) and (0 <= y < m) and grid[x][y] != '*'

	def bfs(x, y):
		MAX_DIST = (1 << 20)
		dist = [[MAX_DIST for y in range(m)] for x in range(n)]
		dist[x][y] = 0
		q = deque()
		q.append((x, y))

		while len(q) > 0:
			x, y = q.popleft()

			for x0, y0 in zip(dx, dy):
				if ok(x + x0, y + y0) and dist[x][y] + 1 < dist[x + x0][y + y0]:
					dist[x + x0][y + y0] = dist[x][y] + 1
					q.append((x + x0, y + y0))

		return dist

	path = []
	x_start, y_start = x, y

	dist = bfs(x_start, y_start)

	for i in range(k // 2):
		for x1, y1 in zip(dx, dy):
			if ok(x + x1, y + y1):
				path.append(names.get((x1, y1)))
				x += x1
				y += y1
				break
		else:
			print("IMPOSSIBLE")
			return

	moves = k // 2
	for i in range(k // 2):
		for x1, y1 in zip(dx, dy):
			if ok(x + x1, y + y1) and dist[x + x1][y + y1] <= moves:
				path.append(names.get((x1, y1)))
				x += x1
				y += y1
				moves -= 1
				break

	print("".join(x for x in path))

def __starting_point():
	main()

# Made By Mostafa_Khaled

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/769/D:
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.

Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers a_{i} and a_{j} is k-interesting. Your task is to help Vasya and determine this number.

-----Input-----

The first line contains two integers n and k (2 ≤ n ≤ 10^5, 0 ≤ k ≤ 14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ.

The second line contains the sequence a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^4), which Vasya has.

-----Output-----

Print the number of pairs (i, j) so that i < j and the pair of integers a_{i} and a_{j} is k-interesting.

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

Output
4

Input
6 0
200 100 100 100 200 200

Output
6

-----Note-----

In the first test there are 4 k-interesting pairs:  (1, 3),  (1, 4),  (2, 3),  (2, 4).

In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs:  (1, 5),  (1, 6),  (2, 3),  (2, 4),  (3, 4),  (5, 6).

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

def binary(n):
    curr=0
    while(n>0):
        if(n%2):
            curr+=1
        n=n//2
    return curr
l=input().split()
n=int(l[0])
k=int(l[1])
l=input().split()
li=[int(i) for i in l]
arr=[]
for i in range(2**15):
    if(binary(i)==k):
        arr.append(i)
hashi=dict()
for i in li:
    if i in hashi:
        hashi[i]+=1
    else:
        hashi[i]=1
count=0
for i in hashi:
    for j in arr:
        if((i^j) in hashi):
            if((i^j)==i):
                count=count+(hashi[i]*(hashi[i]-1))
            else:
                count=count+(hashi[i]*hashi[i^j])
print(count//2)


I found an interesting problem on https://codeforces.com/problemset/problem/770/A:
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.

Innokentiy decides that new password should satisfy the following conditions:  the length of the password must be equal to n,  the password should consist only of lowercase Latin letters,  the number of distinct symbols in the password must be equal to k,  any two consecutive symbols in the password must be distinct.

Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions.

-----Input-----

The first line contains two positive integers n and k (2 ≤ n ≤ 100, 2 ≤ k ≤ min(n, 26)) — the length of the password and the number of distinct symbols in it.

Pay attention that a desired new password always exists.

-----Output-----

Print any password which satisfies all conditions given by Innokentiy.

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

Output
java

Input
6 6

Output
python

Input
5 2

Output
phphp

-----Note-----

In the first test there is one of the appropriate new passwords — java, because its length is equal to 4 and 3 distinct lowercase letters a, j and v are used in it.

In the second test there is one of the appropriate new passwords — python, because its length is equal to 6 and it consists of 6 distinct lowercase letters.

In the third test there is one of the appropriate new passwords — phphp, because its length is equal to 5 and 2 distinct lowercase letters p and h are used in it.

Pay attention the condition that no two identical symbols are consecutive is correct for all appropriate passwords in tests.

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

n, k = input().split()
n, k = int(n), int(k)
s = []
for i in range(n):
	s.append(chr((i % k + ord('a'))))
print(''.join(s))


I found an interesting problem on https://codeforces.com/problemset/problem/770/B:
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.

Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.

-----Input-----

The first line contains the positive integer x (1 ≤ x ≤ 10^18) — the integer which Anton has.

-----Output-----

Print the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros.

-----Examples-----
Input
100

Output
99

Input
48

Output
48

Input
521

Output
499

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

def sum_n(n):
    l = len(n)

    summ = 0
    for i in range(l):
        summ += int(n[i])

    return summ

def transfer(x, i):
    x = list(x)

    x[i+1] = '9'
    if x[i] != '0':
        x[i] = str(int(x[i])-1)
    else:
        j = i
        while (j > 0) and (int(x[j]) == 0):
            x[j] = '9'
            j -= 1
        x[j] = str(int(x[j])-1)
    if (x[0] == '0'):
        del x[0]

    return x

x = list(input())
max_cifr = sum_n(x)
maxnum = x
res = ''

for i in range(len(x)-2, -1, -1):
    x = transfer(x, i)
    if(max_cifr < sum_n(x)):
        max_cifr = sum_n(x)
        maxnum = x

for i in range(len(maxnum)):
    res = res+maxnum[i]

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/770/C:
Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.

The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).

Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses.

Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.

-----Input-----

The first line contains n and k (1 ≤ k ≤ n ≤ 10^5) — the number of online-courses and the number of main courses of Polycarp's specialty.

The second line contains k distinct integers from 1 to n — numbers of main online-courses of Polycarp's specialty.

Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer t_{i} (0 ≤ t_{i} ≤ n - 1) — the number of courses on which the i-th depends. Then there follows the sequence of t_{i} distinct integers from 1 to n — numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself.

It is guaranteed that the sum of all values t_{i} doesn't exceed 10^5.

-----Output-----

Print -1, if there is no the way to get a specialty.

Otherwise, in the first line print the integer m — the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers — numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them.

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

Output
5
1 2 3 4 5

Input
9 3
3 9 5
0
0
3 9 4 5
0
0
1 8
1...

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

# https://codeforces.com/problemset/problem/770/C
n, k = list(map(int, input().split()))
K    = set(list(map(int, input().split())))
g    = {}
rg   = {}
deg  = {}

def push_d(deg, u, val):
    if u not in deg:
        deg[u] = 0
    deg[u] += val

def push_g(g, u, v):
    if u not in g:
        g[u] = []
    g[u].append(v)

for u in range(1, n+1):
    list_v = list(map(int, input().split()))[1:]
    deg[u] = 0

    for v in list_v:
        push_d(deg, u, 1)
        push_g(g,  v, u)
        push_g(rg, u, v)

S    = [x for x in K]
used = [0] * (n+1)
i = 0
while i<len(S):
    u = S[i]
    if u in rg:
        for v in rg[u]:
            if used[v] == 0:
                used[v] = 1
                S.append(v)
    i+=1

S    = {x:1 for x in S}
deg0 = [x for x in S if deg[x]==0]
ans  = []

def process(g, deg, deg0, u):
    if u in g:
        for v in g[u]:
            if v in S:
                push_d(deg, v, -1)

                if deg[v] == 0:
                    deg0.append(v)

while len(deg0) > 0 and len(K) > 0:
    u = deg0.pop()
    ans.append(u)

    if u in K:
        K.remove(u)

    process(g, deg, deg0, u)

if len(K) > 0:
    print(-1)
else:
    print(len(ans))
    print(' '.join([str(x) for x in ans]))

#6 2
#5 6
#0
#1 1
#1 4 5
#2 2 1
#1 4
#2 5 3


I found an interesting problem on https://codeforces.com/problemset/problem/770/D:
A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular.

Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as:

+-        -++- -+

|+- -++- -+||   |

||   ||   |||   |

|+- -++- -+||   |

+-        -++- -+

Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.

Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height.

The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.

Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.

-----Input-----

The first line contains an even integer n (2 ≤ n ≤ 100) — the length of the sequence of brackets.

The second line contains the sequence of brackets — these are n symbols "[" and "]". It is guaranteed that the given sequence of brackets is regular.

-----Output-----

Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces.

-----Examples-----
Input
8
[[][]][]

Output
+-        -++- -+
|+- -++- -+||   |
||   ||   |||   |
|+- -++- -+||   |
+-        -++- -+

Input
6
[[[]]]

Output
+-     -+
|+-   -+|
||+-...

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

def Paint(height,napr):
   return ''
rngOfseq=int(input())
seq=input()
maxh=3
heightes=[]
current=1
tek=3
for i in range(rngOfseq-1):#maxh
    if seq[i]=='[' and seq[i+1]=='[':
        tek+=2
    if seq[i]==']' and seq[i+1]==']':
        tek-=2
    if maxh<tek:
        maxh=tek
current=maxh
for i in range(rngOfseq-1):#heightes
    heightes.append(current)
    if seq[i]=='[' and seq[i+1]=='[':
        current-=2
    if seq[i]==']' and seq[i+1]==']':
        current+=2
heightes.append(current)
current=maxh
Flag=True
for j in range(maxh):#draw
    currentraw=''
    for i in range(rngOfseq):
        if heightes[i]==current:
            if seq[i]=='[':
                currentraw+='+-'
            else:
                currentraw+='-+'
        elif heightes[i]>current:
            currentraw+='|'
        else:
            currentraw+=' '
        try:
            if heightes[i]==heightes[i+1]:
                if heightes[i]==current:
                    if seq[i] =='[' and seq[i+1]==']':
                        currentraw+=' '
                elif heightes[i]<current:
                    if seq[i] ==']' and seq[i+1]=='[':
                        currentraw+='  '
                    if seq[i] =='[' and seq[i+1]==']':
                        currentraw+=' '
                else:
                    if seq[i] =='[' and seq[i+1]==']':
                        currentraw+='   '
        except:
            continue
    if current==1:
        Flag=False
    if Flag:
        current-=2
    else:
        current+=2
    print(currentraw)


I found an interesting problem on https://codeforces.com/problemset/problem/771/A:
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).

There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.

Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.

For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.

Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.

-----Input-----

The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, $0 \leq m \leq \operatorname{min}(150000, \frac{n \cdot(n - 1)}{2})$) — the number of members and the number of pairs of members that are friends.

The i-th of the next m lines contains two distinct integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}). Members a_{i} and b_{i} are friends with each other. No pair of members will appear more than once in the input.

-----Output-----

If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).

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

Output
YES

Input
4 4
3 1
2 3
3 4
1 2

Output
NO

Input
10 4
4 3
5 10
8 9
1 2

Output
YES

Input
3 2
1 2
2 3

Output
NO

-----Note-----

The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.

 [Image]

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

from sys import *
f = lambda: map(int, stdin.readline().split())
n, m = f()
g = [[i] for i in range(n + 1)]
for j in range(m):
    u, v = f()
    g[u].append(v)
    g[v].append(u)
k = 'YES'
for t in g: t.sort()
for t in g:
    s = len(t)
    if s > 1 and not all(g[x] == t for x in t):
        k = 'NO'
        break
    for j in t: g[j] = []
print(k)


I found an interesting problem on https://codeforces.com/problemset/problem/771/B:
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).

A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.

You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.

You managed to steal the general's notes, with n - k + 1 strings s_1, s_2, ..., s_{n} - k + 1, each either "YES" or "NO".   The string s_1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise).  The string s_2 describes a group of soldiers 2 through k + 1.  And so on, till the string s_{n} - k + 1 that describes a group of soldiers n - k + 1 through n.

Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print "Xyzzzdj" or "T" for example.

Find and print any solution. It can be proved that there always exists at least one solution.

-----Input-----

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 50) — the number of soldiers and the size of a group respectively.

The second line contains n - k + 1 strings s_1, s_2, ..., s_{n} - k + 1. The string s_{i} is "YES" if the group of soldiers i through i + k - 1 is effective, and "NO" otherwise.

-----Output-----

Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible...

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

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

r = []

name = "Aa"

def nextName():
	nonlocal name
	if name[-1] == 'z': name = name + 'a'
	else: name = name[:-1] + chr(ord(name[-1]) + 1)
	return name

for i in range(k-1):
	r.append(nextName())

for i in range(n-k+1):
	r.append(nextName() if s[i] else r[i])

print(*r)


I found an interesting problem on https://codeforces.com/problemset/problem/771/C:
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.

Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.

Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.

For a pair of vertices (s, t) we define f(s, t) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.

-----Input-----

The first line of the input contains two integers n and k (2 ≤ n ≤ 200 000, 1 ≤ k ≤ 5) — the number of vertices in the tree and the maximum allowed jump distance respectively.

The next n - 1 lines describe edges in the tree. The i-th of those lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n) — the indices on vertices connected with i-th edge.

It's guaranteed that the given edges form a tree.

-----Output-----

Print one integer, denoting the sum of f(s, t) over all pairs of vertices (s, t) such that s < t.

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

Output
20

Input
13 3
1 2
3 2
4 2
5 2
3 6
10 6
6 7
6 13
5 8
5 9
9 11
11 12

Output
114

Input
3 5
2 1
3 1

Output
3

-----Note-----

In the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). [Image]

There are $\frac{n \cdot(n - 1)}{2} = 15$ pairs of vertices (s, t) such that s < t. For 5 of those pairs Limak would need two jumps: (1, 6), (3, 4), (3, 5), (3, 6), (5, 6). For other 10 pairs one jump is enough. So, the answer is 5·2 + 10·1 = 20.

In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (s < t), so the answer is 3·1 = 3.

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

"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""

import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right

from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

from collections import defaultdict as dd, deque as dq,...


I found an interesting problem on https://codeforces.com/problemset/problem/772/A:
You have n devices that you want to use simultaneously.

The i-th device uses a_{i} units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·a_{i} units of power. The i-th device currently has b_{i} units of power stored. All devices can store an arbitrary amount of power.

You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.

You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.

If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.

-----Input-----

The first line contains two integers, n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 10^9) — the number of devices and the power of the charger.

This is followed by n lines which contain two integers each. Line i contains the integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 100 000) — the power of the device and the amount of power stored in the device in the beginning.

-----Output-----

If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.

Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 4}.

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

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

Output
2.0000000000
Input
1 100
1 1

Output
-1

Input
3 5
4 3
5 2
6 1

Output
0.5000000000

-----Note-----

In sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough...

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

from math import inf
n, p = [int(x) for x in input().split()]
l = []
for i in range(n):
    a, b = [int(x) for x in input().split()]
    l.append((a, b, b/a))
l.sort(key=lambda x: x[2])
asum = 0
bsum = 0
sumt = 0
for i in range(n):
    a0, b0, _ = l[i]
    c1 = inf if i == n-1 else l[i+1][2]
    asum += a0
    bsum += b0
    dp = asum - p
    if dp > 0:
        t = bsum / dp
        if t < c1:
            print(t)
            return
print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/772/B:
You are given a convex polygon P with n distinct vertices p_1, p_2, ..., p_{n}. Vertex p_{i} has coordinates (x_{i}, y_{i}) in the 2D plane. These vertices are listed in clockwise order.

You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.

Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.

-----Input-----

The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices.

The next n lines contain the coordinates of the vertices. Line i contains two integers x_{i} and y_{i} ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).

-----Output-----

Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.

Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.

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

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

Output
0.3535533906

Input
6
5 0
10 0
12 -4
10 -8
5 -8
3 -4

Output
1.0000000000

-----Note-----

Here is a picture of the first sample

[Image]

Here is an example of making the polygon non-convex.

[Image]

This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.

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

import math
from decimal import Decimal
n = int(input())
d = [[] for i in range(n)]
for i in range(n):
    d[i] = list(map(Decimal,input().split()))
def cnt(m):
    l = m - 1
    if (l < 0): l = n - 1
    r = (m + 1) % n
    lol = Decimal(2)
    a = ((d[l][0] - d[m][0])**lol + (d[l][1] - d[m][1]) ** 2)**(Decimal(1/2))
    b = ((d[m][0] - d[r][0]) ** lol + (d[m][1] - d[r][1]) ** 2)**(Decimal(1/2))
    c = ((d[l][0] - d[r][0]) ** lol + (d[l][1] - d[r][1]) ** 2)**(Decimal(1/2))
    p = (a + b + c) / lol
    s = (p * (p - a) * (p - b) * (p - c))**(Decimal(1/2))
    return Decimal(s / c)

ans = Decimal(cnt(0))
for i in range(0,n):
    ans = min(ans, cnt(i))
    # for j in range(0,n):
    #     if i == j :continue;
    #     cur = ((d[i][0] - d[j][0]) ** 2 + (d[i][1] - d[j][1]) ** 2) ** (1/2)
    #     ans = min(ans, cur / 2)

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/772/C:
You are given an integer m, and a list of n distinct integers between 0 and m - 1.

You would like to construct a sequence satisfying the properties:  Each element is an integer between 0 and m - 1, inclusive.  All prefix products of the sequence modulo m are distinct.  No prefix product modulo m appears as an element of the input list.  The length of the sequence is maximized.

Construct any sequence satisfying the properties above.

-----Input-----

The first line of input contains two integers n and m (0 ≤ n < m ≤ 200 000) — the number of forbidden prefix products and the modulus.

If n is non-zero, the next line of input contains n distinct integers between 0 and m - 1, the forbidden prefix products. If n is zero, this line doesn't exist.

-----Output-----

On the first line, print the number k, denoting the length of your sequence.

On the second line, print k space separated integers, denoting your sequence.

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

Output
5
1 2 4 3 0

Input
3 10
2 9 1

Output
6
3 9 2 9 8 0

-----Note-----

For the first case, the prefix products of this sequence modulo m are [1, 2, 3, 4, 0].

For the second case, the prefix products of this sequence modulo m are [3, 7, 4, 6, 8, 0].

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

import math

def gcdExtended(a, b):

    # Base Case
    if a == 0 :
        return b, 0, 1

    gcd, x1, y1 = gcdExtended(b%a, a)

    # Update x and y using results of recursive
    # call
    x = y1 - (b//a) * x1
    y = x1

    return gcd, x, y

def rev_elem(x, m):
    return (gcdExtended(x, m)[1] % m + m) % m

n, m = map(int, input().split())
a = []
if n > 0:
    a = [int(i) for i in input().split()]

banned = [False] * (m + 5)
for i in a:
    banned[i] = True

cycle = [[] for i in range(m + 5)]
d, dp, p = [], [], []
for i in range(m):
    cycle[math.gcd(m, i)].append(i)
cycle = [[i for i in j if not banned[i]] for j in cycle]

d = [i for i in range(1, m + 1) if m % i == 0]
dp = [len(cycle[i]) for i in d]
p = [-1 for i in d]
ans, lst = -1, -1

for i in range(len(d)):
    if dp[i] > ans:
        ans, lst = dp[i], i
    for j in range(i + 1, len(d)):
        if d[j] % d[i] != 0 or dp[j] > dp[i] + len(cycle[d[j]]):
            continue
        dp[j] = dp[i] + len(cycle[d[j]])
        p[j] = i
print(ans)

pos, dpos, pref = [], [], []
cur = lst
while cur != -1:
    dpos.append(d[cur])
    cur = p[cur]
dpos.reverse()

for i in dpos:
    pref += cycle[i]
cur = 1
for i in pref:
    ad = 1
    if math.gcd(i, m) != math.gcd(cur, m):
        ad = ((cur * math.gcd(i, m) // math.gcd(cur, math.gcd(i, m))) // cur) % m
    ncur = (cur * ad) % m
    ad *= i // math.gcd(ncur, m) * (rev_elem(ncur // math.gcd(ncur, m), m // math.gcd(ncur, m)))

    ad %= m
    cur = (cur * ad) % m

    pos.append(ad)

print(*pos)


I found an interesting problem on https://codeforces.com/problemset/problem/773/A:
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.

Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?

-----Input-----

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.

Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 10^9; 0 ≤ p ≤ q ≤ 10^9; y > 0; q > 0).

It is guaranteed that p / q is an irreducible fraction.

Hacks. For hacks, an additional constraint of t ≤ 5 must be met.

-----Output-----

For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.

-----Example-----
Input
4
3 10 1 2
7 14 3 8
20 70 2 7
5 6 1 1

Output
4
10
0
-1

-----Note-----

In the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.

In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.

In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.

In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.

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

def gcd(a, b):
	if a == 0:
		return [b, 0, 1]
	d = gcd(b % a, a)
	return [d[0], d[2] - (b // a) * d[1], d[1]]

t = int(input())
while t > 0:
	t -= 1
	x, y, p, q = list(map(int, input().split()))
	if p == q:
		if x == y:
			print(0)
		else:
			print(-1)
		continue
	if p == 0:
		if x == 0:
			print(0)
		else:
			print(-1)
		continue
	a = p - q
	b = p
	c = q * x - p * y
	g, xa, ya = gcd(abs(a), abs(b))
	if c % g != 0:
		print(-1)
	else:
		xa *= c // g
		ya *= c // g
		if a < 0:
			xa = -xa
		if b < 0:
			ya = -ya
		if xa < 0:
			gaps = (-xa + (b // g) - 1) // (b // g)
			xa += gaps * (b // g)
			ya -= gaps * (a // g)
		if ya < 0:
			gaps = (-ya + (-a // g) - 1) // (-a // g)
			xa += gaps * (b // g)
			ya -= gaps * (a // g)
		#print(xa, ya, a, b, c)
		if xa < 0 or ya < 0:
			print(-1)
		else:
			addon = min(xa // (b // g), ya // (-a // g))
			xa -= addon * (b // g)
			ya += addon * (a // g)
			print(xa + ya)


I found an interesting problem on https://codeforces.com/problemset/problem/773/B:
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.

For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.

$\left. \begin{array}{|l|r|} \hline \text{Solvers fraction} & {\text{Maximum point value}} \\ \hline(1 / 2,1 ] & {500} \\ \hline(1 / 4,1 / 2 ] & {1000} \\ \hline(1 / 8,1 / 4 ] & {1500} \\ \hline(1 / 16,1 / 8 ] & {2000} \\ \hline(1 / 32,1 / 16 ] & {2500} \\ \hline [ 0,1 / 32 ] & {3000} \\ \hline \end{array} \right.$

Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500.

If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem.

There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.

With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will...

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

n=int(input())
a=[list(map(int,input().split())) for i in range(n)]
solved=[0]*5
score=[0]*5
for i in range(n):
	for j in range(5):
		solved[j]+=int(a[i][j]>-1)
for k in range(31*n+1):
	for i in range(5):
		tot=n+k
		cur=solved[i]
		cur+=k*(a[0][i]>-1 and a[1][i]>-1 and a[0][i]>a[1][i])
		score[i]=500
		while score[i]<3000 and 2*cur<=tot:
			cur*=2;
			score[i]+=500
	res=[0,0]
	for j in range(2):
		for i in range(5):
			res[j]+=(a[j][i]>-1)*score[i]/250*(250-a[j][i])
	if res[0]>res[1]:
		print(k)
		break
else:
	print("-1")


I found an interesting problem on https://codeforces.com/problemset/problem/773/C:
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2^{k} - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2^{k}. Let's call that representation prairie partition of x.

For example, the prairie partitions of 12, 17, 7 and 1 are:  12 = 1 + 2 + 4 + 5,

17 = 1 + 2 + 4 + 8 + 2,

7 = 1 + 2 + 4,

1 = 1.

Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of numbers given from Alice to Borys.

The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^12; a_1 ≤ a_2 ≤ ... ≤ a_{n}) — the numbers given from Alice to Borys.

-----Output-----

Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.

If there are no such values of m, output a single integer -1.

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

Output
2

Input
6
1 1 1 2 2 2

Output
2 3

Input
5
1 2 4 4 4

Output
-1

-----Note-----

In the first example, Alice could get the input sequence from [6, 20] as the original sequence.

In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3].

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

from collections import Counter
n = int(input())
a = list(map(int, input().split()))

def get(cnt):
    c = Counter(a)
    last = []
    while c[1] and (cnt is None or len(last) < cnt):
        x = 1
        while c[x]:
            c[x] -= 1
            x *= 2
        last.append(x >> 1)
    rem = sorted(c.elements())
    i = 0
    for x in last[::-1]:
        if i < len(rem) and rem[i] < 2 * x:
            i += 1
    return len(last) if i == len(rem) else 0

mx = get(None)
lo, hi = 0, mx
while lo < hi:
    mid = (lo + hi) >> 1
    if get(mid):
        hi = mid
    else:
        lo = mid + 1
if mx:
    print(*list(range(lo, mx + 1)))
else:
    print(-1)


I found an interesting problem on https://codeforces.com/problemset/problem/774/A:
Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.

Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c_1 + c_2·(x - 1)^2 (in particular, if the group consists of one person, then the price is c_1).

All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group.

-----Input-----

The first line contains three integers n, c_1 and c_2 (1 ≤ n ≤ 200 000, 1 ≤ c_1, c_2 ≤ 10^7) — the number of visitors and parameters for determining the ticket prices for a group.

The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.

-----Output-----

Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.

-----Examples-----
Input
3 4 1
011

Output
8

Input
4 7 2
1101

Output
18

-----Note-----

In the first test one group of three people should go to the attraction. Then they have to pay 4 + 1 * (3 - 1)^2 = 8.

In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7 + 2 * (2 - 1)^2 = 9....

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

t = input()

t = t.split()

n = int(t[0])

c1 = int(t[1])

c2 = int(t[2])

t = input()

d = 0

for i in t:

    if(i=="1"):

        d = d+1

min = 10**1488

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

    t = c1*i + i*c2*(((n//i)-1)**2) + c2*(n%i)*(2*(n//i)-1)

    if t<min:

        min = t

print(min)

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/774/B:
Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters — its significance c_{i} and width w_{i}.

Stepan decided to expose some of his cups on a shelf with width d in such a way, that:  there is at least one Physics cup and at least one Informatics cup on the shelf,  the total width of the exposed cups does not exceed d,  from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too).

Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups.

-----Input-----

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100 000, 1 ≤ d ≤ 10^9) — the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf.

Each of the following n lines contains two integers c_{i} and w_{i} (1 ≤ c_{i}, w_{i} ≤ 10^9) — significance and width of the i-th cup for Physics olympiads.

Each of the following m lines contains two integers c_{j} and w_{j} (1 ≤ c_{j}, w_{j} ≤ 10^9) — significance and width of the j-th cup for Informatics olympiads.

-----Output-----

Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement.

If there is no way to expose cups on the shelf, then print 0.

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

Output
8

Input
4 3 12
3 4
2 4
3 5
3 4
3 5
5 2
3 4

Output
11

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

Output
0

-----Note-----

In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so...

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

n, m, d = map(int, input().split())
ph = [[int(j) for j in input().split()] for i in range(n)]
inf = [[int(j) for j in input().split()] for i in range(m)]
for i in range(n):
    ph[i][1] = -ph[i][1]
for i in range(m):
    inf[i][1] = -inf[i][1]
ph.sort(reverse=True)
inf.sort(reverse=True)
sw, sc = 0, 0
for p in inf:
    sc += p[0]
    d += p[1]
ans = 0
z = m - 1
for p in ph:
    sc += p[0]
    d += p[1]
    #print(sc, d)
    while z > 0 and d < 0:
        sc -= inf[z][0]
        d -= inf[z][1]
        z -= 1
    #print(sc, d)
    if d >= 0:
        ans = max(ans, sc)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/774/C:
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. [Image]

So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted.

The battery of the newest device allows to highlight at most n sections on the display.

Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.

-----Input-----

The first line contains the integer n (2 ≤ n ≤ 100 000) — the maximum number of sections which can be highlighted on the display.

-----Output-----

Print the maximum integer which can be shown on the display of Stepan's newest device.

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

Output
1

Input
3

Output
7

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/774/D:
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a_1, a_2, ..., a_{n}.

While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b_1, b_2, ..., b_{n}.

Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).

Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.

-----Input-----

The first line contains three integers n, l, r (1 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ n) — the number of Vasya's cubes and the positions told by Stepan.

The second line contains the sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the sequence of integers written on cubes in the Vasya's order.

The third line contains the sequence b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ n) — the sequence of integers written on cubes after Stepan rearranged their order.

It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.

-----Output-----

Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes).

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

Output
TRUTH

Input
3 1 2
1 2 3
3 1 2

Output
LIE

Input
4 2 4
1 1 1 1
1 1 1 1

Output
TRUTH

-----Note-----

In the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became...

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

n, l, r = map(int, input().split())
l -= 1
r -= 1
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(n):
	if (b[i] != a[i]) and (i < l or i > r):
		print("LIE")
		break
else:
	print("TRUTH")


I found an interesting problem on https://codeforces.com/problemset/problem/774/E:
Stepan has a very big positive integer.

Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.

Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m.

-----Input-----

The first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200 000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.

The second line contains the integer m (2 ≤ m ≤ 10^8) — the number by which Stepan divides good shifts of his integer.

-----Output-----

Print the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number m.

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

Output
2

Input
1001
5

Output
0

Input
5678901234567890123456789
10000

Output
123

-----Note-----

In the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.

In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder.

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

s=input()
m=int(input())
N=int(s)
MIN=N%m
L=len(s)-1
temp1=N
temp2=0
big=pow(10,L,m)
for i in range(0,len(s)-1):
    temp2*=10
    temp2+=int(s[i])
    temp2%=m
    temp1-=big*int(s[i])
    temp1*=10
    temp1%=m
    temp=temp1+temp2
    #print(temp1,temp2)
    #print(temp)
    temp%=m
    if s[i+1]!='0':
        if temp<MIN:
            MIN=temp
print(MIN)


I found an interesting problem on https://codeforces.com/problemset/problem/774/F:
Stepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (n + 1)-th day again he uses the pen number 1, on the (n + 2)-th — he uses the pen number 2 and so on.

On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day.

Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above.

-----Input-----

The first line contains the integer n (1 ≤ n ≤ 50 000) — the number of pens Stepan has.

The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is equal to the number of milliliters of ink which the pen number i currently has.

-----Output-----

Print the index of the pen which will run out of ink before all (it means that there will be no ink left in it), if Stepan will use pens according to the conditions described above.

Pens are numbered in the order they are given in input data. The numeration begins from one.

Note that the answer is always unambiguous, since several pens can not end at the same time.

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

Output
2

Input
5
5 4 5 4 4

Output
5

-----Note-----

In the first test Stepan uses ink of pens as follows:   on the day number 1 (Monday) Stepan will use the pen number 1, after that there will be 2 milliliters of ink in it;  on the day number 2 (Tuesday) Stepan will use the pen number 2, after that there will be 2 milliliters of ink in it;  on the day number 3 (Wednesday) Stepan will use the pen number 3, after that there will be 2 milliliters of ink in it;  on the day number 4 (Thursday) Stepan will use the pen number 1, after that there will be 1...

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

import sys

def Min(x, y):
    if x > y:
        return y
    else:
        return x

def Gcd(x, y):
    if x == 0:
        return y
    else:
        return Gcd(y % x, x)

def Lcm(x, y):
    return x * y // Gcd(x, y)

n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]

ok = 0

cur = 0

len = Lcm(7, n)

for i in range(0, 7 * n):
    if a[i % n] == 0 :
        print(i % n + 1)
        ok = 1
        break
    if cur != 6:
        a[i % n] -= 1
        d[i % n] += 1
    cur = (cur + 1) % 7

if ok == 0:
    k = 10**20

    for i in range(0, n):
        a[i] += d[i]
        if d[i] == 0: continue
        if a[i] % d[i] > 0:
            k = Min(k, a[i] // d[i])
        else:
            k = Min(k, a[i] // d[i] - 1)

    if k == 10**20:
        k = 0

    for i in range(0, n):
        a[i] -= k * d[i]

    iter = 0
    cur = 0

    while True:
        if a[iter] == 0:
            print(iter % n + 1)
            break
        else:
            if cur != 6:
                a[iter] -= 1
            cur = (cur + 1) % 7
            iter = (iter + 1) % n


I found an interesting problem on https://codeforces.com/problemset/problem/774/G:
Arkadiy has lots square photos with size a × a. He wants to put some of them on a rectangular wall with size h × w.

The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and columns of photos to the nearest bound of the wall must be equal to x, where x is some non-negative real number. Look on the picture below for better understanding of the statement.

 [Image]

Arkadiy haven't chosen yet how many photos he would put on the wall, however, he want to put at least one photo. Your task is to determine the minimum value of x which can be obtained after putting photos, or report that there is no way to put positive number of photos and satisfy all the constraints. Suppose that Arkadiy has enough photos to make any valid arrangement according to the constraints.

Note that Arkadiy wants to put at least one photo on the wall. The photos should not overlap, should completely lie inside the wall bounds and should have sides parallel to the wall sides.

-----Input-----

The first line contains three integers a, h and w (1 ≤ a, h, w ≤ 10^9) — the size of photos and the height and the width of the wall.

-----Output-----

Print one non-negative real number — the minimum value of x which can be obtained after putting the photos on the wall. The absolute or the relative error of the answer must not exceed 10^{ - 6}.

Print -1 if there is no way to put positive number of photos and satisfy the constraints.

-----Examples-----
Input
2 18 13

Output
0.5

Input
4 4 4

Output
0

Input
3 4 3

Output
-1

-----Note-----

In the first example Arkadiy can put 7 rows of photos with 5 photos in each row, so the minimum value of x equals to 0.5.

In the second example Arkadiy can put only 1 photo which will take the whole wall, so the minimum value of x equals to 0.

In the third example there is no way to put positive number of photos and satisfy the constraints described in the statement,...

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

def gcd(n,m):
    if m==0:return n
    else:return gcd(m,n%m)
a,h,w=map(int,input().split())
g=gcd(a+h,a+w)
s=(a+w)//g
t=((w//a+1)//s)*s-1
if t<=0:print(-1)
else:print("%.10lf"%((w-t*a)/(t+1)))


I found an interesting problem on https://codeforces.com/problemset/problem/774/H:
Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet.

After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c_1, c_2, ..., c_{n}, where n equals the length of the string s, and c_{i} equals the number of substrings in the string s with the length i, consisting of the same letters. The substring is a sequence of consecutive characters in the string s.

For example, if the Stepan's favorite string is equal to "tttesst", the sequence c looks like: c = [7, 3, 1, 0, 0, 0, 0].

Stepan asks you to help to repair his favorite string s according to the given sequence c_1, c_2, ..., c_{n}.

-----Input-----

The first line contains the integer n (1 ≤ n ≤ 2000) — the length of the Stepan's favorite string.

The second line contains the sequence of integers c_1, c_2, ..., c_{n} (0 ≤ c_{i} ≤ 2000), where c_{i} equals the number of substrings of the string s with the length i, consisting of the same letters.

It is guaranteed that the input data is such that the answer always exists.

-----Output-----

Print the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet.

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

Output
kkrrrq
Input
4
4 0 0 0

Output
abcd

-----Note-----

In the first test Stepan's favorite string, for example, can be the string "kkrrrq", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3).

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

import sys

n = int(input())
c = list(map(int, input().split()))
cc = ord('a')
ans = ""
cur = n - 1
if 1:
    cur = n - 1
    while cur >= 0:
        while c[cur] > 0:
            if chr(cc) > 'z':
                cc = ord('a')
            ans += chr(cc) * (cur + 1)
            c[cur] -= 1
            for i in range(cur):
                c[i] -= (cur - i + 1)
            cc += 1
        cur -= 1
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/774/J:
Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not.

Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch.

Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k.

-----Input-----

The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked.

The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not.

-----Output-----

If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes).

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

Output
YES

Input
6 1
????NN

Output
NO

-----Note-----

In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2.

In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive.

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

n, k = map(int, input().split())
string = input()
series = []
now = ""
for elem in string:
    if elem == "Y":
        if now:
            series.append(now)
        now = ""
    else:
        now += elem
if now:
    series.append(now)

answer = False
no_max = True
if not k:
    for elem in series:
        if elem.count('N'):
            answer = True

    print("YES" if not answer else "NO")
else:
    for elem in series:
        m = len(elem)
        for i in range(m - k + 1):
            if (not i or elem[i - 1] == '?') and ((i + k - 1) == m - 1 or elem[i + k] == '?'):
                answer = True

        counter = 0
        for letter in elem:
            if letter == 'N':
                counter += 1
                if counter > k:
                    no_max = False
            else:
                counter = 0

    print("YES" if answer and no_max else "NO")


I found an interesting problem on https://codeforces.com/problemset/problem/774/K:
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".

Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".

There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".

Sergey is very busy and asks you to help him and write the required program.

-----Input-----

The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of letters in the word written by Stepan.

The second line contains the string s which has length that equals to n and contains only lowercase English letters — the word written by Stepan.

-----Output-----

Print the single string — the word written by Stepan converted according to the rules described in the statement.

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

Output
pobeda

Input
22
iiiimpleeemeentatiioon

Output
implemeentatioon

Input
18
aeiouyaaeeiioouuyy

Output
aeiouyaeeioouy

Input
24
aaaoooiiiuuuyyyeeeggghhh

Output
aoiuyeggghhh

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

def end(r, curr_s, curr_l):
    if curr_l == 0:
        return
    if (curr_s == "o" or curr_s == "e") and curr_l == 2:
        r.append(curr_s * 2)
    else:
        r.append(curr_s)

def main():
    n = int(input())
    s = input()

    glasnie = "aeiouy"
    curr_s = ""
    curr_l = 0
    r = []
    for e in s:
        if e in glasnie:
            if e != curr_s:
                end(r, curr_s, curr_l)
                curr_s = e
                curr_l = 1
            else:
                curr_l += 1
        else:
            end(r, curr_s, curr_l)
            r.append(e)
            curr_s = ""
            curr_l = 0
    end(r, curr_s, curr_l)

    print("".join(r))

def __starting_point():
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/774/L:
Polycarp's workday lasts exactly $n$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $k$ bars at the beginning of the workday.

In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $k$ is strictly greater than $1$.

Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.

Consider that Polycarp eats a bar in the minute $x$ and the next bar in the minute $y$ ($x < y$). Then the break time is equal to $y - x - 1$ minutes. It is not necessary for Polycarp to eat all bars he has.

-----Input-----

The first line contains two integers $n$ and $k$ ($2 \le n \le 200\,000$, $2 \le k \le n$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday.

The second line contains the string with length $n$ consisting of zeros and ones. If the $i$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $i$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $i$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.

-----Output-----

Print the minimum possible break in minutes between eating chocolate bars.

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

Output
1

Input
8 3
01010110

Output
3

-----Note-----

In the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.

In the second example Polycarp will...

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

import sys
from math import *
from fractions import gcd
from random import * # randint(inclusive,inclusive)
readints=lambda:list(map(int, input().strip('\n').split()))
from itertools import permutations, combinations
s = "abcdefghijklmnopqrstuvwxyz"
# print('', end=" ")
# for i in {1..5}; do echo "hi"; done

n,k=readints()
s=input()

lo=-1
hi=n+1

def test(x):
    have=k-1
    last=0
    arr=[]
    for i in range(n):
        if s[i]=='0':
            arr.append(i)

    arr.append(10**9)

    for i in range(1,len(arr)):
        if arr[i]-last-1>x:
            if arr[i-1]==last:
                return False
            if have==0:
                return False
            if arr[i-1]-last-1>x:
                return False
            last=arr[i-1]
            have-=1

    return True

while hi-lo>1:
    mid=(lo+hi)//2
    if test(mid):
        hi=mid
    else:
        lo=mid

print(hi)


I found an interesting problem on https://codeforces.com/problemset/problem/776/C:
Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value a_{i}.

Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.

Help her to do so in finding the total number of such segments.

-----Input-----

The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 ≤ n ≤ 10^5, 1 ≤ |k| ≤ 10).

Next line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — affection values of chemicals.

-----Output-----

Output a single integer — the number of valid segments.

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

Output
8

Input
4 -3
3 -6 -3 12

Output
3

-----Note-----

Do keep in mind that k^0 = 1.

In the first sample, Molly can get following different affection values:  2: segments [1, 1], [2, 2], [3, 3], [4, 4];

 4: segments [1, 2], [2, 3], [3, 4];

 6: segments [1, 3], [2, 4];

 8: segments [1, 4].

Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.

In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].

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

n, k = list(map(int, input().split()))
A = list(map(int, input().split()))
cumsum = [0]

for a in A:
   cumsum.append(cumsum[-1] + a)
#print(cumsum)
pows = set([k**i for i in range(50)])
cum = dict({})
cum[0] = 1

res = 0

for x in cumsum[1:]:
    for pow in pows:
        if (x - pow) in cum:
            res += cum[x - pow]
    if x in cum:
        cum[x] += 1
    else:
        cum[x] = 1

print(res)

# Made By Mostafa_Khaled


I found an interesting problem on https://codeforces.com/problemset/problem/776/D:
Moriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are m switches. Each switch control doors of some rooms, but each door is controlled by exactly two switches.

You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch 1, which was connected to room 1, 2 and 3 which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked.

You need to tell Sherlock, if there exists a way to unlock all doors at the same time.

-----Input-----

First line of input contains two integers n and m (2 ≤ n ≤ 10^5, 2 ≤ m ≤ 10^5) — the number of rooms and the number of switches.

Next line contains n space-separated integers r_1, r_2, ..., r_{n} (0 ≤ r_{i} ≤ 1) which tell the status of room doors. The i-th room is locked if r_{i} = 0, otherwise it is unlocked.

The i-th of next m lines contains an integer x_{i} (0 ≤ x_{i} ≤ n) followed by x_{i} distinct integers separated by space, denoting the number of rooms controlled by the i-th switch followed by the room numbers that this switch controls. It is guaranteed that the room numbers are in the range from 1 to n. It is guaranteed that each door is controlled by exactly two switches.

-----Output-----

Output "YES" without quotes, if it is possible to open all doors at the same time, otherwise output "NO" without quotes.

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

Output
NO
Input
3 3
1 0 1
3 1 2 3
1 2
2 1 3

Output
YES
Input
3 3
1 0 1
3 1 2 3
2 1 2
1 3

Output
NO

-----Note-----

In the second example input, the initial statuses of the doors are [1, 0, 1] (0 means locked, 1 — unlocked).

After toggling switch 3, we get [0, 0, 0] that means all doors are...

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

import sys
from collections import deque

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n, m = map(int, sys.stdin.readline().split())
    r = [1 - int(i) for i in sys.stdin.readline().split()]
    es = [[] for i in range(n)]

    for i in range(m):
        line = [int(j) for j in sys.stdin.readline().split()]

        for u in line[1:]:
            es[u - 1].append(i)

    Adj = [[] for i in range(m)]

    for u, v in es:
        Adj[u].append(v)
        Adj[v].append(u)

    edges = dict()

    for i, e in enumerate(es):
        e.sort()
        if tuple(e) not in edges:
            edges[tuple(e)] = r[i]
        elif edges[tuple(e)] != r[i]:
            print('NO')
            return None
        else:
            pass

    cols = [None] * m

    for u in range(m):
        if cols[u] is None:
            if not bfs(Adj, edges, cols, u):
                print('NO')
                return None
            else:
                pass

    print('YES')

def bfs(Adj, edges, cols, u):
    nxts = deque([u])
    cols[u] = 0

    while nxts:
        v = nxts.popleft()

        for w in Adj[v]:
            ed = tuple(sorted([v, w]))
            if cols[w] is None:
                cols[w] = cols[v] ^ edges[ed]
                nxts.append(w)
            else:
                if cols[w] ^ cols[v] != edges[ed]:
                    return False

    return True

def __starting_point():
    solve()
__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/776/E:
The Holmes children are fighting over who amongst them is the cleverest.

Mycroft asked Sherlock and Eurus to find value of f(n), where f(1) = 1 and for n ≥ 2, f(n) is the number of distinct ordered positive integer pairs (x, y) that satisfy x + y = n and gcd(x, y) = 1. The integer gcd(a, b) is the greatest common divisor of a and b.

Sherlock said that solving this was child's play and asked Mycroft to instead get the value of $g(n) = \sum_{d|n} f(n / d)$. Summation is done over all positive integers d that divide n.

Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.

She defined a k-composite function F_{k}(n) recursively as follows:

$F_{k}(n) = \left\{\begin{array}{ll}{f(g(n)),} & {\text{for} k = 1} \\{g(F_{k - 1}(n)),} & {\text{for} k > 1 \text{and} k \operatorname{mod} 2 = 0} \\{f(F_{k - 1}(n)),} & {\text{for} k > 1 \text{and} k \operatorname{mod} 2 = 1} \end{array} \right.$

She wants them to tell the value of F_{k}(n) modulo 1000000007.

-----Input-----

A single line of input contains two space separated integers n (1 ≤ n ≤ 10^12) and k (1 ≤ k ≤ 10^12) indicating that Eurus asks Sherlock and Mycroft to find the value of F_{k}(n) modulo 1000000007.

-----Output-----

Output a single integer — the value of F_{k}(n) modulo 1000000007.

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

Output
6
Input
10 2

Output
4

-----Note-----

In the first case, there are 6 distinct ordered pairs (1, 6), (2, 5), (3, 4), (4, 3), (5, 2) and (6, 1) satisfying x + y = 7 and gcd(x, y) = 1. Hence, f(7) = 6. So, F_1(7) = f(g(7)) = f(f(7) + f(1)) = f(6 + 1) = f(7) = 6.

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

phi = [0 for i in range(100100)]
phi[1] = 1
for i in range(2, 100050):
    if (phi[i] == 0):
        for j in range(i, 100051, i):
            if (phi[j] == 0):
                phi[j]=j
            phi[j] = phi[j]//i*(i-1)

def Fenjie(n):
    k = {}
    if (n == 1):
        return {}
    a = 2
    while (n >= 2):
        b = n%a
        if (a*a > n):
            if (n in k):
                k[n] += 1
            else:
                k[n] = 1
            break
        if (b == 0):
            if (a in k):
                k[a] += 1
            else:
                k[a] = 1
            n = n//a
        else:
            a += 1
    return k

def Euler(k):
    if (len(k) == 0):
        return 1
    ans = 1
    for i in k:
        s = k[i]
        ans *= pow(i, s)
        ans = ans//i*(i-1)
    return ans

n, k = list(map(int, input().split()))
k = (k+1)//2
while (k):
    k -= 1
    n = Euler(Fenjie(n))
    if (n==1):
        break
print(n%(10**9+7))


I found an interesting problem on https://codeforces.com/problemset/problem/777/A:
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.

Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).

Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly n movements were made by the operator and the ball was under shell x at the end. Now he wonders, what was the initial position of the ball?

-----Input-----

The first line of the input contains an integer n (1 ≤ n ≤ 2·10^9) — the number of movements made by the operator.

The second line contains a single integer x (0 ≤ x ≤ 2) — the index of the shell where the ball was found after n movements.

-----Output-----

Print one integer from 0 to 2 — the index of the shell where the ball was initially placed.

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

Output
1

Input
1
1

Output
0

-----Note-----

In the first sample, the ball was initially placed beneath the middle shell and the operator completed four movements.  During the first move operator swapped the left shell and the middle shell. The ball is now under the left shell.  During the second move operator swapped the middle shell and the right one. The ball is still under the left shell.  During the third move operator swapped the left shell and the middle shell again. The ball is again in the middle.  Finally, the operators swapped the middle shell and the right shell. The ball is now beneath the right shell.

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