1337xyz1337xyz/codeforces-editorial-full-2026-07-16 huggingface dataset:
Songwriter
Contest: 2019-2020 ICPC, Asia Jakarta Regional Contest (Online Mirror, ICPC Rules, Teams Preferred)
Difficulty rating: 2200
Tags: greedy, two pointers

Andi is a mathematician, a computer scientist, and a songwriter. After spending so much time writing songs, he finally writes a catchy melody that he thought as his best creation. However, the singer who will sing the song/melody has a unique vocal range, thus, an adjustment may be needed.

A melody is defined as a sequence of $$$N$$$ notes which are represented by integers. Let $$$A$$$ be the original melody written by Andi. Andi needs to adjust $$$A$$$ into a new melody $$$B$$$ such that for every $$$i$$$ where $$$1 \le i < N$$$:

- If $$$A_i < A_{i+1}$$$, then $$$B_i < B_{i+1}$$$.
- If $$$A_i = A_{i+1}$$$, then $$$B_i = B_{i+1}$$$.
- If $$$A_i > A_{i+1}$$$, then $$$B_i > B_{i+1}$$$.
- $$$|B_i - B_{i+1}| \le K$$$, i.e. the difference between two successive notes is no larger than $$$K$$$.

Help Andi to determine whether such $$$B$$$ exists, and find the lexicographically smallest $$$B$$$ if it exists. A melody $$$X$$$ is lexicographically smaller than melody $$$Y$$$ if and only if there exists $$$j$$$ ($$$1 \le j \le N$$$) such that $$$X_i = Y_i$$$ for all $$$i < j$$$ and $$$X_{j} < Y_{j}$$$.

For example, consider a melody $$$A = \{1,3,5,6,7,8,9,10,3,7,8,9,10,11,12,12\}$$$ as shown in the following figure. The diagonal arrow up in the figure implies that $$$A_i < A_{i+1}$$$, the straight right arrow implies that $$$A_i = A_{i+1}$$$, and the diagonal arrow down implies that $$$A_i > A_{i+1}$$$.

Supposed we want to make a new melody with $$$L = 1$$$, $$$R = 8$$$, and $$$K = 6$$$. The new melody $$$B = \{1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,8\}$$$ as shown in the figure satisfies all the requirements, and it is the lexicographically smallest possible.

Input format:
Input begins with a line containing four integers: $$$N$$$ $$$L$$$ $$$R$$$ $$$K$$$ ($$$1 \le N \le 100\,000$$$; $$$1 \le L \le R \le 10^9$$$; $$$1 \le K \le 10^9$$$) representing the number of notes in the melody, the vocal range ($$$L$$$ and $$$R$$$), and the maximum difference between two successive notes in the new melody, respectively. The next line contains $$$N$$$ integers: $$$A_i$$$ ($$$1 \le A_i \le 10^9$$$) representing the original melody.

Output format:
Output in a line $$$N$$$ integers (each separated by a single space) representing the lexicographically smallest melody satisfying all the requirements, or output -1 if there is no melody satisfying all the requirements. Note that it might be possible that the lexicographically smallest melody which satisfies all the requirements to be the same as the original melody.

Constraints:
Time limit: 1.0 s
Memory limit: 256.0 MB

Note:
Explanation for the sample input/output #1

This is the example from the problem description.

Example input:
16 1 8 6
1 3 5 6 7 8 9 10 3 7 8 9 10 11 12 12

Example output:
1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 8

Example input:
16 1 8 6
1 3 5 6 7 8 9 10 3 7 8 9 10 11 12 13

Example output:
-1

Editorial:
Twin Buildings
Contest: 2019-2020 ICPC, Asia Jakarta Regional Contest (Online Mirror, ICPC Rules, Teams Preferred)
Difficulty rating: 1800
Tags: greedy, implementation

As you might already know, space has always been a problem in ICPC Jakarta. To cope with this, ICPC Jakarta is planning to build two new buildings. These buildings should have a shape of a rectangle of the same size. Now, their problem is to find land to build the buildings.

There are $$$N$$$ lands available for sale. The $$$i^{th}$$$ land has a rectangular shape of size $$$L_i \times W_i$$$. For a good feng shui, the building's side should be parallel to the land's sides.

One way is to build the two buildings on two different lands, one on each land (not necessarily with the same orientation). A building of size $$$A \times B$$$ can be build on the $$$i^{th}$$$ land if and only if at least one of the following is satisfied:

- $$$A \le L_i$$$ and $$$B \le W_i$$$, or
- $$$A \le W_i$$$ and $$$B \le L_i$$$.

- $$$A \times 2 \le L_i$$$ and $$$B \le W_i$$$, or
- $$$A \times 2 \le W_i$$$ and $$$B \le L_i$$$, or
- $$$A \le L_i$$$ and $$$B \times 2 \le W_i$$$, or
- $$$A \le W_i$$$ and $$$B \times 2 \le L_i$$$.

Your task in this problem is to help ICPC Jakarta to figure out the largest possible buildings they can build given $$$N$$$ available lands. Note that ICPC Jakarta has to build two buildings of $$$A \times B$$$; output the largest possible for $$$A \times B$$$.

Input format:
Input begins with a line containing an integer: $$$N$$$ ($$$1 \le N \le 100\,000$$$) representing the number of available lands. The next $$$N$$$ lines each contains two integers: $$$L_i$$$ $$$W_i$$$ ($$$1 \le L_i, W_i \le 10^9$$$) representing the size of the land.

Output format:
Output in a line a number representing the largest building that ICPC Jakarta can build with exactly one decimal point (see sample input/output for clarity).

Constraints:
Time limit: 1.0 s
Memory limit: 256.0 MB

Note:
Explanation for the sample input/output #1

Two buildings of $$$2.5 \times 5$$$ can be built both on the first land.

Explanation for the sample input/output #2

Two buildings of $$$2 \times 4$$$ can be built each on the first and second lands.

Explanation for the sample input/output #3

Two buildings of $$$7 \times 6$$$ can be built each on the second and third lands.

Example input:
2
5 5
3 4

Example output:
12.5

Example input:
2
2 5
4 3

Example output:
8.0

Editorial:
Addition Robot
Contest: 2019-2020 ICPC, Asia Jakarta Regional Contest (Online Mirror, ICPC Rules, Teams Preferred)
Difficulty rating: 2100
Tags: data structures, math, matrices

Adding two numbers several times is a time-consuming task, so you want to build a robot. The robot should have a string $$$S = S_1 S_2 \dots S_N$$$ of $$$N$$$ characters on its memory that represents addition instructions. Each character of the string, $$$S_i$$$, is either 'A' or 'B'.

You want to be able to give $$$Q$$$ commands to the robot, each command is either of the following types:

- 1 $$$L$$$ $$$R$$$. The robot should toggle all the characters of $$$S_i$$$ where $$$L \le i \le R$$$. Toggling a character means changing it to 'A' if it was previously 'B', or changing it to 'B' if it was previously 'A'.
- 2 $$$L$$$ $$$R$$$ $$$A$$$ $$$B$$$. The robot should call $$$f(L, R, A, B)$$$ and return two integers as defined in the following pseudocode:     function f(L, R, A, B):      FOR i from L to R        if S[i] = 'A'          A = A + B        else          B = A + B      return (A, B)

You want to implement the robot's expected behavior.

Input format:
Input begins with a line containing two integers: $$$N$$$ $$$Q$$$ ($$$1 \le N, Q \le 100\,000$$$) representing the number of characters in the robot's memory and the number of commands, respectively. The next line contains a string $$$S$$$ containing $$$N$$$ characters (each either 'A' or 'B') representing the initial string in the robot's memory. The next $$$Q$$$ lines each contains a command of the following types.

- 1 $$$L$$$ $$$R$$$ ($$$1 \le L \le R \le N$$$)
- 2 $$$L$$$ $$$R$$$ $$$A$$$ $$$B$$$ ($$$1 \le L \le R \le N$$$; $$$0 \le A, B \le 10^9$$$)

Output format:
For each command of the second type in the same order as input, output in a line two integers (separated by a single space), the value of $$$A$$$ and $$$B$$$ returned by $$$f(L, R, A, B)$$$, respectively. As this output can be large, you need to modulo the output by $$$1\,000\,000\,007$$$.

Constraints:
Time limit: 3.0 s
Memory limit: 256.0 MB

Note:
Explanation for the sample input/output #1

For the first command, calling $$$f(L, R, A, B)$$$ causes the following:

- Initially, $$$A = 1$$$ and $$$B = 1$$$.
- At the end of $$$i = 1$$$, $$$A = 2$$$ and $$$B = 1$$$.
- At the end of $$$i = 2$$$, $$$A = 2$$$ and $$$B = 3$$$.
- At the end of $$$i = 3$$$, $$$A = 5$$$ and $$$B = 3$$$.
- At the end of $$$i = 4$$$, $$$A = 8$$$ and $$$B = 3$$$.
- At the end of $$$i = 5$$$, $$$A = 11$$$ and $$$B = 3$$$.

For the second command, string $$$S$$$ will be updated to "ABBBB".

For the third command, the value of $$$A$$$ will always be $$$0$$$ and the value of $$$B$$$ will always be $$$1\,000\,000\,000$$$. Therefore, $$$f(L, R, A, B)$$$ will return $$$(0, 1\,000\,000\,000)$$$.

Example input:
5 3
ABAAA
2 1 5 1 1
1 3 5
2 2 5 0 1000000000

Example output:
11 3
0 1000000000

Editorial:
Elections
Contest: Codeforces Round 316 (Div. 2)
Difficulty rating: 1100
Tags: implementation

The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.

The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.

At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.

Determine who will win the elections.

Input format:
The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively.

Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i.

It is guaranteed that the total number of people in all the cities does not exceed 109.

Output format:
Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

Constraints:
Time limit: 1.0 s
Memory limit: 256.0 MB

Note:
Note to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.

Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

Example input:
3 3
1 2 3
2 3 1
1 2 1

Example output:
2

Example input:
3 4
10 10 3
5 1 6
2 2 2
1 5 7

Example output:
1

Editorial:
Simple Game
Contest: Codeforces Round 316 (Div. 2)
Difficulty rating: 1300
Tags: constructive algorithms, games, greedy, implementation, math

One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a.

Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins.

Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible.

More formally, you need to find such integer a (1 ≤ a ≤ n), that the probability that $$|c-a|<|c-m|$$ is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive).

Input format:
The first line contains two integers n and m (1 ≤ m ≤ n ≤ 109) — the range of numbers in the game, and the number selected by Misha respectively.

Output format:
Print a single number — such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them.

Constraints:
Time limit: 1.0 s
Memory limit: 256.0 MB

Note:
In the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0.

In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less.

Example input:
3 1

Example output:
2

Example input:
4 3

Example output:
2

Editorial:
Replacement
Contest: Codeforces Round 316 (Div. 2)
Difficulty rating: 1600
Tags: constructive algorithms, data structures, implementation

Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.

Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.

You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).

Help Daniel to process all queries.

Input format:
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.

The second line contains string s, consisting of n lowercase English letters and period signs.

The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Output format:
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

Constraints:
Time limit: 2.0 s
Memory limit: 256.0 MB

Note:
Note to the first sample test (replaced periods are enclosed in square brackets).

The original string is ".b..bz....".

- after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.")
- after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.")
- after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")

Note to the second sample test.

The original string is ".cc.".

- after the first query: f(..c.) = 1    ("[..]c."  →  ".c.")
- after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".")
- after the third query: f(.a..) = 1    (".a[..]"  →  ".a.")
- after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")

Example input:
10 3
.b..bz....
1 h
3 c
9 f

Example output:
4
3
1

Example input:
4 4
.cc.
2 .
3 .
2 a
1 a

Example output:
1
3
1
1

Editorial:
Tree Requests
Contest: Codeforces Round 316 (Div. 2)
Difficulty rating: 2200
Tags: binary search, bitmasks, constructive algorithms, dfs and similar, graphs, trees

Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i).

The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1.

We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree.

Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.

Input format:
The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively.

The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i).

The next line contains n lowercase English letters, the i-th of these letters is written on vertex i.

Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query.

Output format:
Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).

Constraints:
Time limit: 2.0 s
Memory limit: 256.0 MB

Note:
String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome.

Clarification for the sample test.

In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z".

In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them.

In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome.

In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome.

In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".

Example input:
6 5
1 1 1 3 3
zacccd
1 1
3 3
4 1
6 1
1 2

Example output:
Yes
No
Yes
Yes
Yes

Editorial:
Pig and Palindromes
Contest: Codeforces Round 316 (Div. 2)
Difficulty rating: 2300
Tags: combinatorics, dp

Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).

Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.

The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).

Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.

Input format:
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the height and width of the field.

Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.

Output format:
Print a single integer — the number of beautiful paths modulo 109 + 7.

Constraints:
Time limit: 4.0 s
Memory limit: 256.0 MB

Note:
Picture illustrating possibilities for the sample test.

Example input:
3 4
aaab
baaa
abba

Example output:
3

Editorial:
Путь Поликарпа
Contest: Технокубок 2017 - Ознакомительный Раунд 3
Difficulty rating: 1200
Tags: *special

Лайнландия состоит из n городов, которые расположены на оси Ox. Координата i-го из городов равна xi.

Поликарп прошел от одного города до другого по прямой кратчайшим образом. Он утверждает, что прошел расстояние d.

Выведите количество пар городов, что Поликарп мог пройти от одного к другому. Иными словами, между которыми расстояние составляет ровно d.

Input format:
В первой строке записаны два целых числа n, d (2 ≤ n ≤ 105, 1 ≤ d ≤ 109).

Вторая строка содержит координаты n городов — последовательность целых чисел x1, x2, ..., xn ( - 109 ≤ xi ≤ 109). Все xi — различны.

Output format:
Выведите искомое количество пар городов. Пары, отличающиеся только порядком городов, следует считать одной и той же парой.

Constraints:
Time limit: 1.0 s
Memory limit: 256.0 MB

Example input:
6 3
6 13 4 10 5 9

Example output:
2

Example input:
10 1
1 2 3 4 5 6 7 8 9 10

Example output:
9

Editorial:
Diverse Substring
Contest: Educational Codeforces Round 53 (Rated for Div. 2)
Difficulty rating: 1000
Tags: implementation, strings

You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.

A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, "defor" is a substring of "codeforces" and "fors" is not.

The length of the substring is the number of letters in it.

Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\frac n 2$$$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.

Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.

Input format:
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of string $$$s$$$.

The second line is the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

Output format:
Print "NO" if there is no diverse substring in the string $$$s$$$.

Otherwise the first line should contain "YES". The second line should contain any diverse substring of string $$$s$$$.

Constraints:
Time limit: 1.0 s
Memory limit: 256.0 MB

Note:
The first example has lots of correct answers.

Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer.

Example input:
10
codeforces

Example output:
YES
code

Example input:
5
aaaaa

Example output:
NO

Editorial:
Notice that the string of two distinct letter is already diverse. That implies that the answer is "NO" if and only if all the letters in the string are the same. Otherwise you can check all pairs of adjacent letters in $$$O(n)$$$.
Overall complexity: $$$O(n)$$$.