I found an interesting problem on https://codeforces.com/problemset/problem/1073/B:
Vasya has got $n$ books, numbered from $1$ to $n$, arranged in a stack. The topmost book has number $a_1$, the next one — $a_2$, and so on. The book at the bottom of the stack has number $a_n$. All numbers are distinct.

Vasya wants to move all the books to his backpack in $n$ steps. During $i$-th step he wants to move the book number $b_i$ into his backpack. If the book with number $b_i$ is in the stack, he takes this book and all the books above the book $b_i$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $[1, 2, 3]$ (book $1$ is the topmost), and Vasya moves the books in the order $[2, 1, 3]$, then during the first step he will move two books ($1$ and $2$), during the second step he will do nothing (since book $1$ is already in the backpack), and during the third step — one book (the book number $3$). Note that $b_1, b_2, \dots, b_n$ are distinct.

Help Vasya! Tell him the number of books he will put into his backpack during each step.

-----Input-----

The first line contains one integer $n~(1 \le n \le 2 \cdot 10^5)$ — the number of books in the stack.

The second line contains $n$ integers $a_1, a_2, \dots, a_n~(1 \le a_i \le n)$ denoting the stack of books.

The third line contains $n$ integers $b_1, b_2, \dots, b_n~(1 \le b_i \le n)$ denoting the steps Vasya is going to perform.

All numbers $a_1 \dots a_n$ are distinct, the same goes for $b_1 \dots b_n$.

-----Output-----

Print $n$ integers. The $i$-th of them should be equal to the number of books Vasya moves to his backpack during the $i$-th step.

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

Output
2 0 1

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

Output
3 2 0 0 0

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

Output
1 1 2 0 1 1

-----Note-----

The first example is described in the statement.

In the second example, during the first step Vasya will move the books $[3, 1, 4]$. After that only books $2$ and $5$ remain in the stack ($2$ is above $5$). During the second step Vasya will...

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

n = int(input())
a_trans = [n + 1] * (n + 1)
i = 1
for ai in input().split():
	a_trans[int(ai)] = i
	i += 1
min_unt_ake_n = 1
res = []
for bi in input().split():
	atb_i = a_trans[int(bi)]
	if atb_i < min_unt_ake_n:
		res.append('0')
	else:
		nex = atb_i + 1
		res.append(nex - min_unt_ake_n)
		min_unt_ake_n = nex
print(*res)


I found an interesting problem on https://codeforces.com/problemset/problem/1073/C:
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations:   U — move from $(x, y)$ to $(x, y + 1)$;  D — move from $(x, y)$ to $(x, y - 1)$;  L — move from $(x, y)$ to $(x - 1, y)$;  R — move from $(x, y)$ to $(x + 1, y)$.

Vasya also has got a sequence of $n$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $(x, y)$.

Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $maxID - minID + 1$, where $maxID$ is the maximum index of a changed operation, and $minID$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $2$, $5$ and $7$ are changed, so the length of changed subsegment is $7 - 2 + 1 = 6$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $1$.

If there are no changes, then the length of changed subsegment is $0$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.

Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $(0, 0)$ to $(x, y)$, or tell him that it's impossible.

-----Input-----

The first line contains one integer number $n~(1 \le n \le 2 \cdot 10^5)$ — the number of operations.

The second line contains the sequence of operations — a string of $n$ characters. Each character is either U, D, L or R.

The third line contains two integers $x, y~(-10^9 \le x, y \le 10^9)$ — the coordinates of the cell where the robot should end its path.

-----Output-----

Print one integer — the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from $(0, 0)$ to $(x, y)$. If this change is impossible, print $-1$.

-----Examples-----
Input
5
RURUU
-2...

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

n = int(input())
subtract = lambda t1, t2: (t1[0] - t2[0], t1[1] - t2[1])
add = lambda t1, t2: (t1[0] + t2[0], t1[1] + t2[1])
def conv(ch):
	if ch == 'L':
		return (-1, 0)
	elif ch == 'R':
		return (1, 0)
	elif ch == 'U':
		return (0, 1)
	elif ch == 'D':
		return (0, -1)

ops = [conv(ch) for ch in input()]
x, y = list(map(int, input().split()))
lsum = [ops[0]] * n
for i in range(1, n):
	lsum[i] = add(lsum[i - 1], ops[i])
rsum = [ops[n - 1]] * n
i = n - 2
while i >= 0:
	rsum[i] = add(rsum[i + 1], ops[i])
	i = i - 1

def check(L):

	for i in range(0, n - L + 1):
		moves = (x, y)
		if i > 0:
			moves = subtract(moves, lsum[i - 1])
		if i + L < n:
			moves = subtract(moves, rsum[i + L])
		turns = abs(moves[0]) + abs(moves[1])
		if (turns <= L and (L - turns) % 2 == 0):
			return True;
	return False;

if abs(x) + abs(y) > n or (abs(x) + abs(y) - n) % 2 != 0:
	print((-1));
else:
	st, en = 0, n
	while st < en:
		md = (st + en) // 2
		if check(md):
			en = md
		else:
			st = md + 1
	print(st)


I found an interesting problem on https://codeforces.com/problemset/problem/1073/D:
XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $n$ booths, arranged in a circle. The booths are numbered $1$ through $n$ clockwise with $n$ being adjacent to $1$. The $i$-th booths sells some candies for the price of $a_i$ burles per item. Each booth has an unlimited supply of candies.

Polycarp has decided to spend at most $T$ burles at the fair. However, he has some plan in mind for his path across the booths:  at first, he visits booth number $1$;  if he has enough burles to buy exactly one candy from the current booth, then he buys it immediately;  then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not).

Polycarp's money is finite, thus the process will end once he can no longer buy candy at any booth.

Calculate the number of candies Polycarp will buy.

-----Input-----

The first line contains two integers $n$ and $T$ ($1 \le n \le 2 \cdot 10^5$, $1 \le T \le 10^{18}$) — the number of booths at the fair and the initial amount of burles Polycarp has.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the price of the single candy at booth number $i$.

-----Output-----

Print a single integer — the total number of candies Polycarp will buy.

-----Examples-----
Input
3 38
5 2 5

Output
10

Input
5 21
2 4 100 2 6

Output
6

-----Note-----

Let's consider the first example. Here are Polycarp's moves until he runs out of money:  Booth $1$, buys candy for $5$, $T = 33$;  Booth $2$, buys candy for $2$, $T = 31$;  Booth $3$, buys candy for $5$, $T = 26$;  Booth $1$, buys candy for $5$, $T = 21$;  Booth $2$, buys candy for $2$, $T = 19$;  Booth $3$, buys candy for $5$, $T = 14$;  Booth $1$, buys candy for $5$, $T = 9$;  Booth $2$, buys candy for $2$, $T = 7$;  Booth $3$, buys candy for $5$, $T = 2$;  Booth $1$, buys no candy, not enough money;  Booth $2$, buys candy for $2$, $T = 0$.

No candy can be bought later. The total number of candies bought is $10$.

In the second example he has $1$...

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

import math as ma
import sys
from decimal import Decimal as dec
from itertools import permutations

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

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

def nu():
	return int(input())

def find_gcd(x , y):
	while (y):
		x , y = y , x % y
	return x

n,t=num()
a=li()
count=n
z=0
while(count>0 and sum(a)>0):
	pp=0
	z+=(t//sum(a))*count
	t=t%sum(a)
	for i in range(n):
		if(t>=a[i] and a[i]!=0):
			pp+=1
			t-=a[i]
		else:
			a[i]=0
	count=pp
	z+=pp
print(z)


I found an interesting problem on https://codeforces.com/problemset/problem/1073/E:
You are given two integers $l$ and $r$ ($l \le r$). Your task is to calculate the sum of numbers from $l$ to $r$ (including $l$ and $r$) such that each number contains at most $k$ different digits, and print this sum modulo $998244353$.

For example, if $k = 1$ then you have to calculate all numbers from $l$ to $r$ such that each number is formed using only one digit. For $l = 10, r = 50$ the answer is $11 + 22 + 33 + 44 = 110$.

-----Input-----

The only line of the input contains three integers $l$, $r$ and $k$ ($1 \le l \le r < 10^{18}, 1 \le k \le 10$) — the borders of the segment and the maximum number of different digits.

-----Output-----

Print one integer — the sum of numbers from $l$ to $r$ such that each number contains at most $k$ different digits, modulo $998244353$.

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

Output
1230

Input
1 2345 10

Output
2750685

Input
101 154 2

Output
2189

-----Note-----

For the first example the answer is just the sum of numbers from $l$ to $r$ which equals to $\frac{50 \cdot 51}{2} - \frac{9 \cdot 10}{2} = 1230$. This example also explained in the problem statement but for $k = 1$.

For the second example the answer is just the sum of numbers from $l$ to $r$ which equals to $\frac{2345 \cdot 2346}{2} = 2750685$.

For the third example the answer is $101 + 110 + 111 + 112 + 113 + 114 + 115 + 116 + 117 + 118 + 119 + 121 + 122 + 131 + 133 + 141 + 144 + 151 = 2189$.

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

l, r, k =list(map(int,input().split()))

d = {i:2**i for i in range(10)}

cache = {}

def can(i, m):
    return d[i] & m

def calc(m):
    b = 1
    c = 0
    for i in range(10):
        if b & m:
            c += 1
        b *= 2

    return c

def sm(ln, k, m, s='', first=False):
    if ln < 1:
        return 0, 1

    if (ln, k, m, s, first) in cache:
        return cache[(ln, k, m, s, first)]

    ans = 0
    count = 0
    base = 10 ** (ln-1)

    use_new = calc(m) < k

    if s:
        finish = int(s[0])+1
    else:
        finish = 10

    for i in range(finish):
        if use_new or can(i, m):
            ss = s[1:]
            if i != finish-1:
                ss = ''
            nm = m | d[i]
            nfirst = False
            if i == 0 and first:
                nm = m
                nfirst = True
            nexta, nextc = sm(ln-1, k, nm, ss, nfirst)
            ans += base * i * nextc + nexta
            count += nextc

#    print(ln, k, m, s, first, ans, count)
    cache[(ln, k, m, s, first)] = (ans, count)

    return ans, count

def call(a, k):
    s = str(a)
    return sm(len(s), k, 0, s, True)[0]

#print(call(r, k) - call(l-1, k))
print((call(r, k) - call(l-1, k)) % 998244353)


I found an interesting problem on https://codeforces.com/problemset/problem/1073/F:
You are given an undirected unweighted tree consisting of $n$ vertices.

An undirected tree is a connected undirected graph with $n - 1$ edges.

Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) $(x_1, y_1)$ and $(x_2, y_2)$ in such a way that neither $x_1$ nor $y_1$ belong to the simple path from $x_2$ to $y_2$ and vice versa (neither $x_2$ nor $y_2$ should not belong to the simple path from $x_1$ to $y_1$).

It is guaranteed that it is possible to choose such pairs for the given tree.

Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from $x_1$ to $y_1$ and from $x_2$ to $y_2$. And among all such pairs you have to choose one with the maximum total length of these two paths.

It is guaranteed that the answer with at least two common vertices exists for the given tree.

The length of the path is the number of edges in it.

The simple path is the path that visits each vertex at most once.

-----Input-----

The first line contains an integer $n$ — the number of vertices in the tree ($6 \le n \le 2 \cdot 10^5$).

Each of the next $n - 1$ lines describes the edges of the tree.

Edge $i$ is denoted by two integers $u_i$ and $v_i$, the labels of vertices it connects ($1 \le u_i, v_i \le n$, $u_i \ne v_i$).

It is guaranteed that the given edges form a tree.

It is guaranteed that the answer with at least two common vertices exists for the given tree.

-----Output-----

Print any two pairs of vertices satisfying the conditions described in the problem statement.

It is guaranteed that it is possible to choose such pairs for the given tree.

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

Output
3 6
7 5

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

Output
2 9
6 8

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

Output
10 6
4 5

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

Output
9 11
8 10

-----Note-----

The picture corresponding to the first example: [Image]

The intersection...

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

import sys

n = int(sys.stdin.readline())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
    i, j = tuple(int(k) for k in sys.stdin.readline().split())
    i -= 1
    j -= 1
    edges[i].append(j)
    edges[j].append(i)

# Prunes the graph starting from the vertices with
# only 1 edge until we reach a vertex with 3+ edges.
# Stores the distance from each non-pruned vertex
# to each of the leaves it reaches.
def prune():
    pruned = [False for _ in range(n)]
    leaves = [[] for _ in range(n)]
    todo = []
    for i in range(n):
        if len(edges[i]) == 1:
            todo.append((0, i, i))
    while len(todo) > 0:
        d, i, j = todo.pop()
        pruned[j] = True
        for k in edges[j]:
            if not pruned[k]:
                if len(edges[k]) < 3:
                    todo.append((d + 1, i, k))
                else:
                    leaves[k].append((d + 1, i))
    return pruned, leaves

pruned, leaves = prune()

# Returns the furthest non-pruned vertices
# from another non-pruned vertex.
def furthest(i):
    assert not pruned[i]
    visited = list(pruned)
    top_distance = 0
    top_vertices = [i]
    todo = [(0, i)]
    while len(todo) > 0:
        d, i = todo.pop()
        visited[i] = True
        if d > top_distance:
            top_distance = d
            top_vertices = []
        if d == top_distance:
            top_vertices.append(i)
        for j in edges[i]:
            if not visited[j]:
                todo.append((d + 1, j))
    return top_distance, top_vertices

# Single center topology.
# Only 1 vertex with 3+ edges.
def solve_single_center(i):
    l = list(reversed(sorted(leaves[i])))[:4]
    return list(l[j][1] for j in range(4))

# Scores non-pruned vertices according to the sum
# of the distances to their two furthest leaves.
def vertices_score(v):
    scores = []
    for i in v:
        assert not pruned[i]
        l = list(reversed(sorted(leaves[i])))[:2]
        score = (l[0][0] + l[1][0]), l[0][1], l[1][1]
        scores.append(score)
    return...


I found an interesting problem on https://codeforces.com/problemset/problem/1075/A:
On a chessboard with a width of $n$ and a height of $n$, rows are numbered from bottom to top from $1$ to $n$, columns are numbered from left to right from $1$ to $n$. Therefore, for each cell of the chessboard, you can assign the coordinates $(r,c)$, where $r$ is the number of the row, and $c$ is the number of the column.

The white king has been sitting in a cell with $(1,1)$ coordinates for a thousand years, while the black king has been sitting in a cell with $(n,n)$ coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates $(x,y)$...

Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:

As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.

The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates $(x,y)$ first will win.

Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the $(a,b)$ cell, then in one move he can move from $(a,b)$ to the cells $(a + 1,b)$, $(a - 1,b)$, $(a,b + 1)$, $(a,b - 1)$, $(a + 1,b - 1)$, $(a + 1,b + 1)$, $(a - 1,b - 1)$, or $(a - 1,b + 1)$. Going outside of the field is prohibited.

Determine the color of the king, who will reach the cell with the coordinates $(x,y)$ first, if the white king moves first.

-----Input-----

The first line contains a single integer $n$ ($2 \le n \le 10^{18}$) — the length of the side of the chess field.

The second line contains two integers $x$ and $y$ ($1 \le x,y \le n$) — coordinates of the cell, where the coin fell.

-----Output-----

In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.

You can print each letter in any case (upper...

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

n = int(input())
x, y = list(map(int, input().split()))

if abs(x - 1) + abs(y - 1) <= abs(x - n) + abs(y - n):
    print('White')
else:
    print('Black')


I found an interesting problem on https://codeforces.com/problemset/problem/1075/B:
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.

Lyft has become so popular so that it is now used by all $m$ taxi drivers in the city, who every day transport the rest of the city residents — $n$ riders.

Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).

The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.

But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $i$ the number $a_{i}$ — the number of riders that would call the $i$-th taxi driver when all drivers and riders are at their home?

The taxi driver can neither transport himself nor other taxi drivers.

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n,m \le 10^5$) — number of riders and taxi drivers.

The second line contains $n + m$ integers $x_1, x_2, \ldots, x_{n+m}$ ($1 \le x_1 < x_2 < \ldots < x_{n+m} \le 10^9$), where $x_i$ is the coordinate where the $i$-th resident lives.

The third line contains $n + m$ integers $t_1, t_2, \ldots, t_{n+m}$ ($0 \le t_i \le 1$). If $t_i = 1$, then the $i$-th resident is a taxi driver, otherwise $t_i = 0$.

It is guaranteed that the number of $i$ such that $t_i = 1$ is equal to $m$.

-----Output-----

Print $m$ integers $a_1, a_2, \ldots, a_{m}$, where $a_i$ is the answer for the $i$-th taxi driver. The taxi driver has the number $i$ if among all the taxi drivers he lives in the $i$-th smallest coordinate (see examples for better understanding).

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

Output
3
Input
3 2
2 3 4 5 6
1 0 0 0 1

Output
2...

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

n, m = map(int, input().split())
dist = [int(x) for x in input().split()]
taxi = [int(x) for x in input().split()]
dists = {}
d = []
for person in range(len(taxi)):
    if taxi[person]:
        dists[dist[person]] = 0
        d.append(dist[person])
start = 0
d.append(10**11)
for person in range(len(taxi)):
    if taxi[person] == 0:
        while dist[person] > d[start + 1]:
            start += 1
        if abs(dist[person] - d[start]) <= abs(dist[person] - d[start + 1]):
            dists[d[start]] += 1
        else:
            dists[d[start + 1]] += 1
for d in dists:
    print(dists[d] if d!=10**11 else '', end=' ')


I found an interesting problem on https://codeforces.com/problemset/problem/1076/A:
You are given a string $s$ consisting of $n$ lowercase Latin letters.

You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.

String $s = s_1 s_2 \dots s_n$ is lexicographically smaller than string $t = t_1 t_2 \dots t_m$ if $n < m$ and $s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$ or there exists a number $p$ such that $p \le min(n, m)$ and $s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$ and $s_p < t_p$.

For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of $s$.

The second line of the input contains exactly $n$ lowercase Latin letters — the string $s$.

-----Output-----

Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $s$.

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

Output
aa

Input
5
abcda

Output
abca

-----Note-----

In the first example you can remove any character of $s$ to obtain the string "aa".

In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".

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

#
import collections, atexit, math, sys, bisect

sys.setrecursionlimit(1000000)
def getIntList():
    return list(map(int, input().split()))

try :
    #raise ModuleNotFoundError
    import numpy
    def dprint(*args, **kwargs):
        #print(*args, **kwargs, file=sys.stderr)
        # in python 3.4 **kwargs is invalid???
        print(*args,  file=sys.stderr)
    dprint('debug mode')
except Exception:
    def dprint(*args, **kwargs):
        pass

inId = 0
outId = 0
if inId>0:
    dprint('use input', inId)
    sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
    dprint('use output', outId)
    sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
    atexit.register(lambda :sys.stdout.close())     #idle 中不会执行 atexit

N, = getIntList()
#print(N)
s = input()

for i in range(1,N):
    if s[i-1] > s[i]:
        print(s[:i-1] + s[i:])
        return
print(s[:-1])


I found an interesting problem on https://codeforces.com/problemset/problem/1076/B:
You are given an integer number $n$. The following algorithm is applied to it:

  if $n = 0$, then end algorithm;  find the smallest prime divisor $d$ of $n$;  subtract $d$ from $n$ and go to step $1$.

Determine the number of subtrations the algorithm will make.

-----Input-----

The only line contains a single integer $n$ ($2 \le n \le 10^{10}$).

-----Output-----

Print a single integer — the number of subtractions the algorithm will make.

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

Output
1

Input
4

Output
2

-----Note-----

In the first example $5$ is the smallest prime divisor, thus it gets subtracted right away to make a $0$.

In the second example $2$ is the smallest prime divisor at both steps.

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

import sys
from math import ceil, sqrt

input = sys.stdin.readline

n = int(input())

if n % 2 == 0:
    print(int(n/2))
else:
    prime = n
    for i in range(2, ceil(sqrt(n)) + 1):
        if n % i == 0:
            prime = i
            break
    print(1 + int((n - prime)/2))


I found an interesting problem on https://codeforces.com/problemset/problem/1076/D:
You are given an undirected connected weighted graph consisting of $n$ vertices and $m$ edges. Let's denote the length of the shortest path from vertex $1$ to vertex $i$ as $d_i$.

You have to erase some edges of the graph so that at most $k$ edges remain. Let's call a vertex $i$ good if there still exists a path from $1$ to $i$ with length $d_i$ after erasing the edges.

Your goal is to erase the edges in such a way that the number of good vertices is maximized.

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($2 \le n \le 3 \cdot 10^5$, $1 \le m \le 3 \cdot 10^5$, $n - 1 \le m$, $0 \le k \le m$) — the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.

Then $m$ lines follow, each containing three integers $x$, $y$, $w$ ($1 \le x, y \le n$, $x \ne y$, $1 \le w \le 10^9$), denoting an edge connecting vertices $x$ and $y$ and having weight $w$.

The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).

-----Output-----

In the first line print $e$ — the number of edges that should remain in the graph ($0 \le e \le k$).

In the second line print $e$ distinct integers from $1$ to $m$ — the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.

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

Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5

Output
2
3 2

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

import sys
input = sys.stdin.readline
import heapq
from collections import defaultdict

n, m, k = list(map(int, input().split()))
edges = defaultdict(list)
dist = [float('inf')] * (n + 1)
dist[1] = 0
pq = []
for i in range(m):
    x, y, w = list(map(int, input().split()))
    edges[x].append((i + 1, y, w))
    edges[y].append((i + 1, x, w))

pq = [(0, 1, -1)]
res = []
c = 0
while pq:
    v, min_e, min_i = heapq.heappop(pq)
    if dist[min_e] == v:
        if min_i != -1:
            res.append(min_i)
            c += 1
        if c >= n - 1 or c == k:
            break
        for item in edges[min_e]:
            i, adj, w = item
            if dist[min_e] + w < dist[adj]:
                dist[adj] = dist[min_e] + w
                heapq.heappush(pq, (dist[adj], adj, i))

print(len(res))
if k > 0:
    print(' '.join(map(str, res)))


I found an interesting problem on https://codeforces.com/problemset/problem/1076/F:
Vova has taken his summer practice this year and now he should write a report on how it went.

Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly $n$ pages and the $i$-th page will include $x_i$ tables and $y_i$ formulas. The pages are numbered from $1$ to $n$.

Vova fills the pages one after another, he can't go filling page $i + 1$ before finishing page $i$ and he can't skip pages.

However, if he draws strictly more than $k$ tables in a row or writes strictly more than $k$ formulas in a row then he will get bored. Vova wants to rearrange tables and formulas in each page in such a way that he doesn't get bored in the process. Vova can't move some table or some formula to another page.

Note that the count doesn't reset on the start of the new page. For example, if the page ends with $3$ tables and the next page starts with $5$ tables, then it's counted as $8$ tables in a row.

Help Vova to determine if he can rearrange tables and formulas on each page in such a way that there is no more than $k$ tables in a row and no more than $k$ formulas in a row.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 3 \cdot 10^5$, $1 \le k \le 10^6$).

The second line contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^6$) — the number of tables on the $i$-th page.

The third line contains $n$ integers $y_1, y_2, \dots, y_n$ ($1 \le y_i \le 10^6$) — the number of formulas on the $i$-th page.

-----Output-----

Print "YES" if Vova can rearrange tables and formulas on each page in such a way that there is no more than $k$ tables in a row and no more than $k$ formulas in a row.

Otherwise print "NO".

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

Output
YES

Input
2 2
5 6
2 2

Output
NO

Input
4 1
4 1 10 1
3 2 10 1

Output
YES

-----Note-----

In the first example the only option to rearrange everything is the following (let table be 'T' and formula be 'F'):   page $1$: "TTFTTFT"  page $2$:...

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

def max(a, b):
	if a > b:
		return a
	else:
		return b
n, k = map(int, input().split())
x = [int(t) for t in input().split()]
y = [int(t) for t in input().split()]
f, s = 0, 0
for i in range(n):
    f = max(0, x[i] + f - k * y[i])
    s = max(0, y[i] + s - k * x[i])
    if f > k or s > k:
        print('NO')
        return
print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1077/A:
A frog is currently at the point $0$ on a coordinate axis $Ox$. It jumps by the following algorithm: the first jump is $a$ units to the right, the second jump is $b$ units to the left, the third jump is $a$ units to the right, the fourth jump is $b$ units to the left, and so on.

Formally:   if the frog has jumped an even number of times (before the current jump), it jumps from its current position $x$ to position $x+a$;  otherwise it jumps from its current position $x$ to position $x-b$.

Your task is to calculate the position of the frog after $k$ jumps.

But... One more thing. You are watching $t$ different frogs so you have to answer $t$ independent queries.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 1000$) — the number of queries.

Each of the next $t$ lines contain queries (one query per line).

The query is described as three space-separated integers $a, b, k$ ($1 \le a, b, k \le 10^9$) — the lengths of two types of jumps and the number of jumps, respectively.

-----Output-----

Print $t$ integers. The $i$-th integer should be the answer for the $i$-th query.

-----Example-----
Input
6
5 2 3
100 1 4
1 10 5
1000000000 1 6
1 1 1000000000
1 1 999999999

Output
8
198
-17
2999999997
0
1

-----Note-----

In the first query frog jumps $5$ to the right, $2$ to the left and $5$ to the right so the answer is $5 - 2 + 5 = 8$.

In the second query frog jumps $100$ to the right, $1$ to the left, $100$ to the right and $1$ to the left so the answer is $100 - 1 + 100 - 1 = 198$.

In the third query the answer is $1 - 10 + 1 - 10 + 1 = -17$.

In the fourth query the answer is $10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$.

In the fifth query all frog's jumps are neutralized by each other so the answer is $0$.

The sixth query is the same as the fifth but without the last jump so the answer is $1$.

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

t = int(input())
for cas in range(t):
    a, b, k = map(int, input().split())
    ans = (a-b)*(k//2)
    if(k%2==1):
        ans += a
    print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1077/B:
There is a house with $n$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $n$ integer numbers $a_1, a_2, \dots, a_n$, where $a_i = 1$ if in the $i$-th flat the light is on and $a_i = 0$ otherwise.

Vova thinks that people in the $i$-th flats are disturbed and cannot sleep if and only if $1 < i < n$ and $a_{i - 1} = a_{i + 1} = 1$ and $a_i = 0$.

Vova is concerned by the following question: what is the minimum number $k$ such that if people from exactly $k$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $k$.

-----Input-----

The first line of the input contains one integer $n$ ($3 \le n \le 100$) — the number of flats in the house.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($a_i \in \{0, 1\}$), where $a_i$ is the state of light in the $i$-th flat.

-----Output-----

Print only one integer — the minimum number $k$ such that if people from exactly $k$ pairwise distinct flats will turn off the light then nobody will be disturbed.

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

Output
2

Input
5
1 1 0 0 0

Output
0

Input
4
1 1 1 1

Output
0

-----Note-----

In the first example people from flats $2$ and $7$ or $4$ and $7$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.

There are no disturbed people in second and third examples.

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

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

ans = 0
for i in range(1, n-1):
  if A[i] == 0 and A[i-1] == 1 and A[i+1] == 1:
    A[i+1] = 0
    ans += 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1077/C:
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $a=[1, 3, 3, 7]$ is good because there is the element $a_4=7$ which equals to the sum $1 + 3 + 3$.

You are given an array $a$ consisting of $n$ integers. Your task is to print all indices $j$ of this array such that after removing the $j$-th element from the array it will be good (let's call such indices nice).

For example, if $a=[8, 3, 5, 2]$, the nice indices are $1$ and $4$:   if you remove $a_1$, the array will look like $[3, 5, 2]$ and it is good;  if you remove $a_4$, the array will look like $[8, 3, 5]$ and it is good.

You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of elements in the array $a$.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — elements of the array $a$.

-----Output-----

In the first line print one integer $k$ — the number of indices $j$ of the array $a$ such that after removing the $j$-th element from the array it will be good (i.e. print the number of the nice indices).

In the second line print $k$ distinct integers $j_1, j_2, \dots, j_k$ in any order — nice indices of the array $a$.

If there are no such indices in the array $a$, just print $0$ in the first line and leave the second line empty or do not print it at all.

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

Output
3
4 1 5
Input
4
8 3 5 2

Output
2
1 4

Input
5
2 1 2 4 3

Output
0

-----Note-----

In the first example you can remove any element with the value $2$ so the array will look like $[5, 1, 2, 2]$. The sum of this array is $10$ and there is an element equals to the sum of remaining elements ($5 = 1 + 2 + 2$).

In the second example you can remove $8$ so the array will look like $[3, 5, 2]$. The sum of this array is $10$...

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

import sys

input = sys.stdin.readline

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

count = {}

sum = 0
for i in range(n):
    if a[i] not in count.keys():
        count[a[i]] = 0
    count[a[i]] += 1

    sum += a[i]

ans = []

for i in range(n):
    sub = sum - a[i]
    if sub % 2 == 1:
        continue
    sub = int(sub/2)
    if sub in count.keys() and sub == a[i]:
        if count[sub] > 1:
            ans.append(str(i+1))
    elif sub in count.keys() and count[sub] >= 1:
        ans.append(str(i+1))

print(len(ans))
print(" ".join(ans))


I found an interesting problem on https://codeforces.com/problemset/problem/1077/D:
You are given an array $s$ consisting of $n$ integers.

You have to find any array $t$ of length $k$ such that you can cut out maximum number of copies of array $t$ from array $s$.

Cutting out the copy of $t$ means that for each element $t_i$ of array $t$ you have to find $t_i$ in $s$ and remove it from $s$. If for some $t_i$ you cannot find such element in $s$, then you cannot cut out one more copy of $t$. The both arrays can contain duplicate elements.

For example, if $s = [1, 2, 3, 2, 4, 3, 1]$ and $k = 3$ then one of the possible answers is $t = [1, 2, 3]$. This array $t$ can be cut out $2$ times.   To cut out the first copy of $t$ you can use the elements $[1, \underline{\textbf{2}}, 3, 2, 4, \underline{\textbf{3}}, \underline{\textbf{1}}]$ (use the highlighted elements). After cutting out the first copy of $t$ the array $s$ can look like $[1, 3, 2, 4]$.  To cut out the second copy of $t$ you can use the elements $[\underline{\textbf{1}}, \underline{\textbf{3}}, \underline{\textbf{2}}, 4]$. After cutting out the second copy of $t$ the array $s$ will be $[4]$.

Your task is to find such array $t$ that you can cut out the copy of $t$ from $s$ maximum number of times. If there are multiple answers, you may choose any of them.

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of elements in $s$ and the desired number of elements in $t$, respectively.

The second line of the input contains exactly $n$ integers $s_1, s_2, \dots, s_n$ ($1 \le s_i \le 2 \cdot 10^5$).

-----Output-----

Print $k$ integers — the elements of array $t$ such that you can cut out maximum possible number of copies of this array from $s$. If there are multiple answers, print any of them. The required array $t$ can contain duplicate elements. All the elements of $t$ ($t_1, t_2, \dots, t_k$) should satisfy the following condition: $1 \le t_i \le 2 \cdot 10^5$.

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

Output
1 2 3

Input
10 4
1 3 1 3 10 3 7 7 12...

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

from operator import itemgetter
#int(input())
#map(int,input().split())
#[list(map(int,input().split())) for i in range(q)]
#print("YES" * ans + "NO" * (1-ans))
n,k =  map(int,input().split())
si = list(map(int,input().split()))
num = 10**5 * 2 + 1
ai = [0] * num
for i in range(n):
    ai[si[i]] += 1
num3 = num
num = max(ai) + 1
ai2 = [[] for i in range(num)]
for i in range(num3):
    if ai[i] != 0:
        ai2[ai[i]] += [[i,1,ai[i]]]
i = num-1
while k > 0:
    for j in ai2[i]:
        if k == 0:
            break
        num2 =  j[2] // (j[1]+1)
        ai2[num2] += [[j[0],j[1]+1,j[2]]]
        print(j[0],end=" ")
        k -= 1
    i -= 1


I found an interesting problem on https://codeforces.com/problemset/problem/1077/E:
Polycarp has prepared $n$ competitive programming problems. The topic of the $i$-th problem is $a_i$, and some problems' topics may coincide.

Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics.

Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:  number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;  the total number of problems in all the contests should be maximized.

Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.

-----Input-----

The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of problems Polycarp has prepared.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) where $a_i$ is the topic of the $i$-th problem.

-----Output-----

Print one integer — the maximum number of problems in the set of thematic contests.

-----Examples-----
Input
18
2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10

Output
14

Input
10
6 6 6 3 6 1000000000 3 3 6 6

Output
9

Input
3
1337 1337 1337

Output
3

-----Note-----

In the first example the optimal sequence of contests is: $2$ problems of the topic $1$, $4$ problems of the topic $2$, $8$ problems of the topic $10$.

In the second example the optimal sequence of contests is: $3$ problems of the topic $3$, $6$ problems of the topic $6$.

In the third example you can take all the problems with the topic $1337$ (the number of such problems is $3$ so the answer is $3$) and host a single contest.

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

n = int(input())
nums = list(map(int, input().split()))
mapa = {}

for nu in nums:
	mapa[nu] = mapa.get(nu, 0) + 1
li = [mapa[x] for x in mapa]

li.sort(reverse=True)

a = li[0]
b = li[0]//2
c = 1
while len(li) > c:
	if b == 0:
		break
	if li[c] >= b:
		silo = b * (2**(c+1) - 1)
		a = max(a, silo)
		b = b//2
		c += 1
	else:
		silo = li[c] * (2**(c+1) - 1)
		a = max(a, silo)
		b = li[c]//2
		c += 1
print(a)


I found an interesting problem on https://codeforces.com/problemset/problem/1077/F1:
The only difference between easy and hard versions is the constraints.

Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.

Vova wants to repost exactly $x$ pictures in such a way that:   each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova;  the sum of beauty values of reposted pictures is maximum possible.

For example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.

Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.

-----Input-----

The first line of the input contains three integers $n, k$ and $x$ ($1 \le k, x \le n \le 200$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the beauty of the $i$-th picture.

-----Output-----

Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.

Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.

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

Output
18

Input
6 1 5
10 30 30 70 10 10

Output
-1

Input
4 3 1
1 100 1 1

Output
100

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

n, k, x = list(map(int, input().split()))
a = [None] + list(map(int, input().split()))
dp = [[-1] * (n + 1) for i in range(x + 1)]
dp[0][0] = 0
for i in range(1, x + 1):
    for j in range(1, n + 1):
        dp[i][j] = max(dp[i - 1][j2] for j2 in range(max(0, j - k), j))
        if dp[i][j] != -1: dp[i][j] += a[j]
ans = max(dp[x][j] for j in range(n - k + 1, n + 1))
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1077/F2:
The only difference between easy and hard versions is the constraints.

Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.

Vova wants to repost exactly $x$ pictures in such a way that:   each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova;  the sum of beauty values of reposted pictures is maximum possible.

For example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.

Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.

-----Input-----

The first line of the input contains three integers $n, k$ and $x$ ($1 \le k, x \le n \le 5000$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.

The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the beauty of the $i$-th picture.

-----Output-----

Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.

Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.

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

Output
18

Input
6 1 5
10 30 30 70 10 10

Output
-1

Input
4 3 1
1 100 1 1

Output
100

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

n, k, x = list(map(int, input().split()))
a = [None] + list(map(int, input().split()))

lo, hi = 0, 10 ** 9 * 5000
q = [None] * (n + 1)

def get(mid):
    f, r = 0, 0
    q[0] = 0, 0, 0
    for i in range(1, n + 1):
        if q[r][2] == i - k - 1: r += 1
        cur = q[r][0] + a[i] - mid, q[r][1] + 1, i
        while r <= f and q[f] <= cur: f -= 1
        f += 1
        q[f] = cur
    if q[r][2] == n - k: r += 1
    return q[r]

while lo < hi:
    mid = (lo + hi + 1) >> 1
    _, cnt, _ = get(mid)
    if cnt >= x:
        lo = mid
    else:
        hi = mid - 1

sm, _, _ = get(lo)
ans = max(-1, sm + x * lo)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1078/B:
You have a set of $n$ weights. You know that their masses are $a_1$, $a_2$, ..., $a_n$ grams, but you don't know which of them has which mass. You can't distinguish the weights.

However, your friend does know the mass of each weight. You can ask your friend to give you exactly $k$ weights with the total mass $m$ (both parameters $k$ and $m$ are chosen by you), and your friend will point to any valid subset of weights, if it is possible.

You are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 100$) — the number of weights.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) — the masses of the weights.

-----Output-----

Print the maximum number of weights you can learn the masses for after making a single query.

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

Output
2

Input
6
1 2 4 4 4 9

Output
2

-----Note-----

In the first example we can ask for a subset of two weights with total mass being equal to $4$, and the only option is to get $\{2, 2\}$.

Another way to obtain the same result is to ask for a subset of two weights with the total mass of $5$ and get $\{1, 4\}$. It is easy to see that the two remaining weights have mass of $2$ grams each.

In the second example we can ask for a subset of two weights with total mass being $8$, and the only answer is $\{4, 4\}$. We can prove it is not possible to learn masses for three weights in one query, but we won't put the proof here.

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

from collections import defaultdict

def calcBinomials(N):
    nonlocal binom
    N += 1
    binom = [[0]*N for _ in range(N)]
    for n in range(N):
        binom[n][0] = binom[n][n] = 1
        for k in range(1, n):
            binom[n][k] = binom[n-1][k] + binom[n-1][k-1]

n = int(input())
a = list(map(int, input().split()))
S, res = sum(a), 0
dp = [defaultdict(lambda: 0) for _ in range(S+1)]
dp[0][0] = 1

cnt = {_:a.count(_) for _ in a}
for x in a:
    for i in range(len(dp)-1-x, -1, -1):
        for k, v in list(dp[i].items()):
            dp[i+x][k+1] += v

calcBinomials(n)
for x, c in list(cnt.items()):
    for i in range(1, c+1):
        if dp[x*i][i] == binom[c][i] or dp[S - x*i][n-i] == binom[c][c-i]:
            res = max(res, i)
if len(cnt) <= 2: res = n
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1080/A:
Petya is having a party soon, and he has decided to invite his $n$ friends.

He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with $k$ sheets. That is, each notebook contains $k$ sheets of either red, green, or blue.

Find the minimum number of notebooks that Petya needs to buy to invite all $n$ of his friends.

-----Input-----

The first line contains two integers $n$ and $k$ ($1\leq n, k\leq 10^8$) — the number of Petya's friends and the number of sheets in each notebook respectively.

-----Output-----

Print one number — the minimum number of notebooks that Petya needs to buy.

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

Output
10

Input
15 6

Output
38

-----Note-----

In the first example, we need $2$ red notebooks, $3$ green notebooks, and $5$ blue notebooks.

In the second example, we need $5$ red notebooks, $13$ green notebooks, and $20$ blue notebooks.

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

import sys
from math import floor, ceil

input = sys.stdin.readline

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

print(ceil((n*2)/k) + ceil((n*5)/k) + ceil((n*8)/k))


I found an interesting problem on https://codeforces.com/problemset/problem/1080/B:
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.

Recently, she was presented with an array $a$ of the size of $10^9$ elements that is filled as follows:   $a_1 = -1$  $a_2 = 2$  $a_3 = -3$  $a_4 = 4$  $a_5 = -5$  And so on ...

That is, the value of the $i$-th element of the array $a$ is calculated using the formula $a_i = i \cdot (-1)^i$.

She immediately came up with $q$ queries on this array. Each query is described with two numbers: $l$ and $r$. The answer to a query is the sum of all the elements of the array at positions from $l$ to $r$ inclusive.

Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.

Help her find the answers!

-----Input-----

The first line contains a single integer $q$ ($1 \le q \le 10^3$) — the number of the queries.

Each of the next $q$ lines contains two integers $l$ and $r$ ($1 \le l \le r \le 10^9$) — the descriptions of the queries.

-----Output-----

Print $q$ lines, each containing one number — the answer to the query.

-----Example-----
Input
5
1 3
2 5
5 5
4 4
2 3

Output
-2
-2
-5
4
-1

-----Note-----

In the first query, you need to find the sum of the elements of the array from position $1$ to position $3$. The sum is equal to $a_1 + a_2 + a_3 = -1 + 2 -3 = -2$.

In the second query, you need to find the sum of the elements of the array from position $2$ to position $5$. The sum is equal to $a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$.

In the third query, you need to find the sum of the elements of the array from position $5$ to position $5$. The sum is equal to $a_5 = -5$.

In the fourth query, you need to find the sum of the elements of the array from position $4$ to position $4$. The sum is equal to $a_4 = 4$.

In the fifth query, you need to find the sum of the elements of the array from position $2$...

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

def s(k):
	if k % 2 == 0:
		return k // 2
	else:
		return - (k + 1) // 2

for i in range(int(input())):
	l, r = list(map(int, input().split()))
	print(s(r) - s(l - 1))


I found an interesting problem on https://codeforces.com/problemset/problem/1080/C:
Recently, Masha was presented with a chessboard with a height of $n$ and a width of $m$.

The rows on the chessboard are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. Therefore, each cell can be specified with the coordinates $(x,y)$, where $x$ is the column number, and $y$ is the row number (do not mix up).

Let us call a rectangle with coordinates $(a,b,c,d)$ a rectangle lower left point of which has coordinates $(a,b)$, and the upper right one — $(c,d)$.

The chessboard is painted black and white as follows:

 [Image]

 An example of a chessboard.

Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat — they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle $(x_1,y_1,x_2,y_2)$. Then after him Denis spilled black paint on the rectangle $(x_3,y_3,x_4,y_4)$.

To spill paint of color $color$ onto a certain rectangle means that all the cells that belong to the given rectangle become $color$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).

Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 10^3$) — the number of test cases.

Each of them is described in the following format:

The first line contains two integers $n$ and $m$ ($1 \le n,m \le 10^9$) — the size of the board.

The second line contains four integers $x_1$, $y_1$, $x_2$, $y_2$ ($1 \le x_1 \le x_2 \le m, 1 \le y_1 \le y_2 \le n$) — the coordinates of the rectangle, the white paint was...

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

def fis(sq):
    if sq[2] < sq[0] or sq[3] < sq[1]:
        return [0, 0]
    sc = (sq[0] + sq[1]) % 2
    fc = (sq[2] + sq[3]) % 2
    sxl = sq[2] - sq[0] + 1
    syl = sq[3] - sq[1] + 1
    hf = (sxl * syl) // 2
    cp = -1
    if sc == fc and (sxl+syl) % 2 == 0 and sxl % 2 == 1:
        cp = sc
    return([hf + (1 if cp == 0 else 0), hf + (1 if cp == 1 else 0)])

t = int(input())
for i in range(t):
    n, m = [int(x) for x in input().split()]
    wco = [int(x) for x in input().split()]
    bco = [int(x) for x in input().split()]
    wf, bf = fis([1, 1, m, n])
    btw = fis(wco)[1]
    wtb = fis(bco)[0]
    bnac = [max(wco[0], bco[0]), max(wco[1], bco[1]), min(wco[2], bco[2]), min(wco[3], bco[3])]
    bna = fis(bnac)[1]
    print(wf+btw-wtb-bna, bf+wtb-btw+bna)


I found an interesting problem on https://codeforces.com/problemset/problem/1080/D:
Recently, Olya received a magical square with the size of $2^n\times 2^n$.

It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly $k$ splitting operations.

A Splitting operation is an operation during which Olya takes a square with side $a$ and cuts it into 4 equal squares with side $\dfrac{a}{2}$. If the side of the square is equal to $1$, then it is impossible to apply a splitting operation to it (see examples for better understanding).

Olya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.

The condition of Olya's happiness will be satisfied if the following statement is fulfilled:

Let the length of the side of the lower left square be equal to $a$, then the length of the side of the right upper square should also be equal to $a$. There should also be a path between them that consists only of squares with the side of length $a$. All consecutive squares on a path should have a common side.

Obviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly $k$ splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 10^3$) — the number of tests.

Each of the following $t$ lines contains two integers $n_i$ and $k_i$ ($1 \le n_i \le 10^9, 1 \le k_i \le 10^{18}$) — the description of the $i$-th test, which means that initially Olya's square has size of $2^{n_i}\times 2^{n_i}$ and Olya's sister asks her to do exactly $k_i$ splitting operations.

-----Output-----

Print $t$ lines, where in the $i$-th line you should output "YES" if it is possible to perform $k_i$ splitting operations in the...

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

case = int(input())
for i in range(case):
	f = [0] * 32
	g = [0] * 32
	success = False
	n,k = map(int,input().split())
	ans = n
	for i in range(1,n):
		f[i] = f[i - 1] * 4 + 1
		if f[i] >= k:
			success = True
			break
	for i in range(1,n + 1):
		if k < (1 << i) - 1:
			break
		k = k - (1 << i) + 1
		ans = ans - 1
	for i in range(n - 1,ans - 1,-1):
		if i >= 32 or (i and f[i] == 0):
			success = True
			break
		g[i] = 1 if i == n - 1 else g[i + 1] * 2 + 3
		k = k - f[i] * g[i]
		if k <= 0:
			success = True
			break
	print("YES %d"%ans if success else "NO");


I found an interesting problem on https://codeforces.com/problemset/problem/1081/A:
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.

He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer $x$ that $x<n$ and $x$ is not a divisor of $n$, then subtract $x$ from $n$. The goal of the player is to minimize the value of $n$ in the end.

Soon, Chouti found the game trivial. Can you also beat the game?

-----Input-----

The input contains only one integer in the first line: $v$ ($1 \le v \le 10^9$), the initial value of $n$.

-----Output-----

Output a single integer, the minimum value of $n$ the player can get.

-----Examples-----
Input
8

Output
1

Input
1

Output
1

-----Note-----

In the first example, the player can choose $x=3$ in the first turn, then $n$ becomes $5$. He can then choose $x=4$ in the second turn to get $n=1$ as the result. There are other ways to get this minimum. However, for example, he cannot choose $x=2$ in the first turn because $2$ is a divisor of $8$.

In the second example, since $n=1$ initially, the player can do nothing.

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

n = int(input())
if n == 2:
    print(2)
else:
    print(1)


I found an interesting problem on https://codeforces.com/problemset/problem/1081/B:
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.

Chouti remembered that $n$ persons took part in that party. To make the party funnier, each person wore one hat among $n$ kinds of weird hats numbered $1, 2, \ldots n$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.

After the party, the $i$-th person said that there were $a_i$ persons wearing a hat differing from his own.

It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $b_i$ be the number of hat type the $i$-th person was wearing, Chouti wants you to find any possible $b_1, b_2, \ldots, b_n$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^5$), the number of persons in the party.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le n-1$), the statements of people.

-----Output-----

If there is no solution, print a single line "Impossible".

Otherwise, print "Possible" and then $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$).

If there are multiple answers, print any of them.

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

Output
Possible
1 1 1
Input
5
3 3 2 2 2

Output
Possible
1 1 2 2 2
Input
4
0 1 2 3

Output
Impossible

-----Note-----

In the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $1$.

In the answer to the second example, the first and the second person wore the hat with type $1$ and all other wore a hat of type $2$.

So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their...

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

num = int(input())
nums = input()
statement = [int(i) for i in nums.split()]

log = {}
group_num = {}
anchor = 1
total = num
status = 'Possible'
ans = []
for i, s in enumerate(statement):
    if s not in log or group_num[s] == 0:
        log[s] = anchor
        anchor += 1
        group_num[s] = num - s
        total -= group_num[s]
        if total < 0:
            status = 'Impossible'
            break
    ans.append(log[s])
    group_num[s] -= 1

print(status)
if status == 'Possible':
    for i in range(num - 1):
        print(ans[i], end=' ')
    print(ans[num - 1])


I found an interesting problem on https://codeforces.com/problemset/problem/1081/C:
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.

There are $n$ bricks lined in a row on the ground. Chouti has got $m$ paint buckets of different colors at hand, so he painted each brick in one of those $m$ colors.

Having finished painting all bricks, Chouti was satisfied. He stood back and decided to find something fun with these bricks. After some counting, he found there are $k$ bricks with a color different from the color of the brick on its left (the first brick is not counted, for sure).

So as usual, he needs your help in counting how many ways could he paint the bricks. Two ways of painting bricks are different if there is at least one brick painted in different colors in these two ways. Because the answer might be quite big, you only need to output the number of ways modulo $998\,244\,353$.

-----Input-----

The first and only line contains three integers $n$, $m$ and $k$ ($1 \leq n,m \leq 2000, 0 \leq k \leq n-1$) — the number of bricks, the number of colors, and the number of bricks, such that its color differs from the color of brick to the left of it.

-----Output-----

Print one integer — the number of ways to color bricks modulo $998\,244\,353$.

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

Output
3

Input
3 2 1

Output
4

-----Note-----

In the first example, since $k=0$, the color of every brick should be the same, so there will be exactly $m=3$ ways to color the bricks.

In the second example, suppose the two colors in the buckets are yellow and lime, the following image shows all $4$ possible colorings. [Image]

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

n,m,k = map(int, input().split())
import math
print((math.factorial(n-1) // math.factorial(n-k-1) // math.factorial(k) * m * (m-1) ** k) % 998244353)


I found an interesting problem on https://codeforces.com/problemset/problem/1081/D:
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.

You are given a connected undirected graph with $n$ vertices and $m$ weighted edges. There are $k$ special vertices: $x_1, x_2, \ldots, x_k$.

Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.

For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.

The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($2 \leq k \leq n \leq 10^5$, $n-1 \leq m \leq 10^5$) — the number of vertices, the number of edges and the number of special vertices.

The second line contains $k$ distinct integers $x_1, x_2, \ldots, x_k$ ($1 \leq x_i \leq n$).

Each of the following $m$ lines contains three integers $u$, $v$ and $w$ ($1 \leq u,v \leq n, 1 \leq w \leq 10^9$), denoting there is an edge between $u$ and $v$ of weight $w$. The given graph is undirected, so an edge $(u, v)$ can be used in the both directions.

The graph may have multiple edges and self-loops.

It is guaranteed, that the graph is connected.

-----Output-----

The first and only line should contain $k$ integers. The $i$-th integer is the distance between $x_i$ and the farthest special vertex from it.

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

Output
2 2

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

Output
3 3 3

-----Note-----

In the first example, the distance between vertex $1$ and $2$ equals to $2$ because one can walk through the edge of weight $2$ connecting them. So the distance to the farthest node for both $1$ and $2$ equals to $2$.

In the second example, one can find that distance between $1$ and $2$,...

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

import sys
def int_reader():
    yield from (int(d) for d in sys.stdin.read().split())

ints = int_reader()
n, m, k = [next(ints) for i in range(3)]
sp = {next(ints) for i in range(k)}

edges = []
for i in range(m):
    u, v, w = [next(ints) for j in range(3)]
    edges.append((w, u, v))
edges.sort()

fu = [i for i in range(n+1)]
def find(x):
    S = []
    while fu[x] != x:
        S.append(x)
        x = fu[x]
    for y in S:
        fu[y] = x
    return x
def union(a, b):
    if b in sp:
        a, b = b, a
    fu[b] = a

ans = 0
for e in edges:
    a, b = find(e[1]), find(e[2])
    if a == b: continue
    if a in sp and b in sp:
        ans = e[0]
    union(a, b)
print((str(ans) + ' ') * k)


I found an interesting problem on https://codeforces.com/problemset/problem/1081/E:
Chouti is working on a strange math problem.

There was a sequence of $n$ positive integers $x_1, x_2, \ldots, x_n$, where $n$ is even. The sequence was very special, namely for every integer $t$ from $1$ to $n$, $x_1+x_2+...+x_t$ is a square of some integer number (that is, a perfect square).

Somehow, the numbers with odd indexes turned to be missing, so he is only aware of numbers on even positions, i.e. $x_2, x_4, x_6, \ldots, x_n$. The task for him is to restore the original sequence. Again, it's your turn to help him.

The problem setter might make mistakes, so there can be no possible sequence at all. If there are several possible sequences, you can output any.

-----Input-----

The first line contains an even number $n$ ($2 \le n \le 10^5$).

The second line contains $\frac{n}{2}$ positive integers $x_2, x_4, \ldots, x_n$ ($1 \le x_i \le 2 \cdot 10^5$).

-----Output-----

If there are no possible sequence, print "No".

Otherwise, print "Yes" and then $n$ positive integers $x_1, x_2, \ldots, x_n$ ($1 \le x_i \le 10^{13}$), where $x_2, x_4, \ldots, x_n$ should be same as in input data. If there are multiple answers, print any.

Note, that the limit for $x_i$ is larger than for input data. It can be proved that in case there is an answer, there must be a possible sequence satisfying $1 \le x_i \le 10^{13}$.

-----Examples-----
Input
6
5 11 44

Output
Yes
4 5 16 11 64 44

Input
2
9900

Output
Yes
100 9900

Input
6
314 1592 6535

Output
No

-----Note-----

In the first example   $x_1=4$  $x_1+x_2=9$  $x_1+x_2+x_3=25$  $x_1+x_2+x_3+x_4=36$  $x_1+x_2+x_3+x_4+x_5=100$  $x_1+x_2+x_3+x_4+x_5+x_6=144$  All these numbers are perfect squares.

In the second example, $x_1=100$, $x_1+x_2=10000$. They are all perfect squares. There're other answers possible. For example, $x_1=22500$ is another answer.

In the third example, it is possible to show, that no such sequence exists.

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

def bi(a, x):
    l  = -1
    u  = len(a)

    while(u-l>1):
        md = int((l+u) / 2)
        if x >= a[md]:
            l = md
        else:
            u = md
    return u

d = {}
for x in range(1, 100000):

    for a in range(1, 500):
        diff = a*a + 2*a*x

        if diff > 200000:
            break

        if diff  not in d:
            d[diff] = []

        d[diff].append(x*x)

def solve(a, d):
    cur = 0
    ans = ''

    for x in a:
        if x not in d:
            return 'No', ''

        next_ = bi(d[x], cur)

        if next_ == len(d[x]):
            return 'No', ''

        next_ = d[x][next_]
        ans  +=  str(next_ - cur) + ' ' + str(x) +' '
        cur = next_ + x

    return 'Yes', ans

n   = int(input())
a   = list(map(int, input().split()))
ans = solve(a, d)

print(ans[0])
print(ans[1])


I found an interesting problem on https://codeforces.com/problemset/problem/1082/A:
Vasya is reading a e-book. The file of the book consists of $n$ pages, numbered from $1$ to $n$. The screen is currently displaying the contents of page $x$, and Vasya wants to read the page $y$. There are two buttons on the book which allow Vasya to scroll $d$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $10$ pages, and $d = 3$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.

Help Vasya to calculate the minimum number of times he needs to press a button to move to page $y$.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 10^3$) — the number of testcases.

Each testcase is denoted by a line containing four integers $n$, $x$, $y$, $d$ ($1\le n, d \le 10^9$, $1 \le x, y \le n$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

-----Output-----

Print one line for each test.

If Vasya can move from page $x$ to page $y$, print the minimum number of times he needs to press a button to do it. Otherwise print $-1$.

-----Example-----
Input
3
10 4 5 2
5 1 3 4
20 4 19 3

Output
4
-1
5

-----Note-----

In the first test case the optimal sequence is: $4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$.

In the second test case it is possible to get to pages $1$ and $5$.

In the third test case the optimal sequence is: $4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$.

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/1082/B:
Vova has won $n$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.

The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.

Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 10^5$) — the number of trophies.

The second line contains $n$ characters, each of them is either G or S. If the $i$-th character is G, then the $i$-th trophy is a golden one, otherwise it's a silver trophy.

-----Output-----

Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.

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

Output
7

Input
4
GGGG

Output
4

Input
3
SSS

Output
0

-----Note-----

In the first example Vova has to swap trophies with indices $4$ and $10$. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is $7$.

In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is $4$.

In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than $0$.

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

n = int(input())
ks  =input().strip()

prev_g_seq_len = 0
cur__g_seq_len = 0
prev_is_s = True

res = 0
for j in ks:
    if j == 'S':
        prev_g_seq_len = cur__g_seq_len
        cur__g_seq_len = 0
        # prev_is_s = True
    else:
        cur__g_seq_len += 1
        # prev_is_s = False
    res = max (res, prev_g_seq_len + cur__g_seq_len + 1)

mmm = ks.count('G')
res = min(mmm, res)

print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1082/C:
A multi-subject competition is coming! The competition has $m$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students.

He has $n$ candidates. For the $i$-th person he knows subject $s_i$ the candidate specializes in and $r_i$ — a skill level in his specialization (this level can be negative!).

The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same.

Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.

(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition).

-----Input-----

The first line contains two integers $n$ and $m$ ($1 \le n \le 10^5$, $1 \le m \le 10^5$) — the number of candidates and the number of subjects.

The next $n$ lines contains two integers per line: $s_i$ and $r_i$ ($1 \le s_i \le m$, $-10^4 \le r_i \le 10^4$) — the subject of specialization and the skill level of the $i$-th candidate.

-----Output-----

Print the single integer — the maximum total sum of skills of delegates who form a valid delegation (according to rules above) or $0$ if every valid non-empty delegation has negative sum.

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

Output
22

Input
5 3
2 6
3 6
2 5
3 5
1 11

Output
23

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

Output
0

-----Note-----

In the first example it's optimal to choose candidates $1$, $2$, $3$, $4$, so two of them specialize in the $2$-nd subject and other two in the $3$-rd. The total sum is $6 + 6 + 5 + 5 = 22$.

In the second example it's optimal to choose candidates $1$, $2$ and $5$. One person in each...

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

def ii():
    return int(input())
def mi():
    return list(map(int, input().split()))
def li():
    return list(mi())

n, m = mi()
a = [[] for i in range(m + 1)]
for i in range(n):
    s, r = mi()
    a[s].append(r)

ch = [0] * (n + 1)
for i in range(1, m + 1):
    a[i].sort(reverse=True)
    pr = 0
    for j in range(len(a[i])):
        pr += a[i][j]
        if pr > 0:
            ch[j + 1] += pr

ans = max(ch)
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1082/D:
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.

The graph is connected if and only if there exists a path between every pair of vertices.

The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.

The degree of a vertex is the number of edges incident to it.

Given a sequence of $n$ integers $a_1, a_2, \dots, a_n$ construct a connected undirected graph of $n$ vertices such that:  the graph contains no self-loops and no multiple edges;  the degree $d_i$ of the $i$-th vertex doesn't exceed $a_i$ (i.e. $d_i \le a_i$);  the diameter of the graph is maximum possible.

Output the resulting graph or report that no solution exists.

-----Input-----

The first line contains a single integer $n$ ($3 \le n \le 500$) — the number of vertices in the graph.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n - 1$) — the upper limits to vertex degrees.

-----Output-----

Print "NO" if no graph can be constructed under the given conditions.

Otherwise print "YES" and the diameter of the resulting graph in the first line.

The second line should contain a single integer $m$ — the number of edges in the resulting graph.

The $i$-th of the next $m$ lines should contain two integers $v_i, u_i$ ($1 \le v_i, u_i \le n$, $v_i \neq u_i$) — the description of the $i$-th edge. The graph should contain no multiple edges — for each pair $(x, y)$ you output, you should output no more pairs $(x, y)$ or $(y, x)$.

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

Output
YES 2
2
1 2
2 3

Input
5
1 4 1 1 1

Output
YES 2
4
1 2
3 2
4 2
5 2

Input
3
1 1 1

Output
NO

-----Note-----

Here are the graphs for the first two example cases. Both have diameter of $2$. [Image] $d_1 = 1 \le a_1 = 2$

$d_2 = 2 \le a_2 = 2$

$d_3 = 1 \le a_3 = 2$  [Image] $d_1 = 1 \le a_1 = 1$

$d_2 = 4 \le a_2 = 4$

$d_3 = 1 \le a_3 = 1$

$d_4 = 1 \le a_4 = 1$

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

n = int(input())
a = [0]
sum = 0
for i in map(int, input().split()) :
    a.append(i)
    sum += i
last = 0
ans = 0
edge = []
for i in range(1, n + 1, 1) :
    if(a[i] == 1) :
        last = i
a[last] = 0
for i in range(1, n + 1, 1) :
    if(a[i] > 1) :
        if(last) :
            edge.append([last, i])
            ans += 1
        last = i
for i in range(1, n + 1, 1) :
    if(a[i] == 1 and last) :
        edge.append([last, i])
        last = 0
        a[i] = 0
        ans += 1
for i in range(1, n + 1, 1) :
    for j in range(1, n + 1, 1) :
        if(a[j] == 1 and a[i] > 2) :
            edge.append([i, j])
            a[i] -= 1
            a[j] -= 1
if(len(edge) != n - 1) :
    print("NO")
else :
    print("YES", ans)
    print(len(edge))
    for i in edge :
        print(i[0], i[1])


I found an interesting problem on https://codeforces.com/problemset/problem/1082/E:
You are given array $a$ of length $n$. You can choose one segment $[l, r]$ ($1 \le l \le r \le n$) and integer value $k$ (positive, negative or even zero) and change $a_l, a_{l + 1}, \dots, a_r$ by $k$ each (i.e. $a_i := a_i + k$ for each $l \le i \le r$).

What is the maximum possible number of elements with value $c$ that can be obtained after one such operation?

-----Input-----

The first line contains two integers $n$ and $c$ ($1 \le n \le 5 \cdot 10^5$, $1 \le c \le 5 \cdot 10^5$) — the length of array and the value $c$ to obtain.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 5 \cdot 10^5$) — array $a$.

-----Output-----

Print one integer — the maximum possible number of elements with value $c$ which can be obtained after performing operation described above.

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

Output
6

Input
3 2
6 2 6

Output
2

-----Note-----

In the first example we can choose any segment and $k = 0$. The array will stay same.

In the second example we can choose segment $[1, 3]$ and $k = -4$. The array will become $[2, -2, 2]$.

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

# coding=utf-8

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

ans = [0] * 500001
res = 0

for i in map(int, input().split()):
    ans[i] = max(ans[i], ans[c])
    ans[i] += 1
    res = max(res, ans[i] - ans[c])

print(res + ans[c])


I found an interesting problem on https://codeforces.com/problemset/problem/1082/G:
Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of $n$ vertices and $m$ edges.

The weight of the $i$-th vertex is $a_i$.

The weight of the $i$-th edge is $w_i$.

A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.

The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.

-----Input-----

The first line contains two numbers $n$ and $m$ ($1 \le n \le 10^3, 0 \le m \le 10^3$) - the number of vertices and edges in the graph, respectively.

The next line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) - the weights of the vertices of the graph.

The following $m$ lines contain edges: the $i$-e edge is defined by a triple of integers $v_i, u_i, w_i$ ($1 \le v_i, u_i \le n, 1 \le w_i \le 10^9, v_i \neq u_i$). This triple means that between the vertices $v_i$ and $u_i$ there is an edge of weight $w_i$. It is guaranteed that the graph does not contain loops and multiple edges.

-----Output-----

Print one integer — the maximum weight of the subgraph of the given graph.

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

Output
8

Input
3 3
9 7 8
1 2 1
2 3 2
1 3 3

Output
0

-----Note-----

In the first test example, the optimal subgraph consists of the vertices ${1, 3, 4}$ and has weight $4 + 4 + 5 - (1 + 2 + 2) = 8$. In the second test case, the optimal subgraph is empty.

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

from collections import deque

def addedge(u, v, value):
	nonlocal e
	a = [v, value, None]
	b = [u, 0, a]
	a[2] = b
	e[u].append(a)
	e[v].append(b)

inf = 2 * (10 ** 12)
ans = 0
n, m = list(map(int, input().split()))
e = [[] for i in range(n + m + 2)]
a = tuple(map(int, input().split()))
S, T = 0, m + n + 1
for i in range(1, m + 1):
	u, v, w = list(map(int, input().split()))
	ans += w
	addedge(i, u + m, inf)
	addedge(i, v + m, inf)
	addedge(S, i, w)
for i in range(m + 1, T):
	addedge(i, T, a[i - m - 1])
# for i in range(n + m + 2):
# 	for edge in e[i]:
# 		print('%d to %d w %d' % (i, edge[0] if edge[0] <= m else edge[0] - m, edge[1]))

lvl = None
def bfs():
	nonlocal e, lvl
	lvl = [0] * (n + m + 2)
	q = deque([0])
	while q:
		node = q.popleft()
		# print('node = %d' % node)
		for edge in e[node]:
			if edge[0] != 0 and lvl[edge[0]] == 0 and edge[1]:
				lvl[edge[0]] = lvl[node] + 1
				q.append(edge[0])
	# print(lvl)

def dfs(node, maxdelta):
	nonlocal e, lvl
	if node == T:
		return maxdelta
	delta = 0
	for edge in e[node]:
		if lvl[edge[0]] == lvl[node] + 1 and edge[1]:
			tmp = dfs(edge[0], min(maxdelta, edge[1]))
			if tmp > 0:
				edge[1] -= tmp
				edge[2][1] += tmp
				maxdelta -= tmp
				delta += tmp
			if maxdelta == 0:
				break
	return delta

flow = 0
while 1:
	bfs()
	tmp = dfs(0, inf)
	if tmp == 0:
		break
	flow += tmp
ans -= flow
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1083/B:
Recently, the Fair Nut has written $k$ strings of length $n$, consisting of letters "a" and "b". He calculated $c$ — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.

Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $s$ and not bigger than string $t$. He is interested: what is the maximum value of $c$ that he could get.

A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: $a$ is a prefix of $b$, but $a \ne b$; in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq n \leq 5 \cdot 10^5$, $1 \leq k \leq 10^9$).

The second line contains a string $s$ ($|s| = n$) — the string consisting of letters "a" and "b.

The third line contains a string $t$ ($|t| = n$) — the string consisting of letters "a" and "b.

It is guaranteed that string $s$ is lexicographically not bigger than $t$.

-----Output-----

Print one number — maximal value of $c$.

-----Examples-----
Input
2 4
aa
bb

Output
6

Input
3 3
aba
bba

Output
8

Input
4 5
abbb
baaa

Output
8

-----Note-----

In the first example, Nut could write strings "aa", "ab", "ba", "bb". These $4$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $6$ strings.

In the second example, Nut could write strings "aba", "baa", "bba".

In the third example, there are only two different strings that Nut could write. If both of them are written, $c=8$.

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

n, k = list(map(int, input().split()))
s = input()
t = input()
Sum = -1
pos = 0
ans = 0
while pos < n and s[pos] == t[pos]:
    pos += 1
    ans += 1
for i in range(pos, n):
    Sum = Sum * 2 + 1 - ord(s[i]) + ord(t[i])
    if Sum + 2 >= k:
        ans += (n - i) * k
        break
    else:
        ans += Sum + 2
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1084/A:
The Fair Nut lives in $n$ story house. $a_i$ people live on the $i$-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.

It was decided that elevator, when it is not used, will stay on the $x$-th floor, but $x$ hasn't been chosen yet. When a person needs to get from floor $a$ to floor $b$, elevator follows the simple algorithm:   Moves from the $x$-th floor (initially it stays on the $x$-th floor) to the $a$-th and takes the passenger.  Moves from the $a$-th floor to the $b$-th floor and lets out the passenger (if $a$ equals $b$, elevator just opens and closes the doors, but still comes to the floor from the $x$-th floor).  Moves from the $b$-th floor back to the $x$-th.  The elevator never transposes more than one person and always goes back to the floor $x$ before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the $a$-th floor to the $b$-th floor requires $|a - b|$ units of electricity.

Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the $x$-th floor. Don't forget than elevator initially stays on the $x$-th floor.

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 100$) — the number of floors.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 100$) — the number of people on each floor.

-----Output-----

In a single line, print the answer to the problem — the minimum number of electricity units.

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

Output
16
Input
2
1 1

Output
4

-----Note-----

In the first example, the answer can be achieved by choosing the second floor as the $x$-th floor. Each person from the second floor (there are two of them) would spend $4$ units of electricity per day ($2$ to get down and $2$...

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

n = int(input())

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

ans = 0
e = 10 ** 9

for i in range(n):
    ne = 0
    for j in range(n):
        ne += (abs(i - j) + j + i) * 2 * a[j]

    if ne < e:
        e = ne
        ans = i

print(e)


I found an interesting problem on https://codeforces.com/problemset/problem/1084/B:
The Fair Nut likes kvass very much. On his birthday parents presented him $n$ kegs of kvass. There are $v_i$ liters of kvass in the $i$-th keg. Each keg has a lever. You can pour your glass by exactly $1$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $s$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.

Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $s$ liters of kvass.

-----Input-----

The first line contains two integers $n$ and $s$ ($1 \le n \le 10^3$, $1 \le s \le 10^{12}$) — the number of kegs and glass volume.

The second line contains $n$ integers $v_1, v_2, \ldots, v_n$ ($1 \le v_i \le 10^9$) — the volume of $i$-th keg.

-----Output-----

If the Fair Nut cannot pour his glass by $s$ liters of kvass, print $-1$. Otherwise, print a single integer — how much kvass in the least keg can be.

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

Output
3

Input
3 4
5 3 4

Output
2

Input
3 7
1 2 3

Output
-1

-----Note-----

In the first example, the answer is $3$, the Fair Nut can take $1$ liter from the first keg and $2$ liters from the third keg. There are $3$ liters of kvass in each keg.

In the second example, the answer is $2$, the Fair Nut can take $3$ liters from the first keg and $1$ liter from the second keg.

In the third example, the Fair Nut can't pour his cup by $7$ liters, so the answer is $-1$.

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

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

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

if sum(v) < s:
    print(-1)
    return

mv = min(v)

for i in range(n):
    s -= v[i] - mv

if s < 1:
    print(mv)
    return

ans = mv - s // n
if s % n != 0:
    ans -= 1

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1084/C:
The Fair Nut found a string $s$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $p_1, p_2, \ldots, p_k$, such that:   For each $i$ ($1 \leq i \leq k$), $s_{p_i} =$ 'a'.  For each $i$ ($1 \leq i < k$), there is such $j$ that $p_i < j < p_{i + 1}$ and $s_j =$ 'b'.

The Nut is upset because he doesn't know how to find the number. Help him.

This number should be calculated modulo $10^9 + 7$.

-----Input-----

The first line contains the string $s$ ($1 \leq |s| \leq 10^5$) consisting of lowercase Latin letters.

-----Output-----

In a single line print the answer to the problem — the number of such sequences $p_1, p_2, \ldots, p_k$ modulo $10^9 + 7$.

-----Examples-----
Input
abbaa

Output
5
Input
baaaa

Output
4
Input
agaa

Output
3

-----Note-----

In the first example, there are $5$ possible sequences. $[1]$, $[4]$, $[5]$, $[1, 4]$, $[1, 5]$.

In the second example, there are $4$ possible sequences. $[2]$, $[3]$, $[4]$, $[5]$.

In the third example, there are $3$ possible sequences. $[1]$, $[3]$, $[4]$.

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/1085/A:
Polycarp loves ciphers. He has invented his own cipher called Right-Left.

Right-Left cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{n}$ Polycarp uses the following algorithm:  he writes down $s_1$,  he appends the current word with $s_2$ (i.e. writes down $s_2$ to the right of the current result),  he prepends the current word with $s_3$ (i.e. writes down $s_3$ to the left of the current result),  he appends the current word with $s_4$ (i.e. writes down $s_4$ to the right of the current result),  he prepends the current word with $s_5$ (i.e. writes down $s_5$ to the left of the current result),  and so on for each position until the end of $s$.

For example, if $s$="techno" the process is: "t" $\to$ "te" $\to$ "cte" $\to$ "cteh" $\to$ "ncteh" $\to$ "ncteho". So the encrypted $s$="techno" is "ncteho".

Given string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i.e. find the string $s$.

-----Input-----

The only line of the input contains $t$ — the result of encryption of some string $s$. It contains only lowercase Latin letters. The length of $t$ is between $1$ and $50$, inclusive.

-----Output-----

Print such string $s$ that after encryption it equals $t$.

-----Examples-----
Input
ncteho

Output
techno

Input
erfdcoeocs

Output
codeforces

Input
z

Output
z

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/1085/B:
Vasya likes to solve equations. Today he wants to solve $(x~\mathrm{div}~k) \cdot (x \bmod k) = n$, where $\mathrm{div}$ and $\mathrm{mod}$ stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, $k$ and $n$ are positive integer parameters, and $x$ is a positive integer unknown. If there are several solutions, Vasya wants to find the smallest possible $x$. Can you help him?

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq n \leq 10^6$, $2 \leq k \leq 1000$).

-----Output-----

Print a single integer $x$ — the smallest positive integer solution to $(x~\mathrm{div}~k) \cdot (x \bmod k) = n$. It is guaranteed that this equation has at least one positive integer solution.

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

Output
11

Input
1 2

Output
3

Input
4 6

Output
10

-----Note-----

The result of integer division $a~\mathrm{div}~b$ is equal to the largest integer $c$ such that $b \cdot c \leq a$. $a$ modulo $b$ (shortened $a \bmod b$) is the only integer $c$ such that $0 \leq c < b$, and $a - c$ is divisible by $b$.

In the first sample, $11~\mathrm{div}~3 = 3$ and $11 \bmod 3 = 2$. Since $3 \cdot 2 = 6$, then $x = 11$ is a solution to $(x~\mathrm{div}~3) \cdot (x \bmod 3) = 6$. One can see that $19$ is the only other positive integer solution, hence $11$ is the smallest one.

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

n,k=list(map(int,input().split()))
deli=[]

oti=1
for i in range(k-1,0,-1):
    if n%i==0:
        oti=i
        break

ans=(n//oti)*k+oti
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1085/C:
The Squareland national forest is divided into equal $1 \times 1$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $(x, y)$ of its south-west corner.

Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $A, B, C$ in the forest. Initially, all plots in the forest (including the plots $A, B, C$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $A, B, C$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side. [Image] For example, $A=(0,0)$, $B=(1,1)$, $C=(2,2)$. The minimal number of plots to be cleared is $5$. One of the ways to do it is shown with the gray color.

Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.

-----Input-----

The first line contains two integers $x_A$ and $y_A$ — coordinates of the plot $A$ ($0 \leq x_A, y_A \leq 1000$). The following two lines describe coordinates $(x_B, y_B)$ and $(x_C, y_C)$ of plots $B$ and $C$ respectively in the same format ($0 \leq x_B, y_B, x_C, y_C \leq 1000$). It is guaranteed that all three plots are distinct.

-----Output-----

On the first line print a single integer $k$ — the smallest number of plots needed to be cleaned from trees. The following $k$ lines should contain coordinates of all plots needed to be cleaned. All $k$ plots should be distinct. You can output the plots in any order.

If there are multiple solutions, print any of them.

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

Output
5
0 0
1 0
1 1
1 2
2 2

Input
0 0
2 0
1 1

Output
4
0 0
1 0
1 1
2 0

-----Note-----

The first example is shown on the picture in the legend.

The second example is illustrated with the following image: [Image]

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

def doWay(x, y, x1, y1, x2, y2):
    nonlocal answer
    while x < x1 and x < x2:
        x += 1
        answer.add((x, y))
    while y < y1 and y < y2:
        y += 1
        answer.add((x, y))
    while x > x1 and x > x2:
        x -= 1
        answer.add((x, y))
    while y > y1 and y > y2:
        y -= 1
        answer.add((x, y))

xy = list()
xy.append(tuple(map(int, input().split())))
xy.append(tuple(map(int, input().split())))
xy.append(tuple(map(int, input().split())))

answer = set(xy)
doWay(xy[0][0], xy[0][1], xy[1][0], xy[1][1], xy[2][0], xy[2][1])
doWay(xy[1][0], xy[1][1], xy[0][0], xy[0][1], xy[2][0], xy[2][1])
doWay(xy[2][0], xy[2][1], xy[0][0], xy[0][1], xy[1][0], xy[1][1])

print(len(answer))
for x, y in answer:
    print(x, y)