Полигон YMLSYMLS PolygonТашкент · 2026Tashkent · 2026
до попыткиuntil the attempt —
День 12 2 сентября, среда АлгоритмыAlgorithmsТактикаTactics

Динамика, жадность и Python как оружиеDynamic Programming, Greedy Methods, and Python as a Weapon

Восемь задач ступени YMLS из шести тем вперемешку: исход решают первые тридцать секунд, а там, где аналитика длинная, число берётся машинойEight YMLS-level problems drawn from six mixed topics: the first thirty seconds decide the outcome, and where the analytical route is long, let the machine produce the number

0% дня закрыто · решено задач 0 из 17

цель дня
RU

К вечеру ты по двум-трём словам условия называешь тип задачи и её первый ход, не начиная считать. Там, где аналитического хода не видно, получаешь число машиной — точным перебором, динамикой или симуляцией — и знаешь, сколько знаков этому числу можно доверять. Проверка — восемь задач ступени YMLS, намеренно перемешанных: четыре из них финальные и разобраны ниже, ещё четыре закрываются одной строкой из блока «Мост». Мини-тестом идёт y1204.

EN

By evening, from two or three words in a statement you can name the problem type and its first move without starting to calculate. When the analytical route is not obvious, you can get the number by machine—exact enumeration, dynamic programming, or simulation—and know how many digits you can trust. The check is eight mixed YMLS problems: four are finals explained below, and four more close with a single line from the “Bridge” block. The mini-test is y1204.

Самостоятельные задачи

К концу дня нужно уметь решать эти задачи самостоятельно, без подсказок.

Мост · что нужно вспомнить
RU

Мостов сегодня не два и не три: восемь задач ступени YMLS собраны из шести разных тем, и это сделано нарочно. Блочная практика («сегодня только интегралы») даёт ощущение владения, потому что тип задачи известен заранее. Смешанная показывает реальное состояние, потому что тип надо назвать самому — а именно этого от тебя потребуют послезавтра.

Из вчерашнего дня берётся одна вещь, но важнейшая: оценка размера. Ориентир $10^8$ операций в секунду сегодня работает не на выбор структуры данных, а на выбор способа решения: помещается ли пространство исходов в перебор, или нужна динамика, или исход вообще непрерывный и остаётся симуляция.

Из четвёртого дня возвращается хвостовая формула, из второго — вероятность как доля площади, из восьмого — первообразная степени и гамма-интеграл, из девятого — расстояние до плоскости, из одиннадцатого — направление округления, из первого — правило произведения. Ни один из этих приёмов сегодня не выводится заново: всё, что нужно, выписано ниже, а день тратится на то, чтобы узнавать их в чужой формулировке и получать число быстро.

Завтра полный мок на четыре часа, послезавтра экзамен. Сегодня — последний день, когда что-то можно добрать.

EN

Today the bridges are not two or three: eight YMLS problems draw on six different topics, and that is deliberate. Block practice (“today is only integrals”) gives you a feeling of mastery because the problem type is known in advance. Mixed practice shows your real state because you must name the type yourself—and that is exactly what will be required the day after tomorrow.

From yesterday we take one thing, but the crucial one: estimating scale. The $10^8$ operations- per-second rule of thumb is used today not to choose a data structure but to choose a solution method: does the outcome space fit in an enumeration, do you need dynamic programming, or is the outcome continuous so that simulation is the only option?

The tail formula returns from day 4, probability as an area fraction from day 2, the antiderivative of a power and the gamma integral from day 8, distance to a plane from day 9, rounding direction from day 11, and the product rule from day 1. None of these techniques is derived again today: everything you need is written below, and the day is spent on recognizing them in unfamiliar wording and obtaining the number quickly.

Tomorrow is a full four-hour mock; the exam is the day after tomorrow. Today is the last day when you can add anything.

Вспомни вслух, до открытия конспектов:

  1. Правило произведения: независимые выборы перемножаются. Если $N = p_1^{\alpha_1}\cdots p_k^{\alpha_k}$, то число натуральных делителей равно $(\alpha_1+1)\cdots(\alpha_k+1)$ (день 1)Product rule: independent choices multiply. If $N = p_1^{\alpha_1}\cdots p_k^{\alpha_k}$, the number of positive divisors is $(\alpha_1+1)\cdots(\alpha_k+1)$ (day 1)
  2. Правило «никакие два не рядом»: двоичных строк длины $n$ ровно с $k$ единицами, среди которых нет двух соседних, ровно $\binom{n-k+1}{k}$The “no two adjacent” rule: binary strings of length $n$ with exactly $k$ ones and no adjacent ones number exactly $\binom{n-k+1}{k}$
  3. Вероятность как доля меры: при равномерном выборе точки в фигуре вероятность события есть площадь подобласти, делённая на площадь всей фигуры (день 2)Probability as a measure fraction: for a uniformly chosen point in a figure, event probability is the subregion’s area divided by the whole figure’s area (day 2)
  4. Независимые события: вероятность того, что произошли все сразу, равна произведению вероятностей (день 2)Independent events: the probability that they all occur is the product of their probabilities (day 2)
  5. Хвостовая формула: для целой неотрицательной величины $\E X = \sum_{k \ge 1}\P(X \ge k)$ (день 4)Tail formula: for a nonnegative integer-valued variable, $\E X = \sum_{k \ge 1}\P(X \ge k)$ (day 4)
  6. Беспорядки: перестановок $n$ элементов без неподвижных точек ровно $D_n = n!\sum_{k=0}^{n}\frac{(-1)^k}{k!}$, и $D_n/n! \to e^{-1}$ (в дне 4 названы, формула — здесь)Derangements: the number of permutations of $n$ elements with no fixed points is $D_n = n!\sum_{k=0}^{n}\frac{(-1)^k}{k!}$, and $D_n/n! \to e^{-1}$ (named on day 4, formula here)
  7. Геометрическая прогрессия: $\sum_{k\ge0}q^k = \frac{1}{1-q}$ при $|q|<1$, конечная сумма $\sum_{k=0}^{m-1}q^k = \frac{1-q^m}{1-q}$Geometric progression: $\sum_{k\ge0}q^k = \frac{1}{1-q}$ when $|q|<1$; the finite sum is $\sum_{k=0}^{m-1}q^k = \frac{1-q^m}{1-q}$
  8. Гамма-интеграл: $\int_0^{\infty}x^{n}e^{-x}\,dx = n!$ для целого $n \ge 0$ (день 8)Gamma integral: $\int_0^{\infty}x^{n}e^{-x}\,dx = n!$ for an integer $n \ge 0$ (day 8)
  9. Замена переменной: если $x = x(y)$ монотонна, то $dx$ заменяется на $|x'(y)|\,dy$, а пределы пересчитываются (день 8)Change of variable: if $x = x(y)$ is monotone, replace $dx$ with $|x'(y)|\,dy$ and recompute the bounds (day 8)
  10. Первообразная степени: $\int u^2\,du = \frac{u^3}{3}$; сдвиг $u = x - \frac12$ пределы только переносит (день 8)Power antiderivative: $\int u^2\,du = \frac{u^3}{3}$; shifting with $u = x - \frac12$ only translates the bounds (day 8)
  11. Расстояние от точки $p$ до плоскости $\langle n, x\rangle = c$ равно $\frac{|\langle n,p\rangle - c|}{\|n\|}$, а коэффициенты уравнения — это координаты нормали (день 9)Distance from a point $p$ to the plane $\langle n, x\rangle = c$ is $\frac{|\langle n,p\rangle - c|}{\|n\|}$, and the equation’s coefficients are the normal’s coordinates (day 9)
  12. Площадь круга радиуса $r$ равна $\pi r^2$; площадь треугольника — половина произведения основания на высотуThe area of a circle of radius $r$ is $\pi r^2$; the area of a triangle is half the product of its base and height
  13. Возводить неравенство в квадрат можно, когда обе части неотрицательны: знак при этом не меняетсяYou may square an inequality when both sides are nonnegative; the sign does not change
  14. Одновременная работа: скорости складываются, а время равно работе, делённой на суммарную скоростьWorking simultaneously: rates add, and time equals work divided by the total rate
  15. Округление: $\lceil t\rceil$ — наименьшее целое, не меньшее $t$. «За сколько успеем» округляется вверх, «сколько успеем» — вниз (день 11)Rounding: $\lceil t\rceil$ is the smallest integer not less than $t$. “How long will it take?” rounds up; “how much can we do?” rounds down (day 11)
  16. Теорема Виета: у уравнения $x^2 - yx - 1 = 0$ сумма корней равна $y$, а произведение равно $-1$Vieta’s formulas: for $x^2 - yx - 1 = 0$, the roots sum to $y$ and multiply to $-1$
  17. Ориентир скорости: компьютер делает порядка $10^8$ простых операций в секунду (день 11)Speed reference: a computer performs about $10^8$ simple operations per second (day 11)

Повторение прошлых дней

Карточки возвращаются через 1, 2, 4, 7, 14 и 21 день в зависимости от того, насколько уверенно ты их вспомнил; «не помню» отправляет карточку в начало. Это часть разогрева, вместе с блоком «Мост».

Комбинаторика день 1 осталось 107
RU

Правило умножения: две оговорки, без которых оно не работает

EN

The multiplication rule: two qualifications without which it does not work

Сначала сформулируй вслух. Попытка вспомнить закрепляет сильнее, чем чтение готового ответа.

5 задач: подборка покрывает темы и микронавыки последнего учебного дня (11), а для каждой идеи выбирает наиболее сильный доступный уровень. Здесь отдельная попытка: решение в исходном дне не подставляется. Сначала назови тему вслух, затем решай.

Y1104Уровень YMLSАлгоритмыуровень YMLS
RU

Для массива из задачи w1101 найдите сумму пяти наибольших элементов. Повторы учитываются: если одно и то же значение встречается несколько раз, оно и берётся столько раз, сколько попало в пятёрку.

EN

For the array from problem w1101, find the sum of its five largest elements. Repetitions count: if the same value occurs several times, include it as many times as it appears among the top five elements.

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. В первой строке $n$ и $k$ ($1 \le k \le n \le 10^5$), во второй — $n$ целых чисел. Вывод. Сумма $k$ наибольших элементов, повторы учитываются.

EN

Input. The first line holds $n$ and $k$ ($1 \le k \le n \le 10^5$); the second holds $n$ integers. Output. The sum of the $k$ largest elements, counting repeats.

ВыводOutput
Подсказка / Hint
RU

Полная сортировка избыточна — достаточно кучи размера $k$.

EN

Sorting the full array is unnecessary; a heap of size $k$ is sufficient.

Решение / Solution
RU
import heapq
print(sum(heapq.nlargest(5, a)))   # 43

Ответ: 43 — это $9 + 9 + 9 + 8 + 8$. Девятка встречается в массиве трижды, восьмёрка — тоже трижды, и в пятёрку крайних попадают три девятки и две восьмёрки.

Это тот же проход, что в мосте b1102: куча размера 5 идёт по массиву и держит пятёрку лучших. Там спрашивали её вершину — пятый по величине элемент, здесь нужна сумма всей пятёрки, поэтому вершину брать не надо, а надо сложить содержимое кучи.

Где здесь теряют ответ

Если прочитать условие как «пять наибольших различных значений», получится $9 + 8 + 7 + 6 + 5 = 35$ — другое число. Условие говорит про элементы, а не про значения, поэтому повторы берутся столько раз, сколько их есть.

Три ответа, которые надо назвать на собеседовании

Сортировка — $O(n\log n)$, просто и всегда работает. Куча размера $k$ — $O(n\log k)$, заметно быстрее при $k \ll n$. Quickselect — $O(n)$ в среднем; «медиана медиан» даёт $O(n)$ в худшем случае.

Назвать все три — сильный ход. Он показывает, что ты видишь пространство решений, а не одно заученное.

EN
import heapq
print(sum(heapq.nlargest(5, a)))   # 43

Answer: 43, since $9 + 9 + 9 + 8 + 8 = 43$. The value 9 occurs three times and 8 also occurs three times, so the top five elements contain three 9s and two 8s.

This is the same pass as in bridge problem b1102: a heap of size 5 traverses the array and retains the five best elements. That problem asks for the heap's top, the fifth-largest element. Here we need the sum of all five elements, so we sum the entire heap rather than reading its top.

How the wrong answer arises

If the statement is misread as asking for the five largest distinct values, the result is $9 + 8 + 7 + 6 + 5 = 35$. The problem asks about elements, not distinct values, so repetitions count as many times as they occur.

Three solutions to mention in an interview

Sorting: $O(n\log n)$, simple and universally applicable. A heap of size $k$: $O(n\log k)$, substantially faster when $k \ll n$. Quickselect: $O(n)$ expected time; median of medians gives $O(n)$ worst-case time.

Naming all three is valuable: it shows that you see the solution space rather than one memorized method.

уверенность1 — угадал, 5 — уверен полностью
S1101Уровень ШАДАлгоритмыОлимпиада ШАД 2025, задача «Похожие геномы»
RU

Мерой похожести двух вирусов служит побитовое исключающее ИЛИ (XOR) их геномов: чем меньше XOR, тем более похожи вирусы.

В базе лежат геномы

[38, 18, 7, 52, 13, 25, 60, 3, 44, 29]

Найдите наименьший возможный XOR пары геномов, стоящих на разных позициях.

EN

The similarity of two viruses is measured by the bitwise exclusive OR (XOR) of their genomes: the smaller the XOR, the more similar the viruses.

The database contains the genomes

[38, 18, 7, 52, 13, 25, 60, 3, 44, 29]

Find the smallest possible XOR of two genomes at distinct positions.

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. В первой строке $n$ ($2 \le n \le 10^5$), во второй — $n$ целых чисел $0 \le a_i < 2^{30}$. Вывод. Наименьший $a_i \oplus a_j$ по парам разных позиций.

EN

Input. The first line holds $n$ ($2 \le n \le 10^5$); the second holds $n$ integers $0 \le a_i < 2^{30}$. Output. The smallest $a_i \oplus a_j$ over pairs of different positions.

ВыводOutput
Подсказка / Hint
RU

Для десяти чисел хватит перебора сорока пяти пар — приём из b1101, только вместо суммы XOR. Быстрый ход — тот же спуск по разрядам, что в мосте b1105, но в обратную сторону. А дальше подумай, как отвечать на такой запрос, если чисел $2 \cdot 10^5$ и они добавляются по одному.

EN

With ten numbers, enumerating all forty-five pairs is enough; this is the technique from b1101, with XOR instead of addition. The fast approach uses the same bitwise descent as bridge problem b1105, but in the opposite direction. Then consider how to answer the query if there are $2 \cdot 10^5$ numbers arriving one by one.

Решение / Solution
RU

Ответ для наших данных: 4 — пара $7$ и $3$: $7 \oplus 3 = 0111_2 \oplus 0011_2 = 0100_2 = 4$.

from itertools import combinations
print(min(x ^ y for x, y in combinations(G, 2)))   # 4

Перебор пар — это $O(n^2)$, здесь всего 45 пар. На олимпиадных ограничениях ($n$ до $2\cdot10^5$, числа до $2^{30}$) он не проходит, и нужен другой подход.

Правильное решение — префиксное дерево (бор) на битах.

Храним двоичные представления чисел в дереве как строки длины $K = 30$, от старших разрядов к младшим. При добавлении нового числа $X$ делаем два действия:

  1. Ищем в боре число $Y$, дающее минимальный XOR с $X$. Спускаемся от корня; на каждой глубине пытаемся пойти по тому же биту, что у $X$ — тогда в этом разряде XOR даст ноль. Если такого перехода нет, идём по единственному имеющемуся.
  2. Вставляем $X$ в бор.

Ответ поддерживаем как минимум по всем добавлениям.

Почему жадный спуск корректен. Пусть на глубине $d$ можно пойти двумя путями. Совпадение бита даёт в этом разряде ноль, несовпадение — единицу, то есть вклад $2^{K-d}$. Но по пункту блока «Мост» один старший разряд перевешивает все младшие вместе взятые, поэтому совпадение в старшем разряде выгоднее любого выигрыша во всех младших. Жадность оптимальна.

Сложность: $O(NK)$ по времени и памяти, где $K$ — число бит.

Проверка третьим способом

Работает правило из блока «Триггеры»: минимальный XOR всегда достигается на паре соседей в отсортированном порядке. Вот его вывод в две строки. Пусть $x < y < z$, и пусть $b$ — самый старший разряд, в котором $x$ и $z$ различаются: в нём у $x$ ноль, у $z$ единица, поэтому $x \oplus z \ge 2^{b}$. Все разряды старше $b$ у $x$ и $z$ совпадают, а $y$ лежит между ними, поэтому в старших разрядах $y$ совпадает с обоими; в самом разряде $b$ у $y$ стоит либо ноль, и тогда $x \oplus y < 2^{b}$, либо единица, и тогда $y \oplus z < 2^{b}$. В обоих случаях какая-то из более тесных пар строго лучше крайней — значит пару, между членами которой лежит третье число, можно не проверять.

Отсортируем: 3, 7, 13, 18, 25, 29, 38, 44, 52, 60 — и проверим только девять соседних пар вместо сорока пяти. Их XOR равны 4, 10, 31, 11, 4, 59, 10, 24, 8; наименьшее значение 4 достигается дважды: $3 \oplus 7 = 4$ и $25 \oplus 29 = 4$. Ответ сошёлся с перебором, и это независимая проверка, а не пересчёт того же самого.

Что забрать

Идея «старший разряд важнее всех младших вместе» — универсальная для битовых задач. Она превращает переборную задачу в жадный спуск по дереву, то есть в то же деление пополам, что и бинарный поиск, только режется не отрезок чисел, а множество кандидатов по очередному биту.

На YMLS такое вряд ли придёт в полном объёме, но сам приём «работать с числами поразрядно, от старших к младшим» вполне может понадобиться.

EN

For the given data, the answer is 4, attained by 7 and 3: $7 \oplus 3 = 0111_2 \oplus 0011_2 = 0100_2 = 4$.

from itertools import combinations
print(min(x ^ y for x, y in combinations(G, 2)))   # 4

Pair enumeration takes $O(n^2)$ time and involves only 45 pairs here. It is too slow under olympiad constraints ($n$ up to $2\cdot10^5$, values below $2^{30}$), so a different approach is required.

The appropriate solution is a binary prefix tree, or binary trie.

Store the binary representations of the numbers in a tree as strings of length $K=30$, from the most significant bit to the least significant. When a new number $X$ arrives, perform two operations:

  1. Find a number $Y$ in the trie minimizing its XOR with $X$. Descend from the root. At each depth, first try the branch with the same bit as $X$, which contributes zero at this position. If that branch does not exist, take the only available branch.
  2. Insert $X$ into the trie.

Maintain the answer as the minimum over all insertions.

Why the greedy descent is correct. Suppose both branches are available at depth $d$. Matching the bit contributes zero at this position, while differing contributes one, with value $2^{K-d}$. One more significant bit outweighs all less significant bits combined, as established in the Bridge section. Therefore matching the more significant bit is preferable to any possible gain below it, and the greedy choice is optimal.

The time and space complexity are $O(NK)$, where $K$ is the number of bits.

A third method for checking

The rule from the Triggers section applies: the minimum XOR is always attained by two adjacent values in sorted order. Here is the proof. Let $x<y<z$, and let $b$ be the most significant bit at which $x$ and $z$ differ. At this bit, $x$ has zero and $z$ has one, so $x\oplus z \ge 2^b$. All bits above $b$ coincide in $x$ and $z$. Since $y$ lies between them, it agrees with both in those higher bits. At bit $b$, either $y$ has zero, giving $x\oplus y < 2^b$, or it has one, giving $y\oplus z < 2^b$. In either case, a closer pair is strictly better than the outer pair. Thus a pair with a third number between its members never needs to be checked.

Sort the values: 3, 7, 13, 18, 25, 29, 38, 44, 52, 60. Check only nine adjacent pairs rather than forty-five. Their XORs are 4, 10, 31, 11, 4, 59, 10, 24, 8. The minimum, 4, is attained twice: $3 \oplus 7 = 4$ and $25 \oplus 29 = 4$. This agrees with exhaustive search and is an independent check.

The takeaway

The principle “a more significant bit outweighs all less significant bits combined” is universal in bitwise problems. It turns an exhaustive search into a greedy tree descent: the same kind of halving as binary search, except that the candidate set is partitioned by the next bit rather than by a numeric interval.

A full-strength version is unlikely on YMLS, but the underlying technique of processing numbers bit by bit, from most significant to least significant, may well be useful.

уверенность1 — угадал, 5 — уверен полностью
Y1102Уровень YMLSАлгоритмыуровень YMLS · бинпоиск по ответу
RU

Есть пять куч бананов размерами $[30, 11, 23, 4, 20]$ и $h = 6$ часов. За один час можно съесть не более $k$ бананов из одной кучи; если в куче осталось меньше $k$, час всё равно тратится целиком, и перейти к другой куче в этот же час нельзя.

Найдите минимальное целое $k$, при котором все кучи будут съедены за $h$ часов.

EN

There are five piles of bananas of sizes $[30, 11, 23, 4, 20]$ and $h = 6$ available hours. During one hour, at most $k$ bananas may be eaten from one pile. If fewer than $k$ bananas remain, the full hour is still used, and no other pile may be started during that hour.

Find the smallest integer $k$ for which all piles can be eaten within $h$ hours.

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. В первой строке $n$ ($1 \le n \le 10^5$) и $h$ ($n \le h \le 10^9$), во второй — размеры куч $1 \le p_i \le 10^9$. Вывод. Наименьшее целое $k$, при котором все кучи съедены за $h$ часов.

EN

Input. The first line holds $n$ ($1 \le n \le 10^5$) and $h$ ($n \le h \le 10^9$); the second holds pile sizes $1 \le p_i \le 10^9$. Output. The smallest integer $k$ that finishes all piles within $h$ hours.

ВыводOutput
Подсказка / Hint
RU

Проверить конкретное $k$ легко, и эта проверка монотонна. Дальше — шаблон эталонной задачи урока, только предикат другой.

EN

Checking a fixed $k$ is easy, and the predicate is monotone. Apply the template from the model problem in the lesson with a different predicate.

Решение / Solution
RU

Шаг 1. Что ищем. «Минимальное $k$, при котором …» — признак бинарного поиска по ответу. Ищем не элемент массива куч, а само число $k$.

Шаг 2. Предикат. При скорости $k$ на кучу размера $p$ уходит $\lceil p/k\rceil$ часов — неполный час тоже потрачен:

$$\text{hours}(k) = \sum_i \left\lceil \frac{p_i}{k}\right\rceil$$

Шаг 3. Монотонность. Чем больше $k$, тем меньше часов. Значит годные значения $k$ образуют луч $[k_0, +\infty)$, и надо найти его левую границу.

Шаг 4. Границы. $\text{lo} = 1$ — меньше есть нельзя; $\text{hi} = \max p_i = 30$ заведомо годится: при такой скорости каждая куча съедается за один час, всего пять часов из шести.

piles = [30, 11, 23, 4, 20]; h = 6

def hours(k):
    return sum(-(-p // k) for p in piles)    # -(-a//b) = округление вверх

lo, hi = 1, max(piles)
while lo < hi:
    mid = (lo + hi) // 2
    if hours(mid) <= h: hi = mid       # подошло — граница не правее
    else:               lo = mid + 1   # не подошло — mid точно мал
print(lo)                              # 23

Шаг 5. Проверка соседа. При $k = 23$ часы складываются в $2+1+1+1+1 = 6 \le 6$ ✓. При $k = 22$ — в $2+1+2+1+1 = 7 > 6$ ✗. Значит 23 — граница, а не «примерно то».

Ответ: 23.

Чем эта задача отличается от моста b1107

Там искали максимум и делили нацело вниз, здесь ищут минимум и округляют вверх. Шаблон соответственно обычный, а не зеркальный: hi = mid и lo = mid + 1, середина без единицы.

Направление округления читается прямо из условия: «час тратится целиком» — вверх, «остаток короче куска выбрасывается» — вниз. Перепутанное округление даёт число, отличающееся от верного на единицу, и никакого сигнала об ошибке.

EN

Step 1. Identify the search variable. The phrase “smallest $k$ such that” signals binary search on the answer. We are searching for $k$ itself, not for an element of the array of pile sizes.

Step 2. Predicate. At rate $k$, a pile of size $p$ takes $\lceil p/k\rceil$ hours because a partial hour is still spent:

$$\text{hours}(k) = \sum_i \left\lceil \frac{p_i}{k}\right\rceil$$

Step 3. Monotonicity. As $k$ increases, the required time decreases. Hence the feasible values form the ray $[k_0,+\infty)$, and we need its left endpoint.

Step 4. Bounds. Set $\text{lo}=1$, since smaller values are impossible. Set $\text{hi}=\max p_i=30$, which is certainly feasible: at this rate each pile is finished in one hour, using five of the six hours.

piles = [30, 11, 23, 4, 20]; h = 6

def hours(k):
    return sum(-(-p // k) for p in piles)    # -(-a//b) = ceiling division

lo, hi = 1, max(piles)
while lo < hi:
    mid = (lo + hi) // 2
    if hours(mid) <= h: hi = mid       # feasible — boundary is not to the right
    else:               lo = mid + 1   # infeasible — mid is definitely too small
print(lo)                              # 23

Step 5. Check the adjacent value. For $k = 23$, the hours sum to $2+1+1+1+1 = 6 \le 6$ ✓. For $k = 22$, they sum to $2+1+2+1+1 = 7 > 6$ ✗. Therefore 23 is the exact boundary, not merely an approximation.

Answer: 23.

How this differs from bridge problem b1107

There we sought a maximum and rounded down; here we seek a minimum and round up. Accordingly, this is the ordinary rather than mirrored template: use hi = mid, lo = mid + 1, and no added one in the midpoint.

The direction of rounding comes directly from the statement: “the full hour is used” means round up, while “a remainder shorter than the piece is discarded” means round down. The wrong direction usually gives an answer off by one without any obvious warning.

уверенность1 — угадал, 5 — уверен полностью
Y1103Уровень YMLSАлгоритмыуровень YMLS · скользящее окно
RU

Дана строка algorithmsandprogramming (24 символа). Найдите длину самой длинной её подстроки (подряд идущих символов), в которой все символы различны.

В настоящей постановке строка длиной до $2\cdot10^{5}$ символов; здесь 24, чтобы ответ можно было пересчитать руками. Назови сложность и приём до того, как писать код.

EN

Consider the 24-character string algorithmsandprogramming. Find the length of its longest substring, that is, its longest contiguous segment, in which all characters are distinct.

In the full version, the string may contain up to $2\cdot10^{5}$ characters. Here its length is 24, so the answer can be checked by hand. State the technique and complexity before writing code.

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. Одна строка из строчных латинских букв, длина от 1 до $10^5$. Вывод. Длина самой длинной подстроки, в которой все символы различны.

EN

Input. One line of lowercase Latin letters, length from 1 to $10^5$. Output. The length of the longest substring whose characters are all distinct.

ВыводOutput
Подсказка / Hint
RU

Расширяй правую границу окна; когда символ повторился, сдвигай левую границу за его предыдущее вхождение.

EN

Expand the right boundary of a window. When a character repeats, move the left boundary just beyond its previous occurrence.

Решение / Solution
RU

Состояние окна — словарь «символ — его последний индекс». Когда правый конец приносит символ, уже стоящий внутри окна, левая граница перескакивает сразу за его прошлое вхождение: все промежуточные положения заведомо плохи, проверять их незачем.

s = "algorithmsandprogramming"
seen = {}          # символ -> последний индекс
left = 0; best = 0
for right, ch in enumerate(s):
    if ch in seen and seen[ch] >= left:
        left = seen[ch] + 1        # сдвигаем левую границу
    seen[ch] = right
    best = max(best, right - left + 1)
print(best)                        # 13

Ответ: 13 — подстрока lgorithmsandp.

Условие seen[ch] >= left обязательно

Без него левая граница может прыгнуть назад, если символ встречался давно, ещё до текущего окна. Тогда окно расширится за пределы допустимого и ответ будет завышен.

Сложность $O(n)$: каждый из двух указателей проходит строку ровно один раз и никогда не идёт назад. Как только левая граница получила право двигаться назад, ломается и правильность, и линейность — сразу обе.

Проверка ответа за десять секунд

Различных букв в строке ровно 13, значит подстрока без повторов длиннее 13 невозможна в принципе. Ответ упёрся ровно в этот потолок: в подстроке lgorithmsandp встречаются все тринадцать букв по одному разу.

Такая прикидка не заменяет решения, но мгновенно ловит завышенный ответ, а здесь ещё и подсказывает, что искать надо окно, вмещающее весь алфавит строки.

EN

The window state is a dictionary mapping each character to its most recent index. When the right endpoint brings in a character already inside the window, move the left endpoint immediately past its previous occurrence. Every intermediate position is invalid, so there is no reason to check it.

s = "algorithmsandprogramming"
seen = {}          # character -> last index
left = 0; best = 0
for right, ch in enumerate(s):
    if ch in seen and seen[ch] >= left:
        left = seen[ch] + 1        # move the left boundary
    seen[ch] = right
    best = max(best, right - left + 1)
print(best)                        # 13

Answer: 13, attained by the substring lgorithmsandp.

The condition seen[ch] >= left is essential

Without it, the left boundary may move backward when the same character occurred long ago, before the current window. The window would then expand beyond the valid range and the answer would be too large.

The complexity is $O(n)$: each of the two pointers traverses the string once and never moves backward. Allowing the left boundary to move backward destroys both correctness and linear complexity at once.

A ten-second answer check

The string contains exactly 13 distinct letters, so no repetition-free substring can have length greater than 13. The answer reaches this upper bound: lgorithmsandp contains all thirteen letters exactly once.

This estimate does not replace a solution, but it catches an answer that is too large immediately and, here, suggests looking for a window containing the string's entire alphabet.

уверенность1 — угадал, 5 — уверен полностью
Y1101Уровень YMLSАлгоритмыуровень YMLS · префиксы по модулю
RU

Для массива из задачи w1101 найдите количество непустых подотрезков (подряд идущих участков), сумма которых делится на 7. Два подотрезка считаются разными, если различаются парой границ.

В настоящей постановке этой задачи $n \le 2\cdot10^{5}$ — перебор всех подотрезков там не проходит по времени; здесь $n = 30$, чтобы ответ можно было проверить перебором. Ограничение прочитано — сложность решения назови вслух до того, как писать код.

EN

For the array from problem w1101, find the number of nonempty subarrays, that is, contiguous segments, whose sum is divisible by 7. Two subarrays are distinct if their pairs of endpoints differ.

In the full version of this problem, $n \le 2\cdot10^{5}$, so enumerating every subarray is too slow. Here $n = 30$, allowing the answer to be verified by exhaustive search. Read the constraint and state the target complexity aloud before writing code.

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. В первой строке $n$ ($1 \le n \le 10^5$) и $k$ ($1 \le k \le 10^9$), во второй — $n$ целых чисел (бывают отрицательные). Вывод. Количество непустых подотрезков, сумма которых делится на $k$.

EN

Input. The first line holds $n$ ($1 \le n \le 10^5$) and $k$ ($1 \le k \le 10^9$); the second holds $n$ integers (negatives allowed). Output. The number of non-empty subarrays whose sum is divisible by $k$.

ВыводOutput
Подсказка / Hint
RU

Сумма на отрезке $(l, r]$ равна $S_r - S_l$. Когда разность делится на 7?

EN

The sum on $(l,r]$ is $S_r-S_l$. When is this difference divisible by 7?

Решение / Solution
RU

Ключевая идея. Сумма на $(l, r]$ делится на 7 тогда и только тогда, когда $S_r$ и $S_l$ дают одинаковый остаток при делении на 7. Значит вопрос про отрезки превратился в вопрос про пары префиксов с равным остатком, а такие пары считает счётчик — ровно как в мосте b1104, только там сравнивались сами суммы, а здесь их остатки.

from collections import Counter
c = Counter({0: 1})     # пустой префикс тоже участвует
s = 0; total = 0
for v in a:
    s = (s + v) % 7
    total += c[s]       # все прежние префиксы с тем же остатком
    c[s] += 1
print(total)            # 56

Ответ: 56.

Почему c[0] = 1 изначально

Пустой префикс $S_0 = 0$ обязан участвовать, иначе потеряются все подотрезки, начинающиеся с первого элемента. Это классическая ошибка на единицу: код выглядит правильно, ответ занижен, и понять причину без разбора трудно.

Почему счётчик здесь обязателен

В b1104 префиксные суммы строго возрастали, поэтому каждое значение встречалось не больше одного раза, и счётчик отвечал «нуль или один». Остатков всего семь, а префиксов тридцать один, поэтому одинаковые остатки встречаются по многу раз — и вопрос «сколько прежних» становится настоящим.

Сложность $O(n)$ по времени и $O(k)$ по памяти, где $k = 7$. Наивный перебор всех подотрезков был бы $O(n^2)$, а с пересчётом суммы каждый раз — даже $O(n^3)$.

EN

Key idea. The sum on $(l,r]$ is divisible by 7 if and only if $S_r$ and $S_l$ have the same remainder modulo 7. Thus a question about subarrays becomes a question about pairs of prefix sums with equal remainders. A counter counts these pairs, just as in b1104; that problem compared the sums themselves, while this one compares their remainders.

from collections import Counter
c = Counter({0: 1})     # the empty prefix counts too
s = 0; total = 0
for v in a:
    s = (s + v) % 7
    total += c[s]       # all earlier prefixes with the same remainder
    c[s] += 1
print(total)            # 56

Answer: 56.

Why initialize c[0] = 1?

The empty prefix $S_0 = 0$ must be included; otherwise every subarray beginning with the first element is missed. This is a classic off-by-one error: the code looks correct, but the answer is too small and the cause is difficult to see without tracing it.

Why a counter is essential here

In b1104, prefix sums were strictly increasing, so each value occurred at most once and the counter returned only zero or one. Here there are only seven remainders but thirty-one prefix sums, so equal remainders occur many times and “how many previous ones?” becomes a genuine counting question.

The complexity is $O(n)$ time and $O(k)$ space, where $k=7$. Naively enumerating every subarray takes $O(n^2)$ time, or even $O(n^3)$ if each sum is recomputed from scratch.

уверенность1 — угадал, 5 — уверен полностью
зачем это сегодня
RU

Про онлайн-этап известен факт, который меняет тактику целиком: принимается только числовой ответ, обоснование не требуется и ход решения не проверяется.

Отсюда следует то, чем большинство поступающих не пользуется. Задача, аналитическое решение которой не видно, часто закрывается за две минуты точным перебором, динамикой по состояниям или симуляцией на миллион испытаний. Это не обход правил, а ровно то, что регламент разрешает.

Но машина не заменяет первый навык дня, а только страхует его. Восемь задач за четыре часа — это полчаса на задачу, и почти весь провал случается не в счёте, а на входе: двадцать минут ушло на разбор случаев там, где хватило разности двух хвостов, или на интеграл там, где стояла табличная формула. Поэтому метрика дня — доля верно опознанных типов, и она важнее доли решённых.

Вторая половина дня — смешанная практика: восемь задач ступени YMLS из шести тем вперемешку. Именно в таком виде задачи придут послезавтра.

EN

There is one fact about the online stage that changes the entire tactic: only a numerical answer is accepted; no justification is submitted and the solution path is not checked.

That leads to an option most applicants do not use. A problem whose analytical solution is not visible can often be closed in two minutes by exact enumeration, dynamic programming over states, or a million-trial simulation. This is not a loophole; it is precisely what the rules allow.

But the machine does not replace today’s first skill; it only protects it. Eight problems in four hours means half an hour per problem, and almost every failure happens at the entry point rather than in the arithmetic: twenty minutes disappear on casework where a difference of two tails was enough, or on an integral where a table formula applied. So today’s metric is the share of types recognized correctly, and it matters more than the share solved.

The second half of the day is mixed practice: eight YMLS problems from six topics, deliberately interleaved. That is exactly how the problems will arrive the day after tomorrow.

Навыки по порядку

Тема разбита на отдельные навыки от простого к сложному. Для каждого указаны тренировочные задачи.

  1. 1Тип и первый ходType and first moveПо двум-трём словам условия называешь тему и первый ход раньше, чем берёшь ручку; если приём табличный, ответ выписывается прямо из блока «Мост» за один-два шага, и всё время задачи уходит на проверку, а не на счётFrom two or three words in the statement, name the topic and first move before picking up your pen; if it is a table technique, write the answer directly from the “Bridge” block in one or two steps, and spend the problem’s time checking rather than calculatingY1205Y1207Y1206Y1208
  2. 2Хвост вместо значенияTail instead of valueПриём узнан, но в готовом виде его нет: считаешь не то, о чём спросили, а эквивалентное событие. «Максимум равен $t$» превращаешь в разность двух «все не больше $t$», а матожидание — в сумму хвостов $\P(X \ge k)$, потому что и то и другое факторизуется по испытаниямYou recognize the technique but it is not available in ready-made form: count an equivalent event instead of the one asked about. Turn “the maximum equals $t$” into the difference of two “everything is at most $t$” events, and an expectation into a sum of tails $\P(X \ge k)$, because both factor over independent trialsW1201W1202B1201B1202Y1201Y1202
  3. 3Область вместо исходовRegion instead of outcomesТа же подмена вопроса, но исходов бесконечно много и считать штуки нечего: переводишь условие в неравенство, корень убираешь возведением в квадрат, получаешь область и берёшь её долю площадиMake the same question substitution when there are infinitely many outcomes and nothing to enumerate: turn the condition into an inequality, remove the root by squaring, obtain a region, and take its area fractionW1203B1203Y1204
  4. 4Машина вместо формулыMachine instead of formulaНи готового приёма, ни короткой подмены не нашлось: оцениваешь размер пространства исходов и выбираешь способ — до нескольких миллионов точный перебор с Fraction, дальше динамика по состояниям, а в непрерывном случае численная квадратура или симуляция с честной оценкой числа верных знаковNo ready-made technique or short substitution is available: estimate the size of the outcome space and choose a method—up to a few million, exact enumeration with Fraction; beyond that, state-based dynamic programming; for a continuous case, numerical quadrature or simulation with an honest estimate of reliable digitsB1205B1204Y1203S1201

Расписание

0:00–0:15РазогревWarm-up Семнадцать пунктов блока «Мост» вслух, без конспектов. Сегодня это не ритуал: четыре из восьми задач ступени YMLS закрываются одной строкой оттуда.Say all seventeen points in the “Bridge” block aloud, without notes. Today this is not a ritual: four of the eight YMLS problems close with a single line from it.
0:15–1:15Урок: распознавание и два аналитических ходаLesson: recognition and two analytical moves Части 1–3. Каждый числовой пример считай на бумаге раньше, чем прочитаешь ответ.Parts 1–3. Calculate every numerical example on paper before reading the answer.
1:15–2:00Урок: машинаLesson: the machine Части 4–8. Каждый сниппет набери и запусти, поменяй в нём числа и предскажи вывод до нажатия Enter. Не читать — запускать.Parts 4–8. Type and run every snippet, change its numbers, and predict the output before pressing Enter. Do not read—run.
2:00–3:20Смешанная практикаMixed practice Задачи по ступеням 1 → 4. Перед каждой вслух тема и первый ход, и только потом счёт. Ступень 3 — четыре моста, они входят в обязательный объём целиком.Problems in levels 1 → 4. Before each one, say the topic and first move aloud, and only then calculate. Level 3 has four bridges; all four are required.
3:20–3:45Мини-тестMini-test y1204 под таймером, в режиме экзамена: подсказка и разбор закрыты, ответ вводится один раз.Do y1204 under a timer, in exam mode: hints and walkthrough are closed, and you enter the answer only once.
3:45–4:00АудитAudit Критерии внизу страницы и журнал ошибок за все двенадцать дней: два самых частых типа выписать на бумагу отдельно. Завтра мок.Use the criteria at the bottom of the page and the twelve-day error log; write the two most frequent types on separate paper. Tomorrow is the mock.

Урок

разбираем с нуля
RU

Вход: восемь задач, шесть тем

Банк дня устроен как экзамен: восемь задач ступени YMLS идут вперемешку, и так они придут 4 сентября — без заголовка «вероятность» над условием. Каждая проще того, что ты решал в свой сильный день по её теме; опасность не в них, а в первых тридцати секундах: неверный первый ход стоит двадцати минут, которых при восьми задачах нет.

Часть 1. Первые тридцать секунд

Правило: сначала вслух тип и первый ход, потом ручка. Пока условие не переведено в одну фразу, счёт не начинается.

В условии стоитТипПервый ход
«максимум равен», «минимум равен»Распределение экстремумаСчитать «все не больше $t$», взять разность
«в среднем», матожидание числа шаговМатожидание целой величиныХвостовая формула через $\P(X \ge k)$
«наудачу выбирается точка»Геометрическая вероятностьНеравенство, область, доля площади
«ни один не на своём месте»БеспорядкиВключения-исключения или перебор
«сколько делителей», «сколькими способами»СчётПравило произведения по независимым выборам
Уравнение плоскости и точкаЛиналНормаль читается прямо из коэффициентов
«работают одновременно», «за сколько успеют»СкоростиСложить скорости, поделить, округлить вверх
Интеграл с $e^{-x}$ по лучу $[0,\infty)$Табличный интегралГамма-интеграл, ответ $n!$

Семь строк из восьми — пункты блока «Мост»; новая только первая, ей посвящена часть 2. Любая из семи вспоминается дольше пары секунд — восстанавливай сейчас.

Регламент, который меняет тактику

На онлайн-этапе принимается только числовой ответ: обоснование не сдаётся, ход решения не проверяется. Значит способ получения числа выбираешь ты, и машинный ничем не хуже. Правило времени: аналитический ход не найден за 10 минут — переходи к машинному.

Часть 2. Считай хвост, а не значение

Задача. Кубик бросают $n$ раз. Чему равна вероятность того, что максимум равен $t$?

Прямой счёт требует разбора случаев: ровно одна $t$ и остальные меньше, ровно две и остальные меньше, и так далее — сумма из $n$ слагаемых с биномиальными коэффициентами. Ход, убирающий разбор целиком: событие «максимум не больше $t$» означает, что каждый бросок не больше $t$, а такие условия независимы, поэтому вероятность есть степень; «равно» получается вычитанием вложенного события «все не больше $t-1$»:

$$\P(\max \le t) = \left(\frac{t}{6}\right)^{n}, \qquad \P(\max = t) = \frac{t^{n} - (t-1)^{n}}{6^{n}}$$

Для минимума всё зеркально: «минимум не меньше $t$» означает, что каждый бросок не меньше $t$, значит $\P(\min \ge t) = \left(\frac{7-t}{6}\right)^{n}$. Работает это по одной причине: «не больше $t$» — условие на каждое испытание по отдельности, и вероятность распадается в произведение, а «равно $t$» — условие на весь набор сразу, и оно не распадается.

Тот же ход для матожидания. Хвостовая формула из блока «Мост» переводит $\E X$ в сумму $\P(X \ge k)$, и работа сводится к вопросу, что значит «$X \ge k$» на языке испытаний. Кубик бросают до первой шестёрки: событие $\{N \ge k\}$ означает, что первые $k-1$ бросков шестёрку не дали, поэтому $\P(N \ge k) = (5/6)^{k-1}$ и $\E N = \frac{1}{1 - 5/6} = 6$ — геометрическая прогрессия вместо ряда с множителем $k$ внутри.

Часть 3. Непрерывный исход: неравенство, область, площадь

Если точка выбирается наудачу в фигуре, исходов бесконечно много и считать нечего: вероятность есть доля площади (блок «Мост»). Вся работа — превратить словесное условие в область. Пример — это финал второго дня, y0202, и он берётся сюда готовым: $X$ и $Y$ независимы и равномерны на $[0,1]$, найти $\P(|X-Y| < 1/3)$. Пара $(X,Y)$ равномерна в единичном квадрате, условие $|x-y| < 1/3$ вырезает полосу вдоль диагонали, а вне полосы остаются два прямоугольных треугольника с катетами $2/3$:

$$\P = 1 - 2\cdot\frac12\left(\frac23\right)^{2} = 1 - \frac49 = \frac59 \approx 0.5556$$

Когда в условии стоит расстояние, появляется корень: возводить неравенство в квадрат здесь законно, обе части неотрицательны. После возведения квадраты координат часто сокращаются, и граница оказывается параболой — это не совпадение: «расстояние до точки равно расстоянию до прямой» и есть определение параболы с фокусом и директрисой.

Что здесь теряют

«Ближайшая сторона» — это четыре разных условия, а не одно: квадрат режется диагоналями на четыре треугольника, в каждом ближайшая сторона своя, и по симметрии достаточно посчитать один и умножить на 4. И площадь подобласти всегда делится на площадь фигуры — для единичного квадрата делить не на что, про деление и забывают.

Часть 4. Машина считает: точный перебор

Первый вопрос — размер пространства исходов. Ориентир вчерашнего дня: $10^8$ простых операций в секунду, значит перебор до нескольких миллионов исходов мгновенный. Шесть бросков кубика — это $6^6 = 46656$, перестановки шести элементов — $6! = 720$, двоичные строки длины 12 — $2^{12} = 4096$: всё перебирается быстрее, чем вспоминается формула. Граница около $10^7$: подмножества 20 предметов ($2^{20} \approx 10^6$) ещё считаются, а перестановки 12 элементов ($12! \approx 4.8\cdot10^8$) — уже нет.

import itertools
from fractions import Fraction as F

c = sum(1 for t in itertools.product(range(1, 7), repeat=6) if max(t) == 5)
print(c, F(c, 6**6), round(float(F(c, 6**6)), 4))   # 11529 427/1728 0.2471

Ответ выходит точным: Fraction не округляет по дороге. И перебор стоит запускать даже тогда, когда формула найдена: два независимых пути к одному числу — надёжнейшая из проверок.

Часть 5. Машина считает: динамика

Когда пространство не помещается в перебор, тот же счёт делается динамикой. Три вопроса, всегда в этом порядке: состояние — какой минимальный набор данных описывает подзадачу; переход — как значение в состоянии выражается через уже посчитанные; база — с чего всё начинается.

Пример. Сколькими способами набрать сумму 30 упорядоченной последовательностью слагаемых из $\{1,3,5\}$? Состояние: $dp[i]$ — число способов набрать сумму $i$. Переход: смотрим, каким было последнее слагаемое, отсюда $dp[i] = dp[i-1] + dp[i-3] + dp[i-5]$; база $dp[0] = 1$.

n = 30
dp = [0] * (n + 1); dp[0] = 1
for i in range(1, n + 1):
    for c in (1, 3, 5):
        if i >= c:
            dp[i] += dp[i - c]
print(dp[:6], dp[n])       # [1, 1, 1, 2, 3, 5] 390257

Проверка руками занимает минуту и обязательна: сумму 4 дают $1{+}1{+}1{+}1$, $1{+}3$ и $3{+}1$ — ровно три последовательности, и в выводе действительно dp[4] = 3.

Порядок циклов меняет саму задачу

Внешний цикл по сумме, внутренний по номиналам — считаются упорядоченные последовательности, их 390257. Поменяй циклы местами — получатся неупорядоченные разбиения, и для той же суммы 30 их всего 40. Код отличается двумя строками, ответ — почти в десять тысяч раз, поэтому маленький случай, проверенный руками, обязателен.

Часть 6. Жадность: первый ход, который можно доказать

Иногда перебор не нужен вовсе: локально лучший выбор оказывается глобально верным, и всё дело в слове «оказывается». Классика: дан набор отрезков, выбрать максимальное число попарно непересекающихся.

iv = [(1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16)]
iv.sort(key=lambda p: p[1])        # по ПРАВОМУ концу
cnt, end = 0, float('-inf')
for s, e in iv:
    if s >= end:
        cnt += 1; end = e
print(cnt)                         # 4
Сортировка решает всё

По правому концу — верно: взяв отрезок, заканчивающийся раньше всех, оставляем максимум места остальным. Формально это аргумент обмена: в любом оптимальном решении первый отрезок можно заменить на самый рано заканчивающийся, не ухудшив результат. По левому концу — неверно: на наборе $(0,10)$, $(0,4)$, $(5,9)$ такая жадность возьмёт длинный отрезок и остановится на одном вместо двух. Жадность без аргумента обмена — догадка. Задачи на жадность в банке дня нет намеренно: на онлайн-этапе она почти не встречается, зато про сортировку по правому концу спрашивают на собеседовании. Поэтому здесь сниппет, который надо набрать и запустить, а не задача, которую надо решить.

Часть 7. Машина считает: симуляция

Когда исход непрерывный, перебора не существует вовсе, а интеграл берётся плохо, остаётся Монте-Карло: повторить опыт много раз и взять долю.

import numpy as np
rng = np.random.default_rng(0)
p = rng.random((5_000_000, 2))
print((np.abs(p[:, 0] - p[:, 1]) < 1/3).mean())     # 0.5557418 — четвёртый знак уже врёт

Точный ответ этой задачи посчитан в части 3: $5/9 = 0.5556$ — пять миллионов испытаний четвёртого знака не дали.

Сколько знаков стоит за симуляцией

Погрешность доли имеет порядок $1/\sqrt{N}$: миллион испытаний — примерно три верных знака, сто миллионов — четыре, и формат «четыре знака после запятой» симуляция сама не закрывает. Отсюда дисциплина: симуляция — для проверки, аналитика — для точности. Аналитики нет вовсе — гони $10^8$ испытаний и помни, что последний знак ненадёжен.

Часть 8. Символьные вычисления за десять секунд

import sympy as sp, numpy as np
x = sp.Symbol('x')
print(sp.integrate(x**5 * sp.exp(-x), (x, 0, sp.oo)))                   # 120
print(sp.limit((sp.exp(x**2) - sp.cos(x)) / x**2, x, 0))                # 3/2
n = np.array([1., 2, 2]); p = np.array([1., 2, 3])
print(abs(n @ p - 6) / np.linalg.norm(n))                               # 1.6666666666666667
print(np.linalg.det(np.array([[3., 1, 2], [0, 5, 1], [4, 2, 7]])))      # 62.99999999999999

Определитель numpy приближённый: $62.99999999999999$ означает ровно $63$, за точным значением иди в sympy.Matrix. А если 4 сентября не окажется самого sympy, символьный ответ заменяется численным: scipy.integrate.quad вместо sp.integrate, scipy.optimize.brentq вместо sp.nsolve, а mpmath.quad берёт даже несобственные интегралы по $[0,\infty)$. Проверь сегодня, что у тебя импортируется: numpy, sympy, scipy, mpmath. Узнать это на экзамене — потерять задачу.

Дисциплина: оценка — счёт — сверка
  1. Оценка руками до счёта: какого порядка ответ, ближе он к нулю или к единице, больше пяти или меньше. Записать до того, как считаешь.
  2. Счёт — аналитический или машинный, любой.
  3. Сверка с оценкой, а если это стоит тридцати секунд — и вторым независимым путём. Ответ, противоречащий оценке, — почти всегда ошибка в постановке, а не в машине.

И последнее: на очном экзамене 20 сентября компьютера не будет. Сегодняшний арсенал — оружие для 4 сентября, а не замена умению считать руками.

Что должно остаться в голове

  1. Сначала тип и первый ход вслух, потом ручка. Неверный первый ход стоит двадцати минут.
  2. «Максимум или минимум равен $t$» — разность двух хвостов; факторизуется именно хвост.
  3. Матожидание целой величины — сумма $\P(X \ge k)$; работа в том, чтобы описать это событие словами.
  4. Непрерывный исход: неравенство, область, доля площади; корень убирается возведением в квадрат, граница часто парабола.
  5. Меньше нескольких миллионов исходов — точный перебор и Fraction; больше — динамика.
  6. Динамика: состояние, переход, база. Порядок циклов меняет смысл ответа.
  7. Жадность верна только там, где проходит аргумент обмена.
  8. Симуляция даёт три знака за миллион испытаний и четыре — за сто миллионов.
EN

Opening: eight problems, six topics

Today’s bank is arranged like the exam: eight YMLS problems appear in mixed order, and that is how they will arrive on September 4—without a “probability” heading above the statement. Each is easier than what you solved on your strongest day in its topic; the danger is the first thirty seconds: a wrong first move costs twenty minutes that you do not have across eight problems.

Part 1. The first thirty seconds

The rule is: say the type and first move aloud, then pick up the pen. Do not start calculating until the statement has been translated into one sentence.

The statement saysTypeFirst move
“the maximum equals,” “the minimum equals”Extreme-value distributionCount “everything is at most $t$,” then take a difference
“on average,” expected number of stepsExpectation of an integer-valued variableUse the tail formula via $\P(X \ge k)$
“a point is chosen at random”Geometric probabilityInequality, region, area fraction
“nothing is in its original position”DerangementInclusion–exclusion or enumeration
“how many divisors,” “in how many ways”CountingProduct rule for independent choices
Plane equation and a pointLinear algebraRead the normal directly from the coefficients
“work simultaneously,” “how long will it take”RatesAdd the rates, divide, round up
Integral with $e^{-x}$ over the ray $[0,\infty)$Table integralGamma integral; the answer is $n!$

Seven of the eight rows are “Bridge” points; only the first is new, and Part 2 is devoted to it. If any of the seven takes more than a couple of seconds to recall, restore it now.

The rule that changes the tactic

The online stage accepts only a numerical answer: no justification is submitted and the solution path is not checked. You choose how to obtain the number, and a machine is just as valid. Time rule: if you have not found an analytical route in 10 minutes, switch to a machine method.

Part 2. Count the tail, not the value

Problem. A die is rolled $n$ times. What is the probability that the maximum equals $t$?

Direct counting requires casework: exactly one $t$ with all the rest smaller, exactly two with all the rest smaller, and so on—a sum of $n$ terms with binomial coefficients. The move that removes all the casework is this: “the maximum is at most $t$” means every roll is at most $t$; the conditions are independent, so the probability is a power. “Equals” is then obtained by subtracting the nested event “everything is at most $t-1$”:

$$\P(\max \le t) = \left(\frac{t}{6}\right)^{n}, \qquad \P(\max = t) = \frac{t^{n} - (t-1)^{n}}{6^{n}}$$

For the minimum, mirror the argument: “the minimum is at least $t$” means every roll is at least $t$, so $\P(\min \ge t) = \left(\frac{7-t}{6}\right)^{n}$. This works for one reason: “at most $t$” is a condition on each trial separately, so the probability factors into a product, while “equals $t$” is a condition on the whole collection and does not factor.

The same move for expectation. The “Bridge” tail formula turns $\E X$ into a sum of $\P(X \ge k)$, and the work is to describe “$X \ge k$” in the language of the trials. Roll a die until the first six: the event $\{N \ge k\}$ means the first $k-1$ rolls were not six, so $\P(N \ge k) = (5/6)^{k-1}$ and $\E N = \frac{1}{1 - 5/6} = 6$—a geometric progression instead of a series with a factor k inside.

Part 3. Continuous outcome: inequality, region, area

When a point is chosen at random inside a figure, there are infinitely many outcomes and nothing to count: probability is an area fraction (“Bridge”). The whole job is to turn the verbal condition into a region. Example: this is final y0202 from day 2, brought here ready-made: $X$ and $Y$ are independent and uniform on $[0,1]$; find $\P(|X-Y| < 1/3)$. The pair $(X,Y)$ is uniform in the unit square, and $|x-y| < 1/3$ cuts out a strip along the diagonal. Outside the strip are two right triangles with legs $2/3$:

$$\P = 1 - 2\cdot\frac12\left(\frac23\right)^{2} = 1 - \frac49 = \frac59 \approx 0.5556$$

When the statement contains distance, a square root appears: squaring the inequality is legal here because both sides are nonnegative. After squaring, coordinate squares often cancel, and the boundary turns out to be a parabola—not a coincidence: “distance to a point equals distance to a line” is the definition of a parabola with a focus and directrix.

What people lose here

“The nearest side” means four different conditions, not one: the square is cut by its diagonals into four triangles, each with its own nearest side, and by symmetry it is enough to calculate one and multiply by 4. Also, the subregion’s area is always divided by the figure’s area—for a unit square there is nothing to divide by, so people forget the division.

Part 4. Let the machine count: exact enumeration

The first question is the size of the outcome space. Yesterday’s reference is $10^8$ simple operations per second, so enumerating a few million outcomes is instant. Six die rolls are $6^6 = 46656$, permutations of six elements are $6! = 720$, and binary strings of length 12 number $2^{12} = 4096$: each can be enumerated faster than you can recall the formula. The boundary is around $10^7$: subsets of 20 items ($2^{20} \approx 10^6$) are still feasible, but permutations of 12 items ($12! \approx 4.8\cdot10^8$) are not.

import itertools
from fractions import Fraction as F

c = sum(1 for t in itertools.product(range(1, 7), repeat=6) if max(t) == 5)
print(c, F(c, 6**6), round(float(F(c, 6**6)), 4))   # 11529 427/1728 0.2471

The answer is exact: Fraction does not round along the way. Run the enumeration even when you have found a formula: two independent paths to the same number are the most reliable check.

Part 5. Let the machine count: dynamic programming

When the outcome space does not fit in enumeration, the same count can be done with dynamic programming. Ask three questions, always in this order: state—what smallest set of data describes the subproblem; transition—how the state value is expressed through values already computed; base—where it begins.

Example. How many ordered sequences of summands from $\{1,3,5\}$ add up to 30? State: $dp[i]$ is the number of ways to make sum $i$. Transition: look at the last summand, giving $dp[i] = dp[i-1] + dp[i-3] + dp[i-5]$; base: $dp[0] = 1$.

n = 30
dp = [0] * (n + 1); dp[0] = 1
for i in range(1, n + 1):
    for c in (1, 3, 5):
        if i >= c:
            dp[i] += dp[i - c]
print(dp[:6], dp[n])       # [1, 1, 1, 2, 3, 5] 390257

Check it by hand; it takes a minute and is mandatory: sum 4 comes from $1{+}1{+}1{+}1$, $1{+}3$, and $3{+}1$—exactly three sequences—and the output really has dp[4] = 3.

Loop order changes the problem itself

Outer loop over sums and inner loop over denominations counts ordered sequences, 390257 of them. Swap the loops and you get unordered partitions; for the same sum 30 there are only 40. The code differs by two lines and the answer by almost a factor of ten thousand, so a small hand-checked case is mandatory.

Part 6. Greedy methods: a first move you can prove

Sometimes enumeration is unnecessary: a locally best choice turns out to be globally correct, and everything hinges on the words “turns out.” Classic problem: given intervals, choose the maximum number of pairwise non-overlapping ones.

iv = [(1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16)]
iv.sort(key=lambda p: p[1])        # by the RIGHT endpoint
cnt, end = 0, float('-inf')
for s, e in iv:
    if s >= end:
        cnt += 1; end = e
print(cnt)                         # 4
Sorting decides everything

Sorting by right endpoint is correct: choosing the interval that ends earliest leaves the most room for the rest. Formally, this is an exchange argument: in any optimal solution, replace its first interval with the earliest-finishing one without making the result worse. Sorting by left endpoint is wrong: on $(0,10)$, $(0,4)$, $(5,9)$, that greedy choice takes the long interval and stops at one instead of two. Greedy without an exchange argument is just a guess. There is deliberately no greedy problem in today’s bank: it is rare in the online stage, but interviews do ask about sorting by right endpoint. So this is a snippet to type and run, not a problem to solve.

Part 7. Let the machine count: simulation

When the outcome is continuous, enumeration does not exist at all, and the integral is difficult, use Monte Carlo: repeat the experiment many times and take the fraction.

import numpy as np
rng = np.random.default_rng(0)
p = rng.random((5_000_000, 2))
print((np.abs(p[:, 0] - p[:, 1]) < 1/3).mean())     # 0.5557418 — the fourth digit is already wrong

The exact answer for this problem was calculated in Part 3: $5/9 = 0.5556$—five million trials did not deliver a reliable fourth digit.

How many digits simulation buys you

The error of a fraction is on the order of $1/\sqrt{N}$: a million trials give about three correct digits, one hundred million give four, and the “four digits after the decimal point” format cannot be guaranteed by simulation alone. Hence the discipline: simulation is for checking; analysis is for precision. If there is no analytical route at all, run $10^8$ trials and remember that the last digit is unreliable.

Part 8. Symbolic computation in ten seconds

import sympy as sp, numpy as np
x = sp.Symbol('x')
print(sp.integrate(x**5 * sp.exp(-x), (x, 0, sp.oo)))                   # 120
print(sp.limit((sp.exp(x**2) - sp.cos(x)) / x**2, x, 0))                # 3/2
n = np.array([1., 2, 2]); p = np.array([1., 2, 3])
print(abs(n @ p - 6) / np.linalg.norm(n))                               # 1.6666666666666667
print(np.linalg.det(np.array([[3., 1, 2], [0, 5, 1], [4, 2, 7]])))      # 62.99999999999999

NumPy’s determinant is approximate: $62.99999999999999$ means exactly $63$; for an exact value, use sympy.Matrix. And if sympy is unavailable on September 4, replace symbolic answers with numeric ones: scipy.integrate.quad instead of sp.integrate, scipy.optimize.brentq instead of sp.nsolve, and mpmath.quad can even handle improper integrals over $[0,\infty)$. Check today that numpy, sympy, scipy, and mpmath import correctly. Discovering that in the exam costs a problem.

Discipline: estimate—calculate—check
  1. Estimate by hand before calculating: what order of magnitude should the answer have; is it closer to zero or one; greater than five or less? Write it down first.
  2. Calculate—analytically or by machine, either is fine.
  3. Check against the estimate, and if it takes thirty seconds, against a second independent route.

An answer that contradicts the estimate is almost always a setup error, not a machine error.

Finally, the in-person exam on September 20 will have no computer. Today’s arsenal is a weapon for September 4, not a replacement for the ability to calculate by hand.

What should stay in your head

  1. Say the type and first move aloud, then pick up the pen. A wrong first move costs twenty minutes.
  2. “The maximum or minimum equals $t$” is the difference of two tails; it is the tail that factors.
  3. The expectation of an integer-valued variable is the sum of $\P(X \ge k)$; the work is describing that event in words.
  4. Continuous outcome: inequality, region, area fraction; remove the root by squaring, and the boundary is often a parabola.
  5. Fewer than a few million outcomes: exact enumeration with Fraction; more: dynamic programming.
  6. Dynamic programming: state, transition, base. Loop order changes the meaning of the answer.
  7. Greedy is correct only where an exchange argument applies.
  8. Simulation gives three digits for a million trials and four for one hundred million.

Признаки и действия

Слева — что заметить в условии. Справа — что сделать первым.

УвиделПервый ход
«Максимум равен», «минимум равен»“The maximum equals,” “the minimum equals”Считай «все не больше $t$» и «все не больше $t-1$», ответ — разность; случаи не разбирайCount “everything is at most $t$” and “everything is at most $t-1$”; the answer is the difference, so do not split into cases
Спрашивают матожидание числа шагов, длины серии, номера попыткиThey ask for the expected number of steps, run length, or attempt numberХвостовая формула: опиши событие $\{X \ge k\}$ одной фразой и суммируй геометрическую прогрессиюUse the tail formula: describe $\{X \ge k\}$ in one sentence and sum a geometric progression
«Наудачу выбирается точка»“A point is chosen at random”Исходов бесконечно: переводи условие в неравенство, корень убирай возведением в квадрат, считай долю площади областиThere are infinitely many outcomes: turn the condition into an inequality, remove the root by squaring, and calculate the area fraction
В условии слово «ближайшая» — сторона, точка, вершинаThe statement says “nearest”—side, point, or vertexЭто несколько разных условий сразу: режь фигуру по симметрии, считай одну часть и умножайThese are several different conditions: cut by symmetry, calculate one part, and multiply
Аналитический ход не найден за 10 минутNo analytical route after 10 minutesОцени размер пространства: до нескольких миллионов — перебор с Fraction, дальше — динамика, непрерывный исход — симуляцияEstimate the outcome-space size: up to a few million, enumerate with Fraction; beyond that, use dynamic programming; for a continuous outcome, simulate
Считаешь число объектов длины $n$ с запретом на соседейYou are counting length-$n$ objects with an adjacency prohibitionДинамика по последнему символу: состояние, переход, база; маленький случай сверь рукамиUse dynamic programming by the last symbol: state, transition, base; check a small case by hand
Хочется взять локально лучший вариантYou want to take the locally best optionЖадность верна, только если проходит аргумент обмена; иначе проверь её перебором на маленьком набореGreedy is valid only with an exchange argument; otherwise test it by enumeration on a small set
Ответ получен симуляциейThe answer came from simulationВерны примерно три знака на миллионе испытаний; четвёртый сдавай только после аналитики или $10^8$ испытанийAbout three digits are reliable at a million trials; submit a fourth only after analysis or $10^8$ trials
эталонная задача

Максимум равен пяти: считаем не то, о чём спросилиThe maximum equals five: count what was not asked

RU

Условие. Кубик бросают 3 раза. Найти вероятность того, что максимальное выпавшее число равно 5.

Смотреть надо не на числа, а на порядок решений: та же последовательность закрывает разминку w1202, мост b1201 (там минимум вместо максимума) и финальную y1201, где бросков пять и разбор случаев уже невозможен.

Шаг 1. Тридцать секунд на тип и первый ход. Слова «максимум равен» — маркер. Первый ход называется вслух до всякой формулы: не разбирать случаи, а перейти к событию «все не больше $t$». Решение о том, что именно считать, принимается здесь, и оно дороже всей последующей арифметики.

Шаг 2. Проверить, что выбранное событие факторизуется. «Все три броска не больше 5» — это три независимых условия, по одному на бросок, поэтому вероятность есть произведение: $\P(\max \le 5) = (5/6)^3$. А событие «ровно один раз выпало 5, остальные меньше» на независимые условия не распадается — от него мы и уходим.

Шаг 3. Разность двух соседних хвостов. Событие «все не больше 4» целиком лежит внутри события «все не больше 5», поэтому вероятности вычитаются без всяких поправок:

$$\P(\max = 5) = \frac{5^3 - 4^3}{6^3} = \frac{125 - 64}{216} = \frac{61}{216} \approx 0.2824$$

Шаг 4. Оценка руками — до сверки, не после. Максимум трёх бросков тяготеет к большим значениям: $\P(\max = 6) = 1 - (5/6)^3 = 91/216 \approx 0.42$. Значит ответ для пятёрки обязан быть заметно меньше $0.42$, но много больше $1/216$. Число $0.28$ в эту вилку попадает — сверку можно продолжать.

Шаг 5. Машина как независимый второй путь. Пространство исходов — $6^3 = 216$, перебор мгновенный, и формула в нём не участвует:

import itertools
from fractions import Fraction as F
c = sum(1 for t in itertools.product(range(1, 7), repeat=3) if max(t) == 5)
print(c, F(c, 216))        # 61 61/216

Шаг 6. Проверка всей конструкции разом. Если приём верен, то вероятности $\P(\max = t) = (t^3 - (t-1)^3)/216$ обязаны в сумме дать единицу. Складываем по $t$ от 1 до 6: числители телескопически схлопываются в $6^3 - 0 = 216$, сумма равна 1. Одна строка — и проверен не ответ, а сам метод.

Алгоритм
  1. Увидел «максимум или минимум равен $t$» — не разбирай случаи: считай «все не больше $t$».
  2. Убедись, что событие распадается на условия по одному испытанию: тогда вероятность — степень.
  3. Ответ — разность двух соседних хвостов; для минимума то же с «все не меньше $t$».
  4. Оцени порядок ответа руками раньше, чем сверяешься: соседние хвосты дают вилку.
  5. Перебери пространство машиной, если оно меньше нескольких миллионов, — это второй путь.
EN

Problem. Roll a die 3 times. Find the probability that the largest number rolled is 5.

Focus not on the numbers but on the order of the solution: the same sequence closes warm-up w1202, bridge b1201 (minimum instead of maximum), and final y1201, where there are five rolls and casework is no longer practical.

Step 1. Thirty seconds for the type and first move. The words “the maximum equals” are the marker. Say the first move aloud before writing any formula: do not split into cases; switch to the event “everything is at most $t$.” The decision about what to count is made here, and it is more valuable than all the arithmetic that follows.

Step 2. Check that the chosen event factors. “All three rolls are at most 5” is three independent conditions, one per roll, so its probability is a product: $\P(\max \le 5) = (5/6)^3$. The event “5 appeared exactly once and all the others are smaller” does not split into independent conditions; that is why we leave it behind.

Step 3. Difference of two neighboring tails. “Everything is at most 4” lies entirely inside “everything is at most 5,” so subtract the probabilities without any correction:

$$\P(\max = 5) = \frac{5^3 - 4^3}{6^3} = \frac{125 - 64}{216} = \frac{61}{216} \approx 0.2824$$

Step 4. Estimate by hand before checking. The maximum of three rolls leans toward larger values: $\P(\max = 6) = 1 - (5/6)^3 = 91/216 \approx 0.42$. The answer for five must be noticeably less than $0.42$ but much greater than $1/216$. The number $0.28$ falls in that interval, so continue checking.

Step 5. The machine as an independent second route. The outcome space has $6^3 = 216$ elements, so enumeration is instant, and the formula does not participate:

import itertools
from fractions import Fraction as F
c = sum(1 for t in itertools.product(range(1, 7), repeat=3) if max(t) == 5)
print(c, F(c, 216))        # 61 61/216

Step 6. Check the entire construction at once. If the technique is correct, the probabilities $\P(\max = t) = (t^3 - (t-1)^3)/216$ must add up to one. Sum over $t$ from 1 to 6: the numerators telescope to $6^3 - 0 = 216$, so the sum is 1. One line checks the method, not just the answer.

Algorithm
  1. See “the maximum or minimum equals $t$”? Do not split into cases; count “everything is at most $t$.”
  2. Make sure the event splits into one condition per trial; then its probability is a power.
  3. The answer is the difference of two neighboring tails; for a minimum, mirror it with “everything is at least $t$.”
  4. Estimate the answer’s order by hand before checking; neighboring tails give you a bracket.
  5. Enumerate with a machine if the space has fewer than a few million outcomes; this is the second route.

Дополнительные материалы

Другие объяснения и материалы по теме. Используй их, если основного урока недостаточно.

интерактивVisuAlgo · дерево рекурсии и ДПVisuAlgo · recursion and dynamic programming tree EN
Отдельного модуля про динамику у VisuAlgo нет, анимация живёт здесь: видно, как дерево рекурсии превращается в DAG, когда подзадачи повторяются. Это и есть момент, где включается ДПVisuAlgo has no separate dynamic-programming module; the animation lives here: watch a recursion tree become a DAG when subproblems repeat. That is the moment dynamic programming switches on
видеоErrichto · Dynamic Programming lecture #1Errichto · Dynamic Programming lecture #1 EN
Разбор ДП от гроссмейстера Codeforces: от Фибоначчи и «рекурсия против итерации» до рюкзака. Смотреть, если динамика по состояниям сегодня не пошлаA Codeforces grandmaster’s DP walkthrough: from Fibonacci and “recursion versus iteration” to knapsack. Watch if state-based dynamic programming does not click today
текстPython · itertoolsPython · itertools EN
product, permutations, combinations — тот самый точный перебор пространства исходов в две строки. Хватит первой таблицы, раздел Recipes внизу можно не читатьproduct, permutations, combinations—the exact outcome-space enumeration you can write in two lines. The first table is enough; you can skip the Recipes section below
текстSympy · вводный туториалSympy · introductory tutorial EN
Полчаса чтения — и sympy становится рабочим инструментом, а не набором заклинанийHalf an hour of reading turns sympy into a working tool rather than a bag of incantations
текстNumPy · quickstartNumPy · quickstart EN
То же для numpy. Особенно раздел про генерацию случайных чисел: он нужен для симуляцийThe same for NumPy. Pay special attention to random-number generation: you need it for simulations
как работать сегодня
RU

Задачи дня выстроены в лестницу из четырёх ступеней, и порядок в ней важнее обычного: восемь задач ступени YMLS идут вперемешку, из шести разных тем, и без разогретого распознавания эта смесь превращается в лотерею.

Полный объём — 17 задач. Всё, что есть на странице, включая задачу ступени ШАД. Это план на день, который идёт хорошо: сорок минут на разминку и ступени 1–2, и час двадцать на ступени 3–4.

Минимум — 10 задач. b1201, b1202, b1203, b1204, b1205, y1201, y1202, y1203, y1204, y1208 — все четыре моста ступени 3, две задачи ступени 2 (динамика b1205 и округление y1208) и четыре задачи ступени 4. В минимуме представлены все четыре микронавыка, поэтому день, урезанный до десяти задач, остаётся полноценным.

Обязательные — 4 задачи. b1201, b1202, b1203, b1204 — ровно вся ступень 3, и каждая из них мост к своему финалу:

  • b1201 ведёт к y1201: тот же приём зеркально, минимум вместо максимума и пять бросков вместо четырёх.
  • b1202 ведёт к y1202: та же начальная серия, но бросков бесконечно много, и конечная сумма становится бесконечной.
  • b1203 ведёт к мини-тесту y1204: в мосте сторона фиксирована, в мини-тесте — ближайшая, и это единственное отличие.
  • b1204 ведёт к y1203: те же беспорядки, но перестановок 720 вместо 24, и руками их уже не выписать.

Если день сорвался и осталось сорок минут, делаются эти четыре и мини-тест.

Четыре лестницы, по которым день идёт. Каждая — один приём на трёх ступенях подряд, и пропуск нижней ступени ломает верхнюю:

  • Хвост для матожидания: w1201 (три хвоста устно) → b1202 (пять, конечная прогрессия) → y1202 (бесконечная).
  • Хвост для экстремума: w1202 (счёт исходов) → b1201 (минимум, четыре броска) → y1201 (максимум, пять бросков).
  • Область: w1203 (круг) → b1203 (парабола, сторона фиксирована) → y1204 (парабола, сторона ближайшая).
  • Машина: b1205 (динамика, 4096 строк) → b1204 (перебор 24 перестановок) → y1203 (перебор 720).

Дриль распознавания. Он важнее любой отдельной задачи. Открой все восемь задач ступени YMLS подряд, не решая, и на каждую потрать ровно тридцать секунд: вслух тема и первый ход, на бумагу — одна строка. Потом сверь: четыре из них разобраны в блоке @final, ещё четыре (y1205–y1208) обязаны закрыться одной строкой из блока «Мост». Метрика дня — доля верно опознанных типов, и она важнее доли решённых.

Двойной счёт. Каждую задачу, где пространство исходов конечно (w1201, w1202, b1201, b1202, b1204, y1201, y1203), закрой дважды: формулой и перебором. Каждую геометрическую (w1203, b1203, y1204) — площадью и симуляцией, помня, что симуляция отвечает за три знака, а не за четыре. Совпадение подтверждает, что метод понят, а не угадан.

Разминка и задачи-узнавания

w1201–w1203 устные, по минуте на задачу, сразу после урока: каждая — простейшая версия одного из приёмов, на которых стоят финалы. В счёт минимума они не входят, но не выбрасываются.

y1205, y1206, y1207 — задачи ступени YMLS по формату и ступени 1–2 по существу: гамма-интеграл, правило произведения и расстояние до плоскости берутся прямо из блока «Мост», и на все три вместе уходит меньше пяти минут. Моста у них нет и не нужно: вести к ним нечего, узнавание и есть весь навык. Именно поэтому они не в минимуме — но делаются всегда, потому что на экзамене это самые дешёвые баллы.

Из этой четвёрки в минимум взята одна y1208: она единственная, где балл теряют, не ошибившись в счёте, — там решает направление округления.

s1201 — задача ступени ШАД, выше уровня экзамена, в минимум не входит. Берётся последней и только если день идёт по полному объёму.

Формат ответа

Все числовые ответы дня, кроме целых, вводятся с четырьмя знаками после запятой, точка как разделитель. Округление — только в самом конце, из точной дроби.

EN

Today’s problems form a four-level ladder, and the order matters more than usual: eight YMLS problems are interleaved across six topics, and without warmed-up recognition the mixture becomes a lottery.

Full volume: 17 problems. Everything on the page, including the SHAD-level problem. This is the plan for a good day: forty minutes for warm-up and levels 1–2, and an hour and twenty minutes for levels 3–4.

Minimum: 10 problems. b1201, b1202, b1203, b1204, b1205, y1201, y1202, y1203, y1204, y1208—all four level-3 bridges, two level-2 problems (dynamic programming b1205 and rounding y1208), and four level-4 problems. All four micro-skills are represented, so even a ten-problem day remains complete.

Mandatory: 4 problems. b1201, b1202, b1203, b1204—the entire level 3, and each is a bridge to its final:

  • b1201 leads to y1201: the same technique mirrored, minimum instead of maximum and five rolls instead of four.
  • b1202 leads to y1202: the same initial run, but infinitely many rolls, so the final sum becomes infinite.
  • b1203 leads to mini-test y1204: the bridge fixes the side; the mini-test uses the nearest side, and that is the only difference.
  • b1204 leads to y1203: the same derangements, but 720 permutations instead of 24, which can no longer be written out by hand.

If the day falls apart and forty minutes remain, do these four and the mini-test.

The four ladders the day follows. Each is one technique across three consecutive levels, and skipping the bottom level breaks the top:

  • Tail for expectation: w1201 (say three tails aloud) → b1202 (five, finite progression) → y1202 (infinite).
  • Tail for an extreme: w1202 (count outcomes) → b1201 (minimum, four rolls) → y1201 (maximum, five rolls).
  • Region: w1203 (circle) → b1203 (parabola, fixed side) → y1204 (parabola, nearest side).
  • Machine: b1205 (dynamic programming, 4096 strings) → b1204 (24 permutations) → y1203 (720 permutations).

Recognition drill. It matters more than any single problem. Open all eight YMLS problems in sequence, without solving, and spend exactly thirty seconds on each: say the topic aloud and write one line on paper. Then check yourself: four are explained in @final; the other four (y1205–y1208) must close with one line from the “Bridge” block. Today’s metric is the fraction of types recognized correctly, more than the fraction solved.

Double calculation. For every problem with a finite outcome space (w1201, w1202, b1201, b1202, b1204, y1201, y1203), solve it twice: by formula and by enumeration. For each geometric problem (w1203, b1203, y1204), solve by area and by simulation, remembering that simulation supports three digits, not four. Agreement confirms that the method is understood rather than guessed.

About the warm-up and recognition problems

w1201–w1203 are oral, one minute per problem, immediately after the lesson: each is the simplest version of a technique used by the finals. They do not count toward the minimum, but do not discard them.

y1205, y1206, y1207 are YMLS-level in format but level 1–2 in substance: the gamma integral, product rule, and distance to a plane come directly from “Bridge,” and all three together take less than five minutes. They have no bridge, and do not need one: recognition is the entire skill. That is why they are not in the minimum—but always do them, because on the exam they are the cheapest points.

Of those four, y1208 is included in the minimum: it is the only one where you can lose the point without making an arithmetic mistake; the rounding direction decides it.

s1201 is the SHAD-level problem, above the exam level and outside the minimum. Take it last, and only if the day is going according to the full-volume plan.

Answer format

Enter every numerical answer today, except integers, with four digits after the decimal point, using a period as the separator. Round only at the very end, from the exact fraction.

17
полный объём
10
минимум
4
обязательные

Полный объём — все задачи ниже. Минимум — если день сорвался и часа осталось два. Обязательные — мосты к финальной задаче, они не пропускаются никогда.

Разминка

решено 0 из 3

Устно, за полминуты. Проверяет, что определение понято, а не выучено.

W1201Разминкаступень 1Случайные величиныразминка
RU

Честную монету бросают до первого орла, но не более трёх раз: как только выпал орёл, броски прекращаются. Пусть $X$ — число сделанных бросков; если орла не выпало ни разу, то $X = 3$. Найдите $\E X$. Ответ округлите до четырёх знаков после запятой.

EN

A fair coin is tossed until the first head appears, but at most three times. Tossing stops as soon as a head appears. Let $X$ be the number of tosses performed; if no head appears, then $X=3$. Find $\E X$. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Распределение $X$ выписывать не надо. Событие «$X \ge k$» описывается одной фразой: первые $k-1$ бросков дали решку.

EN

There is no need to write down the distribution of $X$. The event “$X \ge k$” has a one-sentence description: the first $k-1$ tosses were tails.

Решение / Solution
RU

Хвостовая формула из блока «Мост»: $\E X = \sum_{k\ge1}\P(X \ge k)$. Сумма обрывается на $k = 3$, потому что больше трёх бросков не бывает.

Событие $\{X \ge k\}$ означает ровно одно: первые $k-1$ бросков дали решку (про остальные броски требовать нечего). Отсюда $\P(X \ge 1) = 1$, $\P(X \ge 2) = \frac12$, $\P(X \ge 3) = \frac14$, и

$$\E X = 1 + \frac12 + \frac14 = \frac74 = 1.75$$

Второй путь, для сверки: $X = 1$ с вероятностью $\frac12$, $X = 2$ с вероятностью $\frac14$, а $X = 3$ с вероятностью $\frac14$ (сюда попадают и «решка, решка, орёл», и «решка, решка, решка»), откуда $\E X = \frac12 + \frac24 + \frac34 = \frac74$. Числа сошлись, а хвостовая запись короче.

Куда это ведёт

Хвостов здесь три, и все они видны глазами. В мосте b1202 их будет пять, а в финальной y1202 — бесконечно много, и конечная сумма превратится в геометрическую прогрессию. Приём один и тот же на всех трёх ступенях: описать словами событие «$X \ge k$» и не трогать $\P(X = k)$.

EN

Use the tail-sum formula from the Bridge section: $\E X = \sum_{k\ge1}\P(X \ge k)$. The sum stops at $k=3$ because there can be no more than three tosses.

The event $\{X \ge k\}$ means exactly that the first $k-1$ tosses were tails; no condition is needed on the later tosses. Thus $\P(X \ge 1)=1$, $\P(X \ge 2)=\frac12$, and $\P(X \ge 3)=\frac14$, so

$$\E X = 1 + \frac12 + \frac14 = \frac74 = 1.75$$

For an independent check, $X=1$ with probability $\frac12$, $X=2$ with probability $\frac14$, and $X=3$ with probability $\frac14$. The last event includes both tails–tails–heads and tails–tails–tails. Hence $\E X = \frac12 + \frac24 + \frac34 = \frac74$. The results agree, while the tail-sum calculation is shorter.

Where this leads

There are three tail probabilities here, all visible immediately. Bridge problem b1202 has five, while final problem y1202 has infinitely many and turns the finite sum into a geometric series. The technique is identical at all three levels: describe the event “$X \ge k$” in words and avoid $\P(X=k)$.

уверенность1 — угадал, 5 — уверен полностью
W1202Разминкаступень 1Вероятностьразминка
RU

Кубик бросают два раза. Исход — упорядоченная пара выпавших чисел, всего исходов 36 и все они равновозможны. Сколько исходов имеют максимальное выпавшее число, равное ровно 4?

EN

A die is rolled twice. An outcome is an ordered pair of results, so there are 36 equally likely outcomes. How many outcomes have maximum value exactly 4?

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Считай не «ровно 4», а «оба не больше 4»: такое условие проверяется для каждого броска по отдельности.

EN

Instead of counting “exactly 4,” count outcomes in which both values are at most 4. This condition can be checked separately for each roll.

Решение / Solution
RU

«Оба числа не больше 4» — четыре варианта на каждом броске, всего $4\cdot4 = 16$ исходов. «Оба не больше 3» — $3\cdot3 = 9$ исходов, и все они лежат внутри предыдущих. Максимум равен ровно 4 там, где все числа не больше 4, но не все не больше 3:

$$16 - 9 = 7$$

Прямой перечень подтверждает: $(4,1)$, $(4,2)$, $(4,3)$, $(4,4)$, $(1,4)$, $(2,4)$, $(3,4)$ — семь пар.

Куда это ведёт

На двух кубиках перечислить ещё можно. В финальной y1201 бросков пять, исходов 7776, и перечислять нечего — а разность двух «не больше» пишется так же в одну строку.

EN

There are four possible values on each roll when both results must be at most 4, giving $4\cdot4=16$ outcomes. There are $3\cdot3=9$ outcomes in which both are at most 3, all contained in the first set. The maximum equals exactly 4 when both values are at most 4 but not both are at most 3:

$$16 - 9 = 7$$

Direct enumeration confirms the result: $(4,1)$, $(4,2)$, $(4,3)$, $(4,4)$, $(1,4)$, $(2,4)$, and $(3,4)$, seven pairs in total.

Where this leads

Two dice can still be enumerated. Final problem y1201 uses five rolls and has 7776 outcomes, making enumeration impractical, yet the difference of two “at most” counts is still one line.

уверенность1 — угадал, 5 — уверен полностью
W1203Разминкаступень 1Вероятностьразминка
RU

Точка бросается наудачу (равномерно) в квадрат со стороной 1. Найдите вероятность того, что расстояние от неё до центра квадрата меньше 0.5. Ответ округлите до четырёх знаков после запятой.

EN

A point is chosen uniformly at random from a square of side length 1. Find the probability that its distance from the center of the square is less than 0.5. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Множество таких точек — круг. Вероятность равна доле площади.

EN

The set of such points is a disk. The probability is the corresponding area fraction.

Решение / Solution
RU

Условие задаёт круг радиуса $r = 0.5$ с центром в центре квадрата. Этот круг целиком лежит внутри квадрата, касаясь всех четырёх сторон, поэтому благоприятная площадь — это вся площадь круга, а площадь всей фигуры равна 1:

$$\P = \frac{\pi r^{2}}{1} = \frac{\pi}{4} \approx 0.7854$$
Куда это ведёт

Приём во всех геометрических задачах один и тот же: условие, область, доля площади. Меняется только граница. Здесь это окружность, в мосте b1203 и в мини-тесте y1204 — парабола, и появляется она ровно потому, что расстояние меряется не до точки, а до стороны.

EN

The condition defines a disk of radius $r=0.5$ centered at the center of the square. The disk lies entirely inside the square and is tangent to all four sides. Thus the favorable area is the area of the entire disk, while the total area is 1:

$$\P = \frac{\pi r^{2}}{1} = \frac{\pi}{4} \approx 0.7854$$
Where this leads

Every geometric-probability problem uses the same sequence: translate the condition into a region, then take an area fraction. Only the boundary changes. Here it is a circle; in bridge problem b1203 and mini-test y1204, it is a parabola because distance is measured to a side rather than to a point.

уверенность1 — угадал, 5 — уверен полностью

База

решено 0 из 5

Чистая техника без сюрпризов. Здесь нарабатывается автоматизм.

B1201Базаступень 3обязательнаяВероятностьавторская · мост к y1201
RU

Кубик бросают 4 раза. Найдите вероятность того, что минимальное выпавшее число равно 2. Ответ округлите до четырёх знаков после запятой.

EN

A die is rolled 4 times. Find the probability that the minimum result is 2. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Зеркальная версия приёма из разминки: считай «все броски не меньше $t$».

EN

Use the mirror image of the warm-up technique: count outcomes in which every roll is at least $t$.

Решение / Solution
RU

Событие «все четыре броска не меньше 2» — это условие на каждый бросок по отдельности, подходящих значений 5 из 6, и броски независимы:

$$\P(\min \ge 2) = \left(\frac56\right)^{4}$$

Событие «все не меньше 3» вложено в предыдущее, $\P(\min \ge 3) = \left(\frac46\right)^{4}$. Минимум равен ровно 2 там, где все броски не меньше 2, но не все не меньше 3:

$$\P(\min = 2) = \frac{5^{4} - 4^{4}}{6^{4}} = \frac{625 - 256}{1296} = \frac{369}{1296} = \frac{41}{144} \approx 0.2847$$
Проверка, которая ловит путаницу «больше/меньше»

Сложи ответы для всех $t$ от 1 до 6: $\P(\min = t) = \big((7-t)^{4} - (6-t)^{4}\big)/6^{4}$, и числители телескопически схлопываются в $6^{4}$, то есть сумма равна 1. Если единицы не вышло — где-то «не меньше» подменилось на «не больше».

Второй путь: перебор всех $6^{4} = 1296$ исходов даёт те же 369 благоприятных.

EN

The event that all four rolls are at least 2 imposes an independent condition on each roll. Five of the six values are allowed, and the rolls are independent:

$$\P(\min \ge 2) = \left(\frac56\right)^{4}$$

The event that every roll is at least 3 is contained in the previous event, and $\P(\min \ge 3) = \left(\frac46\right)^{4}$. The minimum equals exactly 2 when all rolls are at least 2 but not all are at least 3:

$$\P(\min = 2) = \frac{5^{4} - 4^{4}}{6^{4}} = \frac{625 - 256}{1296} = \frac{369}{1296} = \frac{41}{144} \approx 0.2847$$
A check that catches reversed inequalities

Sum the answers over $t=1,\ldots,6$: $\P(\min=t)=\big((7-t)^4-(6-t)^4\big)/6^4$. The numerators telescope to $6^4$, so the sum is 1. If it is not, an “at least” was probably replaced by an “at most” somewhere.

A second method enumerates all $6^4=1296$ outcomes and also finds 369 favorable ones.

уверенность1 — угадал, 5 — уверен полностью
B1202Базаступень 3обязательнаяСлучайные величиныавторская · мост к y1202
RU

Честную монету бросают 5 раз. Начальной серией называется максимальный начальный участок, на котором все результаты одинаковы: для ООРОО длина серии равна 2, для РРРРР — 5. Найдите математическое ожидание длины начальной серии. Ответ округлите до четырёх знаков после запятой.

EN

A fair coin is tossed 5 times. The initial run is the longest initial segment in which all outcomes are the same: for HHTHH its length is 2, and for TTTTT its length is 5. Find the expected length of the initial run. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Хвостовая формула. Событие «серия не короче $k$» описывается одной фразой.

EN

Use the tail-sum formula. The event “the run has length at least $k$” has a one-sentence description.

Решение / Solution
RU

Серия не короче $k$ тогда и только тогда, когда первые $k$ бросков одинаковы: первый задаёт результат, каждый следующий обязан его повторить. При $k > 5$ событие невозможно, потому что бросков всего пять:

$$\P(L \ge k) = \left(\frac12\right)^{k-1}, \qquad k = 1,\ldots,5$$

По хвостовой формуле складываем эти пять чисел — это конечная геометрическая прогрессия:

$$\E L = \sum_{k=1}^{5}\left(\frac12\right)^{k-1} = \frac{1 - (1/2)^{5}}{1 - 1/2} = 2\left(1 - \frac1{32}\right) = \frac{31}{16} = 1.9375$$

Второй путь — перебрать все $2^{5} = 32$ последовательности и сложить длины начальных серий: сумма равна 62, и $62/32 = 31/16$. Ровно то же число, полученное без единой формулы.

Мост к финалу

Ступенью ниже, в разминке w1201, хвостов было три и складывались они устно; здесь их пять и они уже складываются формулой конечной прогрессии.

В y1202 монету бросают неограниченно долго, и меняется ровно одно: обрыва суммы на $k = 5$ больше нет. Конечная прогрессия становится бесконечной, и вместо $2\left(1 - \frac1{32}\right)$ выходит ровно 2. Приём тот же, и разница между ответами меньше семи сотых — почти всё матожидание набирается на первых пяти бросках.

EN

The run has length at least $k$ if and only if the first $k$ tosses are equal. The first toss determines the outcome, and each later toss must match it. The event is impossible for $k>5$ because there are only five tosses:

$$\P(L \ge k) = \left(\frac12\right)^{k-1}, \qquad k = 1,\ldots,5$$

By the tail-sum formula, add these five values. This is a finite geometric series:

$$\E L = \sum_{k=1}^{5}\left(\frac12\right)^{k-1} = \frac{1 - (1/2)^{5}}{1 - 1/2} = 2\left(1 - \frac1{32}\right) = \frac{31}{16} = 1.9375$$

As a second method, enumerate all $2^5=32$ sequences and add their initial-run lengths. The total is 62, and $62/32=31/16$, the same value obtained without a formula.

Bridge to the final problem

One level earlier, warm-up problem w1201 had three tail probabilities that could be added mentally. Here there are five, requiring the finite geometric-series formula.

In y1202, the coin is tossed indefinitely, and exactly one thing changes: the sum no longer stops at $k=5$. The finite geometric series becomes infinite, producing exactly 2 rather than $2\left(1-\frac1{32}\right)$. The method is the same, and the answers differ by less than seven hundredths: almost all of the expectation comes from the first five tosses.

уверенность1 — угадал, 5 — уверен полностью
B1203Базаступень 3обязательнаяВероятностьавторская · мост к мини-тесту
RU

Точка бросается наудачу (равномерно) в квадрат со стороной 1. Найдите вероятность того, что она окажется ближе к центру квадрата, чем к его нижней стороне (расстояние до стороны меряется по перпендикуляру). Ответ округлите до четырёх знаков после запятой.

EN

A point is chosen uniformly at random from a square of side length 1. Find the probability that it is closer to the center of the square than to its bottom side, where distance to a side is measured perpendicularly. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Введи координаты, выпиши оба расстояния и возведи неравенство в квадрат: квадраты $y$ сократятся, и граница окажется знакомой кривой.

EN

Introduce coordinates, write both distances, and square the inequality. The $y^2$ terms cancel, leaving a familiar curve as the boundary.

Решение / Solution
RU

Координаты: квадрат $[0,1]\times[0,1]$, центр $\left(\frac12,\frac12\right)$, нижняя сторона лежит на оси абсцисс. Для точки $(x,y)$ внутри квадрата расстояние до нижней стороны равно $y$, а до центра — $\sqrt{\left(x-\frac12\right)^{2} + \left(y-\frac12\right)^{2}}$. Обе части неотрицательны, поэтому неравенство можно возвести в квадрат:

$$\left(x-\tfrac12\right)^{2} + \left(y-\tfrac12\right)^{2} < y^{2}$$

Раскрываем скобку при $y$: она даёт $y^{2} - y + \frac14$, квадраты $y$ сокращаются, и остаётся

$$y > \left(x - \tfrac12\right)^{2} + \frac14$$

Граница — парабола. Её наибольшее значение на отрезке $[0,1]$ достигается в концах и равно $\frac14 + \frac14 = \frac12 < 1$, значит область не обрезается верхней стороной и считается одним интегралом:

$$\P = \int_0^{1}\left(1 - \left(x-\tfrac12\right)^{2} - \frac14\right)dx = \frac34 - \int_0^{1}\left(x-\tfrac12\right)^{2}dx = \frac34 - \frac1{12} = \frac23 \approx 0.6667$$

Последний интеграл берётся заменой $u = x - \frac12$: $\int_{-1/2}^{1/2}u^{2}\,du = \frac{u^{3}}{3}\Big|_{-1/2}^{1/2} = \frac1{12}$.

Мост к мини-тесту

В y1204 сторона не фиксирована, а ближайшая, и это добавляет ровно один шаг: квадрат режется диагоналями на четыре треугольника, в нижнем ближайшая сторона — как раз нижняя, парабола та же самая, надо лишь ограничить интегрирование этим треугольником и умножить результат на 4.

Симуляция здесь обязательна и занимает десять секунд, но знать надо, что она даёт: два миллиона точек воспроизводят $0.666$ — три знака, дальше начинается шум: стандартное отклонение доли равно $\sqrt{p(1-p)/N} \approx 3\cdot10^{-4}$, то есть ошибка живёт уже в четвёртом знаке. Четвёртый знак $0.6667$ даёт только интеграл. Симуляция подтверждает не арифметику, а то, что область выписана правильно.

EN

Use the square $[0,1]\times[0,1]$, whose center is $\left(\frac12,\frac12\right)$ and whose bottom side lies on the $x$-axis. For a point $(x,y)$ inside the square, the distance to the bottom side is $y$, whereas the distance to the center is $\sqrt{\left(x-\frac12\right)^2+\left(y-\frac12\right)^2}$. Both sides are nonnegative, so the inequality may be squared:

$$\left(x-\tfrac12\right)^{2} + \left(y-\tfrac12\right)^{2} < y^{2}$$

Expanding the term involving $y$ gives $y^2-y+\frac14$. The $y^2$ terms cancel, leaving

$$y > \left(x - \tfrac12\right)^{2} + \frac14$$

The boundary is a parabola. Its maximum on $[0,1]$ occurs at the endpoints and equals $\frac14+\frac14=\frac12<1$, so the region is not truncated by the top side and is computed with a single integral:

$$\P = \int_0^{1}\left(1 - \left(x-\tfrac12\right)^{2} - \frac14\right)dx = \frac34 - \int_0^{1}\left(x-\tfrac12\right)^{2}dx = \frac34 - \frac1{12} = \frac23 \approx 0.6667$$

For the final integral, substitute $u=x-\frac12$: $\int_{-1/2}^{1/2}u^{2}\,du = \frac{u^{3}}{3}\Big|_{-1/2}^{1/2} = \frac1{12}$.

Bridge to the mini-test

In y1204, the side is not fixed but is the nearest side. This adds exactly one step: divide the square into four triangles using its diagonals. In the bottom triangle, the nearest side is precisely the bottom side. The parabola is the same; restrict the integral to that triangle and multiply by 4.

A simulation is essential as a check and takes ten seconds, but understand its accuracy: two million points reproduce $0.666$ to three decimal places, after which noise begins. The standard deviation of the proportion is $\sqrt{p(1-p)/N}\approx3\cdot10^{-4}$, so the error already affects the fourth decimal place. Only the integral gives the fourth digit in $0.6667$. The simulation checks that the region was specified correctly, not the final arithmetic.

уверенность1 — угадал, 5 — уверен полностью
B1204Базаступень 3обязательнаяКомбинаторикаавторская · мост к y1203
RU

Четыре пронумерованных письма раскладывают по четырём пронумерованным конвертам, по одному письму в конверт. Раскладка — это перестановка, всего их $4! = 24$.

Сколько раскладок таких, что ни одно письмо не попало в свой конверт? В ответе укажите число раскладок, а не вероятность.

EN

Four numbered letters are placed into four numbered envelopes, one letter per envelope. An assignment is a permutation, so there are $4!=24$ assignments in total.

How many assignments place no letter into its matching envelope? Give the number of assignments, not a probability.

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. Одно целое $n$ ($1 \le n \le 8$) — число писем и конвертов. Вывод. Количество раскладок, где ни одно письмо не попало в свой конверт.

EN

Input. One integer $n$ ($1 \le n \le 8$), the number of letters and envelopes. Output. The number of arrangements in which no letter is in its own envelope.

ВыводOutput
Подсказка / Hint
RU

Прежде чем вспоминать формулу, назови вслух размер пространства исходов. Двадцать четыре перестановки — это тот случай, когда перебор дешевле любой формулы.

EN

Before recalling a formula, state the size of the sample space. With only twenty-four permutations, exhaustive enumeration is cheaper than any formula.

Решение / Solution
RU

Первый ход — оценка размера, а не формула. Раскладка есть перестановка четырёх элементов, всего их $4! = 24$. Двадцать четыре исхода перебираются мгновенно, и никакой комбинаторики для ответа не требуется:

import itertools
c = sum(1 for p in itertools.permutations(range(4)) if all(p[i] != i for i in range(4)))
print(c)      # 9

Здесь перебор доводится до конца и руками. Записывая раскладку строкой «куда легло письмо 1, письмо 2, письмо 3, письмо 4», получаем все девять:

$$2143,\ 2341,\ 2413,\ 3142,\ 3412,\ 3421,\ 4123,\ 4312,\ 4321$$

Сверка формулой. Беспорядки из блока «Мост»:

$$D_4 = 4!\left(1 - 1 + \frac12 - \frac16 + \frac1{24}\right) = 24 - 24 + 12 - 4 + 1 = 9$$

Два независимых пути дали одно число — значит и формула вспомнена верно, и перебор написан без ошибки в условии p[i] != i.

Мост к финалу

В y1203 элементов шесть, перестановок $6! = 720$ — по меркам машины та же мелочь, и первый ход не меняется: назвать размер пространства вслух, потом решать. Меняется одно: 720 раскладок руками уже не выпишешь, и остаётся либо формула, либо машина. Именно поэтому перебор стоит написать здесь, на 24 исходах, где ответ проверяем глазами.

EN

First estimate the size, rather than reaching for a formula. An assignment is a permutation of four elements, so there are $4!=24$ possibilities. They can be enumerated immediately, and no combinatorial formula is needed to obtain the answer:

import itertools
c = sum(1 for p in itertools.permutations(range(4)) if all(p[i] != i for i in range(4)))
print(c)      # 9

The enumeration can also be completed by hand. Writing an assignment as “the envelope receiving letter 1, letter 2, letter 3, letter 4,” the nine possibilities are

$$2143,\ 2341,\ 2413,\ 3142,\ 3412,\ 3421,\ 4123,\ 4312,\ 4321$$

Formula check. The derangement formula from the Bridge section gives

$$D_4 = 4!\left(1 - 1 + \frac12 - \frac16 + \frac1{24}\right) = 24 - 24 + 12 - 4 + 1 = 9$$

Two independent methods give the same value, confirming both the formula and the condition p[i] != i used in the enumeration.

Bridge to the final problem

Problem y1203 has six elements and $6!=720$ permutations, still tiny for a computer. The first move does not change: state the sample-space size before choosing a method. The difference is that 720 assignments are too many to list by hand, leaving either the formula or a program. This is why the enumeration is worth writing here, for 24 outcomes whose result can be inspected directly.

уверенность1 — угадал, 5 — уверен полностью
B1205Базаступень 2минимумАлгоритмыавторская · ДП на строках
RU

Сколько существует двоичных строк длины 12, в которых нет двух единиц подряд?

EN

How many binary strings of length 12 contain no two consecutive ones?

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. Одно целое $n$ ($1 \le n \le 90$). Вывод. Количество двоичных строк длины $n$ без двух единиц подряд (число большое — Python хранит его точно).

EN

Input. One integer $n$ ($1 \le n \le 90$). Output. The number of binary strings of length $n$ with no two adjacent ones (a big number, which Python stores exactly).

ВыводOutput
Подсказка / Hint
RU

Динамика по последнему символу. Получится знакомая последовательность.

EN

Use dynamic programming based on the final character. A familiar sequence will appear.

Решение / Solution
RU

Состояние: $f(n)$ — число подходящих строк длины $n$.

Переход. Строка либо заканчивается нулём — тогда её начало это любая подходящая строка длины $n-1$; либо единицей — тогда перед единицей обязан стоять ноль, а до него любая подходящая строка длины $n-2$:

$$f(n) = f(n-1) + f(n-2), \qquad f(1) = 2,\ f(2) = 3$$

База проверяется руками: строк длины 1 две (0 и 1), длины 2 три (00, 01, 10). Дальше идут числа Фибоначчи: $2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, \mathbf{377}$.

Ответ: 377.

Второй, независимый путь

Строк ровно с $k$ единицами, среди которых нет соседних, ровно $\binom{13-k}{k}$ (правило «никакие два не рядом» из блока «Мост»). Сумма:

$$\sum_{k=0}^{6}\binom{13-k}{k} = 1 + 12 + 55 + 120 + 126 + 56 + 7 = 377$$

И третий путь: перебор всех $2^{12} = 4096$ строк, четыре строки кода. Три независимые дороги к одному числу — то, чем сегодня закрывается каждая задача, где это стоит меньше минуты.

Здесь перебор — запасной путь, а динамика основной. В мосте b1204 они поменяются местами: пространство исходов там 24 перестановки, и перебор станет первым ходом.

EN

State: let $f(n)$ be the number of valid strings of length $n$.

Transition. A string either ends in zero, preceded by any valid string of length $n-1$, or ends in one. In the second case, the one must be preceded by zero, which may itself be preceded by any valid string of length $n-2$:

$$f(n) = f(n-1) + f(n-2), \qquad f(1) = 2,\ f(2) = 3$$

Base cases are checked directly: there are two strings of length 1, 0 and 1, and three valid strings of length 2, 00, 01, and 10. The Fibonacci sequence then appears: $2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, \mathbf{377}$.

Answer: 377.

A second, independent method

The number of strings with exactly $k$ nonadjacent ones is $\binom{13-k}{k}$, by the “no two adjacent” rule from the Bridge section. Therefore

$$\sum_{k=0}^{6}\binom{13-k}{k} = 1 + 12 + 55 + 120 + 126 + 56 + 7 = 377$$

A third method enumerates all $2^{12}=4096$ strings in four lines of code. Three independent routes to the same answer are worthwhile whenever each takes less than a minute.

Here exhaustive search is the fallback and dynamic programming is the primary method. In bridge problem b1204, their roles are reversed: its sample space contains only 24 permutations, so enumeration is the first approach.

уверенность1 — угадал, 5 — уверен полностью

Уровень YMLS

решено 0 из 7

Целевая сложность вступительного экзамена. Ответ — число.

Y1201Уровень YMLSступень 4минимумВероятностьсмешанный набор
RU

Кубик бросают 5 раз. Найдите вероятность того, что максимальное выпавшее число равно 4. Ответ округлите до четырёх знаков после запятой.

EN

A die is rolled 5 times. Find the probability that the maximum result is 4. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

«Максимум равен 4» — это «все не больше 4» минус «все не больше 3».

EN

“The maximum is 4” means “all results are at most 4” minus “all results are at most 3.”

Решение / Solution
RU$$\P(\max \le 4) = \left(\frac46\right)^{5}, \qquad \P(\max \le 3) = \left(\frac36\right)^{5}$$

Второе событие целиком вложено в первое, поэтому вероятности вычитаются без поправок:

$$\P(\max = 4) = \frac{4^{5} - 3^{5}}{6^{5}} = \frac{1024 - 243}{7776} = \frac{781}{7776} \approx 0.1004$$
Универсальный приём для максимума и минимума

Сначала считай «не больше $t$»: это условие на каждый бросок по отдельности, поэтому оно факторизуется. Потом бери разность соседних значений. Прямой подсчёт «ровно максимум 4» потребовал бы разбора случаев по числу четвёрок.

Второй путь — перебор всех $6^{5} = 7776$ исходов: благоприятных ровно 781. Он проверяет не арифметику, а сам приём, и стоит тридцать секунд.

EN$$\P(\max \le 4) = \left(\frac46\right)^{5}, \qquad \P(\max \le 3) = \left(\frac36\right)^{5}$$

The second event is entirely contained in the first, so their probabilities can be subtracted directly:

$$\P(\max = 4) = \frac{4^{5} - 3^{5}}{6^{5}} = \frac{1024 - 243}{7776} = \frac{781}{7776} \approx 0.1004$$
A general technique for maxima and minima

First count “at most $t$.” This is a separate condition on each roll, so its probability factors. Then take the difference of adjacent values. Counting “maximum exactly 4” directly would require separate cases according to the number of fours.

A second method enumerates all $6^5=7776$ outcomes and finds exactly 781 favorable ones. It takes thirty seconds and checks the technique itself, not merely the arithmetic.

уверенность1 — угадал, 5 — уверен полностью
Y1202Уровень YMLSступень 4минимумСлучайные величинысмешанный набор
RU

Честную монету бросают неограниченно долго. Начальной серией называется максимальный начальный участок, на котором все результаты одинаковы (например, для последовательности, начинающейся с ООР, длина серии равна 2).

Найдите математическое ожидание длины начальной серии. Ответ округлите до четырёх знаков после запятой.

EN

A fair coin is tossed indefinitely. The initial run is the longest initial segment in which all outcomes are the same. For example, a sequence beginning HHT has an initial run of length 2.

Find the expected length of the initial run. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Хвостовая формула: посчитать $\P(L \ge k)$ проще, чем $\P(L = k)$.

EN

Use the tail-sum formula: $\P(L \ge k)$ is easier to calculate than $\P(L = k)$.

Решение / Solution
RU

Серия имеет длину не меньше $k$ тогда и только тогда, когда первые $k$ бросков одинаковы. Первый задаёт результат, каждый следующий должен его повторить:

$$\P(L \ge k) = \left(\frac12\right)^{k-1}$$

По хвостовой формуле:

$$\E L = \sum_{k \ge 1}\P(L \ge k) = \sum_{k \ge 1}\left(\frac12\right)^{k-1} = \frac{1}{1 - \frac12} = 2$$
Почему хвостовая формула здесь удобнее

Прямое суммирование $\sum k\,\P(L = k)$ потребовало бы возиться с множителем $k$ внутри ряда. Хвостовая формула превращает задачу в обычную геометрическую прогрессию.

В мосте b1202 бросков было пять, и та же сумма обрывалась на $k = 5$, давая $31/16 = 1.9375$. Здесь обрыва нет, и ответ ровно 2. Близость этих чисел — готовая оценка руками: ответ обязан быть чуть меньше 2 при пяти бросках и ровно 2 при бесконечном числе.

EN

The run has length at least $k$ if and only if the first $k$ tosses are equal. The first toss determines the outcome, and each subsequent toss must match it:

$$\P(L \ge k) = \left(\frac12\right)^{k-1}$$

By the tail-sum formula,

$$\E L = \sum_{k \ge 1}\P(L \ge k) = \sum_{k \ge 1}\left(\frac12\right)^{k-1} = \frac{1}{1 - \frac12} = 2$$
Why the tail-sum formula is convenient here

Directly evaluating $\sum k\,\P(L=k)$ leaves a factor of $k$ inside the series. The tail-sum formula reduces the problem to an ordinary geometric series.

In bridge problem b1202, there were five tosses and the same sum stopped at $k=5$, giving $31/16=1.9375$. Here there is no cutoff, and the answer is exactly 2. These values provide an immediate estimate: for five tosses the answer must be slightly below 2, and with indefinitely many tosses it is 2.

уверенность1 — угадал, 5 — уверен полностью
Y1203Уровень YMLSступень 4минимумКомбинаторикасмешанный набор
RU

Найдите вероятность того, что случайная перестановка 6 элементов не имеет ни одной неподвижной точки, то есть ни один элемент не остался на своём месте. Все $6! = 720$ перестановок равновозможны. Ответ округлите до четырёх знаков после запятой.

EN

Find the probability that a uniformly random permutation of 6 elements has no fixed points, meaning that no element remains in its original position. All $6!=720$ permutations are equally likely. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Либо готовая формула беспорядков из блока «Мост», либо перебор: 720 перестановок — это ничто.

EN

Either use the derangement formula from the Bridge section or enumerate the permutations; 720 is tiny.

Решение / Solution
RU

Путь 1 — готовая формула. Число перестановок без неподвижных точек получается включениями-исключениями по событиям «элемент $i$ остался на месте»:

$$D_n = n!\sum_{k=0}^{n}\frac{(-1)^k}{k!}$$$$\P = \frac{D_6}{6!} = \sum_{k=0}^{6}\frac{(-1)^k}{k!} = 1 - 1 + \frac12 - \frac16 + \frac1{24} - \frac1{120} + \frac1{720} = \frac{53}{144} \approx 0.3681$$

Путь 2 — машина, пятнадцать секунд. Пространство исходов состоит из 720 перестановок, и первый вопрос на экзамене должен быть именно про его размер. Код — дословно тот же, что в мосте b1204, с заменой четвёрки на шестёрку:

import itertools
from fractions import Fraction as F
c = sum(1 for p in itertools.permutations(range(6)) if all(p[i] != i for i in range(6)))
print(c, F(c, 720))       # 265 53/144
Замечательный факт, который работает как оценка руками

При $n \to \infty$ эта вероятность стремится к $e^{-1} \approx 0.3679$, причём сходимость молниеносная: уже при $n = 6$ совпадают три знака. Это та же константа, что в задаче про письма из четвёртого дня, и не случайно: число неподвижных точек асимптотически распределено по Пуассону с $\lambda = 1$.

Отсюда бесплатная проверка: посчитанное значение обязано быть рядом с $0.368$. Если вышло далеко — ошибка видна до всякой сверки с ответом.

EN

Method 1: use the formula. By inclusion–exclusion on the events “element $i$ remains fixed,” the number of permutations with no fixed points is

$$D_n = n!\sum_{k=0}^{n}\frac{(-1)^k}{k!}$$$$\P = \frac{D_6}{6!} = \sum_{k=0}^{6}\frac{(-1)^k}{k!} = 1 - 1 + \frac12 - \frac16 + \frac1{24} - \frac1{120} + \frac1{720} = \frac{53}{144} \approx 0.3681$$

Method 2: let the computer enumerate, in fifteen seconds. The sample space has only 720 permutations; this should be the first observation on an exam. The code is identical to that in bridge problem b1204, with 4 replaced by 6:

import itertools
from fractions import Fraction as F
c = sum(1 for p in itertools.permutations(range(6)) if all(p[i] != i for i in range(6)))
print(c, F(c, 720))       # 265 53/144
A useful fact for estimating the answer

As $n\to\infty$, this probability tends to $e^{-1}\approx0.3679$, and convergence is extremely rapid: already for $n=6$, the first three decimal places agree. This is the same constant that appears in the letter problem from Day 4, for good reason: the number of fixed points is asymptotically Poisson with parameter $\lambda=1$.

Thus the computed value must be near $0.368$. A value far from it reveals an error before comparison with the official answer.

уверенность1 — угадал, 5 — уверен полностью
Y1205Уровень YMLSступень 1Матанализсмешанный набор
RU

Вычислите $\displaystyle\int_0^{+\infty} x^{2}e^{-x}\,dx$.

EN

Evaluate $\displaystyle\int_0^{+\infty} x^{2}e^{-x}\,dx$.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Это гамма-интеграл из блока «Мост». Интегрировать по частям не нужно.

EN

This is the gamma integral from the Bridge section; integration by parts is unnecessary.

Решение / Solution
RU$$\int_0^{\infty}x^{n}e^{-x}\,dx = n!$$

При $n = 2$ получаем $2! = 2$. Вся задача — в узнавании: подынтегральная функция это степень, умноженная на $e^{-x}$, и интеграл берётся по лучу $[0,+\infty)$. Это ступень 1 в одежде экзаменационной задачи: строка из блока «Мост» и подстановка, больше ничего. На экзамене такие задачи стоят столько же, сколько трудные, и берутся первыми.

Перекрёстная проверка с вероятностью

Это второй момент показательного распределения с $\lambda = 1$. Отсюда

$$\D X = \E X^{2} - (\E X)^{2} = 2 - 1 = 1$$

что совпадает с табличной формулой $\D = 1/\lambda^{2}$. Такие сверки между блоками — хороший способ убедиться, что оба факта помнишь верно.

Машинная проверка — одна строка: sp.integrate(x**2*sp.exp(-x), (x, 0, sp.oo)).

EN$$\int_0^{\infty}x^{n}e^{-x}\,dx = n!$$

For $n=2$, this gives $2!=2$. The entire problem is pattern recognition: the integrand is a power times $e^{-x}$, and the interval of integration is $[0,+\infty)$. This is a Level 1 exercise dressed as an exam problem: apply one line from the Bridge section and substitute. Such problems are worth as much as difficult ones on an exam and should be solved first.

Cross-check with probability

This is the second moment of an exponential distribution with $\lambda=1$. Therefore

$$\D X = \E X^{2} - (\E X)^{2} = 2 - 1 = 1$$

which agrees with the standard formula $\D=1/\lambda^2$. Cross-checks between topics are a useful way to ensure that both facts have been remembered correctly.

A one-line computational check is sp.integrate(x**2*sp.exp(-x), (x, 0, sp.oo)).

уверенность1 — угадал, 5 — уверен полностью
Y1206Уровень YMLSступень 2Комбинаторикасмешанный набор
RU

Сколько натуральных делителей (включая 1 и само число) имеет число 7560?

EN

How many positive divisors, including 1 and the number itself, does 7560 have?

Python · решить кодомsolve in code
RU

Программа читает ввод и печатает ответ. «Проверить на тестах» запускает её на тестах задачи: первый — данные из условия (они уже в поле «Ввод»), остальные скрыты, последний большой — на скорость. Прошли все — задача засчитана.

EN

The program reads the input and prints the answer. “Run tests” runs it on the problem’s tests: the first is the statement’s data (already in the Input box), the rest are hidden, and the last one is large to test speed. Pass them all and the problem counts as solved.

RU

Ввод. Одно целое $N$ ($1 \le N \le 10^{12}$). Вывод. Количество натуральных делителей $N$. Перебор всех чисел до $N$ здесь не успеет.

EN

Input. One integer $N$ ($1 \le N \le 10^{12}$). Output. The number of positive divisors of $N$. Trying every number up to $N$ will not finish in time.

ВыводOutput
Подсказка / Hint
RU

Разложение на простые множители в условии не дано — его надо получить самому. Дальше делитель полностью задаётся выбором показателя для каждого простого множителя.

EN

The prime factorization is not given; find it first. Then a divisor is determined completely by choosing an exponent for each prime factor.

Решение / Solution
RU

Шаг 1. Разложить. Делим на 2, пока делится, потом на 3, потом дальше: $7560 = 2\cdot3780 = 4\cdot1890 = 8\cdot945$, а $945 = 3\cdot315 = 9\cdot105 = 27\cdot35$ и $35 = 5\cdot7$. Итого

$$7560 = 2^{3}\cdot 3^{3}\cdot 5\cdot 7$$

Проверка умножением обязательна: $8\cdot27 = 216$, $216\cdot5 = 1080$, $1080\cdot7 = 7560$.

Шаг 2. Правило произведения. Каждый делитель имеет вид $2^{a}3^{b}5^{c}7^{d}$, где $a \in \{0,1,2,3\}$, $b \in \{0,1,2,3\}$, $c \in \{0,1\}$, $d \in \{0,1\}$: больше, чем в самом числе, показатель быть не может, а любая допустимая комбинация показателей даёт делитель, и разные комбинации дают разные делители. Выборы независимы, значит

$$\tau(7560) = 4 \cdot 4 \cdot 2 \cdot 2 = 64$$

Общая формула: если $N = \prod p_i^{\alpha_i}$, то $\tau(N) = \prod(\alpha_i + 1)$. Это правило произведения первого дня в чистом виде.

Второй путь и оценка руками

Прямой перебор sum(1 for d in range(1, 7561) if 7560 % d == 0) даёт те же 64 за миллисекунды — 7560 делений машина не замечает.

Оценка до счёта: делителей заведомо не меньше $2^{4} = 16$ — каждый из четырёх простых множителей либо входит в делитель, либо нет, и такие делители уже все разные. Ответ 12 отсекается, не доходя до сверки.

EN

Step 1. Factor the number. Divide by 2 as long as possible, then by 3, and continue: $7560=2\cdot3780=4\cdot1890=8\cdot945$, while $945=3\cdot315=9\cdot105=27\cdot35$ and $35=5\cdot7$. Therefore,

$$7560 = 2^{3}\cdot 3^{3}\cdot 5\cdot 7$$

Always verify by multiplication: $8\cdot27=216$, $216\cdot5=1080$, and $1080\cdot7=7560$.

Step 2. Apply the product rule. Every divisor has the form $2^a3^b5^c7^d$, where $a\in\{0,1,2,3\}$, $b\in\{0,1,2,3\}$, $c\in\{0,1\}$, and $d\in\{0,1\}$. An exponent cannot exceed the one in 7560. Every allowed combination gives a divisor, and distinct combinations give distinct divisors. These choices are independent, so

$$\tau(7560) = 4 \cdot 4 \cdot 2 \cdot 2 = 64$$

In general, if $N=\prod p_i^{\alpha_i}$, then $\tau(N)=\prod(\alpha_i+1)$. This is the product rule from Day 1 in its purest form.

A second method and a quick estimate

Direct enumeration with sum(1 for d in range(1, 7561) if 7560 % d == 0) also gives 64 in milliseconds; a computer does not notice 7560 divisions.

Before calculating, observe that there are at least $2^4=16$ divisors: each of the four prime factors may be included or omitted, and all such divisors are different. An answer such as 12 can be rejected before any detailed check.

уверенность1 — угадал, 5 — уверен полностью
Y1207Уровень YMLSступень 2Линалсмешанный набор
RU

Найдите расстояние от точки $(2, 1, -2)$ до плоскости $2x - y + 2z = 9$. Ответ округлите до четырёх знаков после запятой.

EN

Find the distance from the point $(2,1,-2)$ to the plane $2x-y+2z=9$. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Коэффициенты уравнения — координаты нормали.

EN

The coefficients in the equation are the coordinates of a normal vector.

Решение / Solution
RU

Нормаль читается прямо из уравнения: $n = (2, -1, 2)$, её длина $\|n\| = \sqrt{4+1+4} = 3$. Скалярное произведение с точкой: $\langle n, p\rangle = 4 - 1 - 4 = -1$.

$$d = \frac{|\langle n, p\rangle - c|}{\|n\|} = \frac{|-1 - 9|}{3} = \frac{10}{3} \approx 3.3333$$
Что подставляют неверно

В числителе стоит модуль невязки $\langle n,p\rangle - c$, а не сумма координат и не $\langle n,p\rangle + c$: свободный член обязан быть перенесён в ту же часть, где стоит точка. Отрицательный знак невязки означает лишь, что точка лежит по другую сторону плоскости от начала координат, и на расстояние он не влияет.

EN

Read the normal directly from the equation: $n=(2,-1,2)$, with norm $\|n\|=\sqrt{4+1+4}=3$. Its inner product with the point is $\langle n,p\rangle=4-1-4=-1$.

$$d = \frac{|\langle n, p\rangle - c|}{\|n\|} = \frac{|-1 - 9|}{3} = \frac{10}{3} \approx 3.3333$$
Common substitution errors

The numerator is the absolute value of the residual $\langle n,p\rangle-c$, not the sum of the coordinates and not $\langle n,p\rangle+c$. The constant term must be moved to the same side as the point evaluation. A negative residual only means that the point and the origin lie on opposite sides of the plane; it has no effect on the distance.

уверенность1 — угадал, 5 — уверен полностью
Y1208Уровень YMLSступень 2минимумАлгоритмысмешанный набор · округление
RU

Три маляра красят стены со скоростями $\frac13$, $\frac14$ и $\frac16$ стены в час и работают одновременно, не мешая друг другу. Найдите минимальное целое число часов, за которое они покрасят 100 стен.

EN

Three painters work simultaneously without interfering with one another. Their rates are $\frac13$, $\frac14$, and $\frac16$ of a wall per hour. Find the smallest integer number of hours in which they can paint 100 walls.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Скорости складываются. И подумай, в какую сторону округлять.

EN

Add the rates, then decide in which direction to round.

Решение / Solution
RU

Суммарная скорость:

$$\frac13 + \frac14 + \frac16 = \frac{4 + 3 + 2}{12} = \frac34 \text{ стены в час}$$$$t = \frac{100}{3/4} = \frac{400}{3} \approx 133.33 \;\Longrightarrow\; \lceil t\rceil = 134$$
Ловушка в округлении

Ответ 133 неверен: за 133 часа покрашено $133 \cdot \frac34 = 99.75$ стены, то есть работа не закончена. Проверка занимает пять секунд и делается всегда.

Спрашивай себя, в какую сторону округлять: «за сколько успеем» — вверх, «сколько успеем» — вниз. Это тот же вопрос, что в задаче про бананы, где $\lceil p/k\rceil$ был обязателен.

EN

The combined rate is

$$\frac13 + \frac14 + \frac16 = \frac{4 + 3 + 2}{12} = \frac34 \text{ of a wall per hour}$$$$t = \frac{100}{3/4} = \frac{400}{3} \approx 133.33 \;\Longrightarrow\; \lceil t\rceil = 134$$
The rounding trap

The answer 133 is wrong: in 133 hours, the painters complete $133\cdot\frac34=99.75$ walls, so the work is unfinished. This five-second check should always be made.

Ask which way to round: “how long until completion?” means round up, while “how much can be completed?” means round down. This is the same issue as in the banana-pile problem, where $\lceil p/k\rceil$ was essential.

уверенность1 — угадал, 5 — уверен полностью

Уровень ШАД

решено 0 из 1

Выше, чем требуется. Берём только там, где тема реально встречалась на их экзаменах.

S1201Уровень ШАДступень 4МатанализОлимпиада ШАД 2025, задача A «Плюс-минус»
RU

Дана интегрируемая функция $f: \mathbb{R} \to \mathbb{R}$ такая, что

$$\int_{-\infty}^{+\infty} f(x)\,dx = 2025$$

Найдите $\displaystyle\int_{-\infty}^{+\infty} f\!\left(x - \frac1x\right)dx$.

EN

Let $f:\mathbb{R}\to\mathbb{R}$ be an integrable function such that

$$\int_{-\infty}^{+\infty} f(x)\,dx = 2025$$

Find $\displaystyle\int_{-\infty}^{+\infty} f\!\left(x - \frac1x\right)dx$.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Ответ тот же. Разберись, почему — здесь замена работает не так, как обычно.

EN

The answer is the same. Determine why: the substitution behaves differently from an ordinary one-to-one change of variables.

Решение / Solution
RU

Ответ: 2025.

Идея. Рассмотрим $\varphi(x) = x - \frac1x$. На каждом из промежутков $(-\infty, 0)$ и $(0, +\infty)$ эта функция строго возрастает и отображает промежуток на всю прямую $\mathbb{R}$.

Значит при замене переменной каждая точка $y$ имеет ровно два прообраза — корни уравнения

$$x^2 - yx - 1 = 0$$

Обозначим их $x_1(y)$ и $x_2(y)$. По теореме Виета

$$x_1(y) + x_2(y) = y$$

Продифференцируем это тождество по $y$:

$$x_1'(y) + x_2'(y) = 1$$

Обе ветви возрастают, значит производные положительны и модули можно снять. Тогда

$$\int_{\mathbb{R}} f\!\left(x - \tfrac1x\right)dx = \int_{\mathbb{R}}\big(|x_1'(y)| + |x_2'(y)|\big)f(y)\,dy = \int_{\mathbb{R}} f(y)\,dy = 2025$$
Сверка, которая ловит ошибку в рассуждении

Утверждение проверяется машиной на конкретной $f$ за полминуты: возьми плотность стандартного нормального распределения, умноженную на 2025, и посчитай оба интеграла численно — mpmath.quad по промежуткам $(-\infty, 0)$ и $(0, +\infty)$ отдельно, потому что в нуле подынтегральная функция ведёт себя резко. Числа совпадут. Это не доказательство, но именно так отличают верное рассуждение от красивого.

Что забрать на YMLS

Приём «замена, склеивающая две ветви»: если подстановка неоднозначна, суммируй по всем ветвям — якобианы часто складываются во что-то тривиальное.

В чистом виде такое на YMLS вряд ли придёт. Но родственный приём — симметризация $\int_a^b f(x)dx = \int_a^b f(a+b-x)dx$ из восьмого дня — приходит регулярно, и это тот же ход мысли: не вычислять, а использовать структуру замены.

EN

Answer: 2025.

Idea. Consider $\varphi(x)=x-\frac1x$. On each interval $(-\infty,0)$ and $(0,+\infty)$, this function is strictly increasing and maps the interval onto the entire real line $\mathbb{R}$.

Therefore, under the change of variables, every point $y$ has exactly two preimages: the roots of

$$x^2 - yx - 1 = 0$$

Denote them by $x_1(y)$ and $x_2(y)$. By Vieta's formulas,

$$x_1(y) + x_2(y) = y$$

Differentiate this identity with respect to $y$:

$$x_1'(y) + x_2'(y) = 1$$

Both branches are increasing, so their derivatives are positive and the absolute values can be removed. Hence

$$\int_{\mathbb{R}} f\!\left(x - \tfrac1x\right)dx = \int_{\mathbb{R}}\big(|x_1'(y)| + |x_2'(y)|\big)f(y)\,dy = \int_{\mathbb{R}} f(y)\,dy = 2025$$
A check that catches a flaw in the reasoning

Test the claim computationally with a specific $f$: take the standard normal density multiplied by 2025 and evaluate both integrals numerically. Use mpmath.quad separately on $(-\infty,0)$ and $(0,+\infty)$ because the integrand varies sharply near zero. The results agree. This is not a proof, but it is an effective way to distinguish a correct argument from an attractive but false one.

The YMLS takeaway

Use the technique “a substitution that merges two branches.” When a substitution is not one-to-one, sum over all branches; the Jacobian factors often combine into something simple.

This exact form is unlikely on YMLS. A related method that appears regularly is the symmetrization $\int_a^b f(x)dx = \int_a^b f(a+b-x)dx$ from Day 8. The idea is the same: exploit the structure of the substitution instead of evaluating the integral directly.

уверенность1 — угадал, 5 — уверен полностью

Мини-тест под таймером

20 минут

Одна задача, таймер идёт, подсказки и решение не открываются до истечения времени. Это тренировка не математики, а поведения под давлением.

Y1204Уровень YMLSступень 4минимумВероятностьсмешанный набор · мини-тест дня
RU

Точка бросается наудачу (равномерно) в квадрат со стороной 1. Найдите вероятность того, что она окажется ближе к центру квадрата, чем к ближайшей из его четырёх сторон (расстояние до стороны меряется по перпендикуляру). Ответ округлите до четырёх знаков после запятой.

EN

A point is chosen uniformly at random from a square of side length 1. Find the probability that it is closer to the center of the square than to the nearest of its four sides, where distance to a side is measured perpendicularly. Round your answer to four decimal places.

Python · решить кодомsolve in code
RU

Здесь нет тестов: программа должна напечатать ответ последней строкой. «Сдать вывод как ответ» подставит его в поле ответа и проверит как обычно.

EN

This problem has no tests: the program must print the answer on its last line. “Submit output” puts it into the answer box and checks it as usual.

ВыводOutput
Подсказка / Hint
RU

Мост b1203 — та же задача с одной фиксированной стороной. Осталось понять, что меняет слово «ближайшая».

EN

Bridge problem b1203 is the same problem with one fixed side. Determine what changes when the side is the “nearest” one.

Решение / Solution
RU

Шаг 1. Разрезать квадрат. Диагонали делят квадрат на четыре равных треугольника, и в каждом ближайшая сторона своя. В нижнем треугольнике (он задан условиями $y < x$ и $y < 1 - x$) ближайшая сторона — нижняя, поэтому по симметрии достаточно посчитать площадь в нём и умножить на 4.

Шаг 2. Граница — та же парабола, что в b1203. Условие «ближе к центру, чем к нижней стороне» после возведения в квадрат превращается в

$$y > \left(x - \tfrac12\right)^{2} + \frac14$$

Шаг 3. Пределы интегрирования. Парабола пересекает сторону $y = x$ там, где $\left(x-\frac12\right)^{2} + \frac14 = x$, то есть $x^{2} - 2x + \frac12 = 0$ и $x = 1 - \frac{\sqrt2}{2} \approx 0.2929$; вторая точка по симметрии — $x = \frac{\sqrt2}{2}$.

Шаг 4. Интеграл. Между этими пределами область зажата между параболой снизу и стороной треугольника сверху. С заменой $u = x - \frac12$ высота полоски равна $u + \frac14 - u^{2}$, а симметрия относительно $x = \frac12$ позволяет считать половину и удвоить:

$$S = 2\int_{u_0}^{0}\left(u + \frac14 - u^{2}\right)du = \frac{\sqrt2}{3} - \frac{5}{12}, \qquad u_0 = \frac{1-\sqrt2}{2}$$$$\P = 4S = \frac{4\sqrt2 - 5}{3} \approx 0.218951$$

Ответ: 0.2190.

Сверка симуляцией.

import numpy as np
p = np.random.default_rng(0).random((6_000_000, 2))
dc = np.hypot(p[:,0] - .5, p[:,1] - .5)                    # до центра
db = np.minimum(np.minimum(p[:,0], 1 - p[:,0]),
                np.minimum(p[:,1], 1 - p[:,1]))            # до ближайшей стороны
print((dc < db).mean())      # 0.2188293...
Мораль дня в одной задаче

Симуляция на шести миллионах дала $0.21883$, точный ответ — $0.218951$. Три знака совпали, четвёртый нет, и сдавать пришлось бы неверное число. Именно об этом правило $1/\sqrt{N}$: на четвёртый знак нужно порядка $10^8$ испытаний.

Правильная стратегия: симуляция подтверждает, что область выписана верно, аналитика даёт точность. Если аналитики нет вовсе — гони сто миллионов испытаний и понимай, что последний знак под вопросом.

EN

Step 1. Partition the square. The diagonals divide it into four congruent triangles, and a different side is nearest in each one. In the bottom triangle, described by $y<x$ and $y<1-x$, the bottom side is nearest. By symmetry, it is enough to calculate the required area there and multiply by 4.

Step 2. The boundary is the same parabola as in b1203. After squaring, the condition “closer to the center than to the bottom side” becomes

$$y > \left(x - \tfrac12\right)^{2} + \frac14$$

Step 3. Integration limits. The parabola intersects the side $y=x$ when $\left(x-\frac12\right)^2+\frac14=x$, or $x^2-2x+\frac12=0$. Thus $x=1-\frac{\sqrt2}{2}\approx0.2929$; the other intersection is, by symmetry, $x=\frac{\sqrt2}{2}$.

Step 4. Integral. Between these limits, the region lies above the parabola and below a side of the triangle. With the substitution $u=x-\frac12$, the vertical width is $u+\frac14-u^2$. Symmetry about $x=\frac12$ allows us to integrate over half the region and double:

$$S = 2\int_{u_0}^{0}\left(u + \frac14 - u^{2}\right)du = \frac{\sqrt2}{3} - \frac{5}{12}, \qquad u_0 = \frac{1-\sqrt2}{2}$$$$\P = 4S = \frac{4\sqrt2 - 5}{3} \approx 0.218951$$

Answer: 0.2190.

Simulation check.

import numpy as np
p = np.random.default_rng(0).random((6_000_000, 2))
dc = np.hypot(p[:,0] - .5, p[:,1] - .5)                    # distance to the center
db = np.minimum(np.minimum(p[:,0], 1 - p[:,0]),
                np.minimum(p[:,1], 1 - p[:,1]))            # distance to the nearest side
print((dc < db).mean())      # 0.2188293...
The lesson of the day in one problem

Six million simulated points give $0.21883$, while the exact answer is $0.218951$. Three decimal places agree, but the fourth does not, so submitting the simulation result would be wrong. This is exactly what the $1/\sqrt{N}$ rule predicts: about $10^8$ trials are needed for the fourth decimal place.

The correct strategy is to use simulation to verify the region and analysis to obtain precision. If no analytical method is available, run one hundred million trials and recognize that the last digit is uncertain.

уверенность1 — угадал, 5 — уверен полностью
день закрыт, когда
Прочитав любую из восьми задач ступени YMLS, за 30 секунд называешь тему и первый ход, не начиная счёт; из восьми опознаний ошибочных не больше одногоAfter reading any of the eight YMLS problems, name the topic and first move within 30 seconds without calculating; no more than one of eight recognitions may be wrong
Четыре табличные задачи (y1205–y1208) решены подряд меньше чем за пять минут; в задаче y1208 направление округления названо вслух («за сколько успеем» — вверх) до вычисления числаSolve the four table-based problems (y1205–y1208) consecutively in under five minutes; for y1208, say the rounding direction aloud (“how long will we manage?” means up) before calculating
Увидев «максимум равен», «минимум равен» или «серия длиной», меньше чем за минуту выписываешь нужную величину через «все не больше $t$» или через хвост $\P(X \ge k)$: проверка на w1201, w1202, b1201, b1202 и финалах y1201, y1202When you see “the maximum equals,” “the minimum equals,” or “a run of length,” write the needed quantity in under a minute via “everything is at most $t$” or the tail $\P(X \ge k)$; check this on w1201, w1202, b1201, b1202, and finals y1201, y1202
Размер пространства исходов называешь вслух до того, как пишешь код: в b1204 — «24, перебор руками», в y1203 — «720, перебор машиной», раньше, чем вспоминаешь формулу беспорядков; а написав симуляцию за 3 минуты, сразу называешь, сколько знаков в ней верны: три при миллионе испытаний, четвёртый только при $10^8$State the outcome-space size aloud before writing code: in b1204, say “24, enumerate by hand”; in y1203, say “720, enumerate by machine,” before recalling the derangement formula; after writing a simulation in 3 minutes, immediately name how many digits are reliable: three at a million trials, the fourth only at $10^8$
Мини-тест y1204 сдан с первого ввода за 20 минут при отведённых на слот 25; оба пути — доля площади и симуляция — дали одно число до третьего знакаSubmit mini-test y1204 on the first entry in 20 minutes of its 25-minute slot; both routes—area fraction and simulation—must give the same number through the third digit
Все четыре обязательные задачи решены без подсказки; перед вводом каждого ответа вслух названа оценка руками: порядок величины и вилка, в которую ответ обязан попастьSolve all four mandatory problems without hints; before entering each answer, state your hand estimate aloud: order of magnitude and the interval the answer must fall into
аудит дня
RU

Сегодня в журнале два разных разреза, и путать их нельзя.

Первый — за сегодня, по типу ошибки. Ошибка распознавания: тема названа неверно или первый ход выбран не тот, и время ушло в стену. Ошибка счёта: приём выбран верно, а число не сошлось. Диагнозы противоположные. Первое лечится дрилем распознавания и таблицей из части 1, второе — оценкой руками до счёта и вторым независимым путём. Если ошибок распознавания больше двух, завтрашний мок надо начинать не с решения, а с прохода по всем восьми условиям и записи типов.

Второй — за все двенадцать дней. Открой журнал целиком, прочитай все записи и выпиши на отдельный лист два самых частых типа ошибок. Не десять, а два. Завтра на моке следи именно за ними, послезавтра — на настоящем экзамене.

EN

Today’s log has two different cuts, and you must not mix them up.

First: today, by error type. A recognition error means the topic was named incorrectly or the first move was wrong, so time ran into a wall. A calculation error means the technique was right but the number did not match. The diagnoses are opposite. Treat the first with recognition drills and the table from Part 1; treat the second with a hand estimate before calculation and a second independent route. If there are more than two recognition errors, start tomorrow’s mock not by solving but by reading all eight statements and writing down their types.

Second: all twelve days. Open the entire log, read every entry, and write the two most frequent error types on a separate sheet. Not ten—two. Watch specifically for those on tomorrow’s mock and the day after tomorrow on the real exam.