Полигон YMLSYMLS PolygonТашкент · 2026Tashkent · 2026
до попыткиuntil the attempt —
День 01 22 августа, суббота КомбинаторикаCombinatoricsСтартGetting started

Как считать вариантыHow to count possibilities

Пять приёмов, которые сводят задачу на счёт к четырём готовым формуламFive techniques that reduce counting problems to four ready-made formulas

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

цель дня
RU

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

EN

By the end of the day, you should be able to read a problem and name, within half a minute, which of the five techniques to use: split a choice into groups, encode an arrangement as a string, divide by overcounting, count quantities rather than order, or count the forbidden cases. Three of the four standard counts are not derived here—they are supplied in the Bridge block—while the fourth (sampling with replacement) is developed in Technique 4. Check yourself on the three final problems below; the last one is timed.

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

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

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

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

EN

There is no bridge from yesterday on the first day. Today’s bridge comes from school: you will need exactly eight facts from it, and none will be derived during the lesson—they are treated as known. Read the list aloud. If any item takes more than a couple of seconds to recall, restore it now; those five minutes will pay off before the day is over.

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

  1. $n! = 1 \cdot 2 \cdots n$, причём $0! = 1$; наизусть до $8! = 40320$$n! = 1 \cdot 2 \cdots n$, with $0! = 1$; know the values up to $8! = 40320$
  2. Упорядоченный выбор $k$ объектов из $n$ без повторов: $n(n-1)\cdots(n-k+1) = \frac{n!}{(n-k)!}$, то есть $k$ убывающих множителейOrdered selection of $k$ objects from $n$ without replacement: $n(n-1)\cdots(n-k+1) = \frac{n!}{(n-k)!}$, that is, $k$ descending factors
  3. $\binom{n}{k} = \frac{n!}{k!\,(n-k)!}$ и симметрия $\binom{n}{k} = \binom{n}{n-k}$$\binom{n}{k} = \frac{n!}{k!\,(n-k)!}$ and the symmetry $\binom{n}{k} = \binom{n}{n-k}$
  4. $n^k$ — число слов длины $k$ из алфавита в $n$ букв$n^k$ is the number of length-$k$ words over an alphabet of $n$ letters
  5. Чисел от 1 до $N$, делящихся на $d$, ровно $\lfloor N/d \rfloor$There are exactly $\lfloor N/d \rfloor$ integers from 1 through $N$ divisible by $d$
  6. Число делится и на $a$, и на $b$ тогда и только тогда, когда делится на НОК$(a, b)$; для взаимно простых $a$ и $b$ это просто $ab$An integer is divisible by both $a$ and $b$ exactly when it is divisible by LCM$(a,b)$; for coprime $a$ and $b$, this is simply $ab$
  7. Мощность объединения: $|A \cup B| = |A| + |B| - |A \cap B|$Size of a union: $|A \cup B| = |A| + |B| - |A \cap B|$
  8. Шестизначное число не может начинаться с нуляA six-digit number cannot begin with zero
зачем это сегодня
RU

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

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

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

EN

Pure combinatorics rarely appears as a standalone topic in the online stage. It appears inside probability problems: classical probability is the ratio of two counts, and you perform both counts. That is why counting comes first and is made automatic before anything else.

A counting mistake is more dangerous than most other mistakes, for a simple reason. If you confuse a differentiation rule, the expression usually stops working: something does not cancel, the sign is wrong, or the answer looks ugly. If you count the wrong set of outcomes, the solution can remain coherent and the number can still look plausible. There is no way to check it except by building an independent check. Half of today’s lesson is about constructing those checks.

The format adds pressure: four hours for eight problems, roughly half an hour per problem; only a number is accepted, with no second attempt. In this setting, the winner is not the person who knows the most formulas, but the person who picks the right count in thirty seconds and checks it in a minute.

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

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

  1. 1Считаю по шагам и выбираю счётCount step by step and choose the right countРаскладываешь исход на последовательные решения, проверяешь словом «при каждом» и по двум вопросам — важен ли порядок, разрешены ли повторы — берёшь готовый счёт из блока «Мост»Break the outcome into sequential decisions, test it with the phrase “for every,” then use the two questions “does order matter?” and “are repetitions allowed?” to select a ready-made count from the BridgeW0102W0104B0102
  2. 2Режу выбор на блокиSplit a choice into groupsТот же счёт, но условие делит объекты на группы: каждый блок считаешь отдельным сочетанием, а блоки перемножаешьThe same count, but the condition divides the objects into groups: count each group as its own combination and multiply the groupsB0101B0103
  3. 3Кодирую расстановку строкойEncode an arrangement as a stringИсход, который не сводится к «кого взяли», записываешь строкой символов, и вопрос сводится к «на каких местах стоят символы одного вида». Общая ступень для обоих финалов y0102 и y0103If the outcome is not simply “which objects were chosen,” write it as a string of symbols. The question becomes “which positions contain symbols of one kind.” This is the common step behind both final problems y0102 and y0103B0104S0101
  4. 4Делю на кратностьDivide by overcountingВ строке символы одного вида повторяются: считаешь как будто все различны, делишь на кратность и отвечаешь, различимы ли группы одинакового размераWhen identical symbols repeat in a string, count as if they were distinct, then divide by the overcounting factor; decide whether groups of equal size are distinguishableW0103B0106Y0103
  5. 5Считаю количества вместо порядкаCount quantities instead of orderОбъекты одинаковы и важно только, сколько раз взят каждый тип: та же строка, но из шаров и перегородокThe objects are identical and only the number of objects of each type matters: use the same string idea, now with balls and dividersW0101B0107Y0102
  6. 6Считаю запрещённоеCount the forbidden casesКогда прямой счёт по любой схеме выше распадается на слагаемые, переворачиваешь его: считаешь запрет и вычитаешь, а пересечения возвращаешь включениями-исключениямиWhen a direct count breaks into too many terms, turn it around: count the forbidden outcomes and subtract them, restoring overlaps with inclusion–exclusionB0108B0105Y0101

Расписание

0:00–0:15РазогревWarm-up Восемь пунктов из блока «Мост» вслух, без конспекта. Заодно убедись, что Python запускается, а заявка на mlschool.yandex.uz подана — без неё окно теста не откроется.Recite the eight Bridge facts without notes. Also make sure Python runs and that your application to mlschool.yandex.uz has been submitted—without it, the test window will not open.
0:15–1:20УрокLesson С бумагой. Входную задачу про четыре вопроса досчитай сам, прежде чем читать дальше; каждый разобранный пример пробуй закрыть до того, как посмотришь ответ.Work on paper. Solve the opening four-question problem yourself before reading on; for every worked example, try to finish it before looking at the answer.
1:20–3:20ЗадачиProblems По ступеням 1 → 4, без перепрыгиваний. Четыре обязательные задачи — b0104 на ступени 2 и вся ступень 3 целиком — не пропускаются ни при каком раскладе: это мосты к финалам.Follow levels 1 → 4 without jumping ahead. Four required problems—b0104 at level 2 and all of level 3—must not be skipped: they are the bridges to the finals.
3:20–3:45Мини-тестMini-test y0103 под таймером, в режиме экзамена: подсказка и разбор закрыты, ответ вводится один раз.Do y0103 under a timer in exam mode: the hint and solution are hidden, and the answer can be submitted once.
3:45–4:00АудитAudit Критерии внизу страницы, заметка дня, первые записи в журнал ошибок.Review the criteria at the bottom of the page, write the day’s note, and make the first entries in your error log.

Урок

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

Вход: одна задача, четыре разных ответа

Из цифр $1, 2, 3, 4, 5, 6$ составляют наборы длины четыре. Сколько существует наборов, если:

  1. цифры могут повторяться и порядок важен — то есть считаем четырёхзначные числа из этих цифр;
  2. цифры различны, порядок важен;
  3. цифры различны, порядок не важен — важно только, какие четыре цифры взяли;
  4. цифры могут повторяться, порядок не важен — важно только, сколько раз взяли каждую.

Четыре вопроса отличаются двумя словами, ответы отличаются в разы: $1296$, $360$, $15$, $126$. Первые три берутся из блока «Мост» без изменений: $6^4$, затем $6 \cdot 5 \cdot 4 \cdot 3$, затем $\binom{6}{4}$. Четвёртый из «Моста» не достаётся и устроен так же, как одна из финальных задач дня. Урок — про то, как за полминуты понять, в какой из четырёх клеток ты находишься и что делать, когда задача не помещается ни в одну. Приёмов пять, идут они в том же порядке, что задачи на странице.

Опора: правило умножения

Единственное, что сегодня формулируется с нуля, — не формула, а условие её применимости. Обе оговорки в правиле рабочие, поэтому произносить его надо целиком.

Правило умножения

Если исход однозначно задаётся последовательностью решений, на первом шаге вариантов $m$, а на втором — $n$ при каждом исходе первого шага, то всего исходов $m \cdot n$.

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

Четыре стандартных счёта — это правило умножения в четырёх режимах. Три клетки таблицы лежат в «Мосте» готовыми, четвёртая разбирается в приёме 4; работа сегодня не в клетках, а в том, как задача к ним сводится.

Что берёмПорядок важенПорядок не важен
$k$ из $n$, повторы разрешены$n^k$$\binom{n+k-1}{k}$
$k$ из $n$, повторы запрещены$n(n-1)\cdots(n-k+1)$$\binom{n}{k}$
все $n$ объектов$n!$1
Проверка порядка за пять секунд

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

Приём 1: разрезать выбор на блоки

Условие вида «ровно столько-то из такой-то группы» почти никогда не считается одним сочетанием.

Задача. В группе 12 студентов, из них 5 девушек. Сколько существует команд из 4 человек, в которых ровно 2 девушки?

Порядок внутри команды не важен, значит сочетания. Но $\binom{12}{4}$ взять нельзя: условие делит людей на две группы, из которых берётся разное количество, и выбор распадается на два шага со своим сочетанием на каждом.

$$\binom{5}{2}\binom{7}{2} = 10 \cdot 21 = 210$$

Перемножаем, а не складываем, потому что команда состоит из девушек и юношей одновременно. Складывают взаимоисключающие случаи: «ровно 2 девушки или ровно 3 девушки» — вот там сумма. Разрезав задачу на блоки, сразу спроси, получается ли каждый исход ровно одним способом: если какому-то исходу отвечают две раскладки по блокам, ответ завышен, а выглядит верным.

Приём 2: закодировать расстановку строкой

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

Задача. Из левого нижнего угла прямоугольника шириной 3 клетки и высотой 2 клетки идут по линиям сетки в правый верхний, за шаг сдвигаясь на клетку вправо или вверх. Сколько путей?

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

$$\binom{5}{2} = 10$$
Кодирование строкой

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

Приём 3: делить на кратность

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

Деление на кратность

Если каждый нужный объект посчитан ровно $r$ раз и $r$ одинаково для всех объектов — раздели на $r$. Если $r$ у разных объектов разное, делить нельзя: надо разбивать на случаи.

Одно применение уже лежит в «Мосте»: $\binom{n}{k}$ — упорядоченный выбор, делённый на $k!$, потому что каждый набор посчитан столько раз, сколькими способами его выстраивают в ряд.

Расстановка по кругу

Задача. Сколькими способами рассадить 5 человек за круглым столом, если рассадки, отличающиеся поворотом стола, считаются одинаковыми?

Занумеруем стулья и рассадим людей как в ряду: $5! = 120$ нумерованных рассадок. Поворот на один стул переводит рассадку в другую нумерованную, но условие их не различает; поворотов 5, считая нулевой, и все дают разные рассадки — при нетривиальном повороте никто не остаётся на своём стуле. Значит кратность равна 5 и одинакова для всех:

$$\frac{5!}{5} = 4! = 24$$
Круговые перестановки

$n$ объектов по кругу, когда повороты не различаются, — это $(n-1)!$, а не $n!$. Практический ход короче деления: посади одного на фиксированное место и считай остальных как обычный ряд — тогда повороты не возникают вовсе.

Строка с повторяющимися символами

Задача. Сколько различных слов получается перестановкой букв слова КОЛОКОЛ?

Букв семь, но не все различны: К — две, О — три, Л — две. Будь все семь различны, слов было бы $7! = 5040$, и каждое реальное слово посчитано там несколько раз: две К переставляются между собой $2!$ способами, три О — $3!$, две Л — $2!$, причём независимо. Кратность равна $2! \cdot 3! \cdot 2! = 24$ и одна и та же для всех слов — зависит от состава, не от порядка:

$$\frac{7!}{2!\,3!\,2!} = \frac{5040}{24} = 210$$

Тот же счёт отвечает на другой с виду вопрос: сколькими способами раздать 7 различных предметов трём людям порциями 2, 3 и 2? Слово из К, О и Л — это указание, кому достался каждый предмет.

Мультиномиальный коэффициент$$\frac{n!}{n_1!\,n_2!\cdots n_k!}, \qquad n_1 + n_2 + \cdots + n_k = n$$

Число отвечает на три вопроса сразу: перестановки строки с повторами; раскладка $n$ различных объектов по $k$ пронумерованным ящикам заданных размеров; выбор составов групп по очереди $\binom{n}{n_1}\binom{n-n_1}{n_2}\cdots$ А если группы равного размера неразличимы («разбить на пары»), ответ делят ещё на число их перестановок: слово «пронумерованные» в условии читай первым.

Приём 4: считать количества вместо порядка

Вернёмся к четвёртому вопросу входной задачи: цифры из $\{1, \ldots, 6\}$, длина четыре, повторы разрешены, порядок не важен — это та клетка таблицы, которой в «Мосте» нет. Первое: «порядок не важен» здесь равносильно «запишем цифры по возрастанию» — у каждого набора с повторами ровно одна неубывающая запись, и наоборот. Второе: набор полностью описывается тем, сколько раз взята каждая из шести цифр, то есть нужно число решений уравнения

$$x_1 + x_2 + \cdots + x_6 = 4$$

в целых неотрицательных числах, где $x_i$ — сколько раз взята цифра $i$. Третье — снова кодирование строкой, только символы другие. Выложим четыре одинаковых шара в ряд и вставим пять перегородок, делящих ряд на шесть участков: сколько шаров в $i$-м участке, столько раз взята $i$-я цифра. Перегородки можно ставить рядом и по краям — это и есть цифра, не взятая ни разу. Всего в ряду $4 + 5 = 9$ позиций, и строка задана тем, где стоят пять перегородок:

$$\binom{9}{5} = \binom{9}{4} = 126$$
Выбор с повторениями

Взять $k$ объектов из $n$ типов, повторы разрешены, порядок не важен: $\binom{n + k - 1}{k}$. Запоминать надо не формулу, а картинку: $k$ шаров и $n - 1$ перегородка в одном ряду. Путаешься, $n + k - 1$ или $n + k$, — проверь на $n = 2$, $k = 2$: пар 11, 12, 22 ровно три.

Приём 5: считать запрещённое

Задача. Сколько слов длины 5 из букв $\{a, b, c, d\}$ содержат хотя бы одну букву $a$?

В лоб — пять слагаемых: ровно одна $a$, ровно две, и так до пяти, и в каждом слагаемом ещё сочетание на выбор позиций. В обход — слов без единой $a$ ровно $3^5$, и это одна строчка:

$$4^5 - 3^5 = 1024 - 243 = 781$$
Рефлекс

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

Приём ломается ровно в одном месте: когда запрещённых условий несколько и они пересекаются, простое вычитание убирает пересечения дважды. Для двух множеств поправка есть в «Мосте»: $|A \cup B| = |A| + |B| - |A \cap B|$. Для трёх картина продолжается со знакочередованием — одиночные складываем, пары вычитаем, тройку возвращаем:

$$|A \cup B \cup C| = |A| + |B| + |C| - |A \cap B| - |A \cap C| - |B \cap C| + |A \cap B \cap C|$$

Проверяется это подсчётом вкладов, а не доказательством. Элемент ровно из одного множества учтён один раз; элемент ровно из двух — дважды в первой сумме и один раз в сумме пар, итого $2 - 1 = 1$; элемент из всех трёх — $3 - 3 + 1 = 1$. Каждый учтён ровно один раз, что и нужно.

Осталась логическая деталь, на которой задачу теряют чаще, чем на арифметике. Если требуется, чтобы выполнялись два условия сразу, запрет — отрицание их обоих вместе, а отрицание «и» — это «или»: требование «есть и единица, и двойка» нарушено, когда нет единицы или нет двойки. Значит запрет — объединение и считается включениями-исключениями; написать вместо этого «нет ни единицы, ни двойки» значит взять кусок запрета. На этом шаге построена эталонная задача ниже.

Как это выглядит на экзамене

«Не делится ни на 2, ни на 3, ни на 5» — это $1000 - |A_2 \cup A_3 \cup A_5|$, где $A_d$ — кратные $d$, а пересечения берутся через НОК: и на 2, и на 3 — значит на 6. Одна из трёх финальных задач дня устроена ровно так.

Пять проверок, которые ловят ошибку до отправки ответа

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

  1. Каждый исход ровно один раз. Возьми конкретный исход и посчитай, сколькими путями твоя схема его выдаёт. Больше одного — ответ завышен ровно в кратность раз.
  2. Сложил или умножил. Умножают последовательные шаги («и»), складывают взаимоисключающие случаи («или»). Проверяется вставкой этого союза в русскую фразу.
  3. Крайний случай. Подставь $k = 0$ или $k = n$ — формула обязана дать 1. Подставь маленькие числа, при которых ответ пересчитывается руками.
  4. Порядок величины. Ответ лежит между нулём и числом исходов без ограничений; где есть доли — прикинь их произведением, как в проверке к задаче y0101.
  5. Целость. В задаче на счёт ответ — целое число. Дробь на выходе означает, что где-то поделили не на ту кратность.
EN

Opening: one problem, four different answers

Form length-four sets from the digits $1, 2, 3, 4, 5, 6$. How many sets are there if:

  1. digits may repeat and order matters—in other words, we are counting four-digit numbers made from these digits;
  2. digits must be distinct and order matters;
  3. digits must be distinct and order does not matter—only which four digits were chosen matters;
  4. digits may repeat and order does not matter—only how many times each digit was chosen matters.

The four questions differ by two words, but their answers differ dramatically: $1296$, $360$, $15$, and $126$. The first three come directly from the Bridge: $6^4$, then $6 \cdot 5 \cdot 4 \cdot 3$, then $\binom{6}{4}$. The fourth is not in the Bridge and is built like one of today’s final problems. The lesson is about recognizing, within half a minute, which of the four cells you are in—and what to do when a problem fits none of them. There are five techniques, presented in the same order as the problems on the page.

Foundation: the multiplication rule

The only thing introduced from scratch today is not a formula but the condition under which it applies. Both qualifications in the rule matter, so state the whole rule.

Multiplication rule

If an outcome is uniquely determined by a sequence of decisions, with $m$ choices at the first step and $n$ choices at the second for every outcome of the first step, then there are $m \cdot n$ outcomes in total.

“Uniquely determined” means that different decision sequences produce different outcomes and every outcome is produced by at least one sequence; otherwise the product counts each outcome with a multiplicity and you must divide. “For every” means that the number of choices at the second step does not depend on the first choice (it may still change from one step to another). Choosing two class monitors in order from ten people gives 10 choices and then 9: the 9 is the same for every first choice. But if the second monitor must not be a classmate of the first, multiplication cannot be applied directly—the number of second choices depends on the first, so split into cases according to the number of classmates.

The four standard counts are the multiplication rule in four different modes. Three cells of the table are supplied in the Bridge; the fourth is developed in Technique 4. The point today is not memorizing cells, but learning how to reduce a problem to one of them.

What is selectedOrder mattersOrder does not matter
$k$ from $n$, repetitions allowed$n^k$$\binom{n+k-1}{k}$
$k$ from $n$, repetitions forbidden$n(n-1)\cdots(n-k+1)$$\binom{n}{k}$
all $n$ objects$n!$1
Check whether order matters in five seconds

Invent two concrete outcomes that differ only in order and ask: are they one result or two? “Petya wins gold and Vanya silver” versus “Vanya wins gold and Petya silver” are two different results. “A committee consisting of Petya and Vanya” versus “a committee consisting of Vanya and Petya” is the same committee.

Technique 1: split a choice into groups

A condition of the form “exactly this many from that group” is almost never counted with one combination.

Problem. A class has 12 students, 5 of them girls. How many four-person teams contain exactly two girls?

Order inside a team does not matter, so we use combinations. But $\binom{12}{4}$ is not valid: the condition divides the people into two groups, from which different numbers must be chosen, so the selection has two steps, each with its own combination.

$$\binom{5}{2}\binom{7}{2} = 10 \cdot 21 = 210$$

We multiply rather than add because the team contains girls and boys at the same time. We add mutually exclusive cases such as “exactly 2 girls or exactly 3 girls.” After splitting a problem into groups, immediately ask whether every outcome has exactly one such decomposition. If some outcome has two decompositions, the answer is overcounted even though it may look reasonable.

Technique 2: encode an arrangement as a string

Splitting into groups works while the outcome is a subset—“which objects were chosen.” But an outcome is often a route, a schedule, or a sequence of similar steps. Write it as a string first; only then does it become clear what is being selected.

Problem. From the lower-left corner of a rectangle 3 cells wide and 2 cells high, move along the grid lines to the upper-right corner, shifting one cell right or up at each step. How many paths are there?

Every such path has exactly three right moves and two up moves; otherwise it cannot reach the upper-right corner. Write a path as a word, where R means “move right” and U means “move up.” The word RRURU represents exactly one path, and every path corresponds to exactly one word: the encoding loses nothing and merges nothing, which is precisely the condition that lets us count words instead of paths. A five-letter word is fully determined by the positions occupied by U:

$$\binom{5}{2} = 10$$
Encoding as a string

If an outcome is a sequence of steps of several types, write it as a string of symbols. The question then always becomes: which positions contain symbols of one kind? Before substituting a formula, check reversibility: the outcome can be reconstructed from the string, and the string from the outcome. This form will return later: Technique 3 uses three kinds of symbols, and Technique 4 uses balls and dividers.

Technique 3: divide by overcounting

The multiplication rule requires different decision sequences to produce different outcomes. The third technique deliberately breaks that requirement: count with repetitions, then divide.

Division by overcounting

If every desired object is counted exactly $r$ times, with the same $r$ for all objects, divide by $r$. If different objects have different values of $r$, division is invalid: split into cases instead.

One example is already in the Bridge: $\binom{n}{k}$ is an ordered selection divided by $k!$, because every set is counted as many times as it can be arranged in a row.

Seating around a circle

Problem. In how many ways can 5 people sit around a circular table if seatings that differ only by rotating the table are considered identical?

Number the chairs and seat the people as in a row: $5! = 120$ numbered seatings. Rotating by one chair maps a seating to another numbered seating, but the condition does not distinguish them. There are 5 rotations, including the zero rotation, and they all give different numbered seatings: under any nontrivial rotation, nobody remains in the same chair. Thus the multiplicity is 5 for every seating:

$$\frac{5!}{5} = 4! = 24$$
Circular permutations

Arranging $n$ objects around a circle when rotations are indistinguishable gives $(n-1)!$, not $n!$. A shorter practical method is to place one person in a fixed seat and arrange the rest in a row; then rotations never arise.

A string with repeated symbols

Problem. How many distinct words can be formed by rearranging the letters of K-O-L-O-K-O-L?

There are seven letters, but they are not all distinct: K occurs twice, O three times, and L twice. If all seven were distinct, there would be $7! = 5040$ words. Each actual word is counted several times there: the two Ks can be swapped in $2!$ ways, the three Os in $3!$ ways, and the two Ls in $2!$ ways, independently. The multiplicity is $2! \cdot 3! \cdot 2! = 24$, the same for every word because it depends on the composition, not the order:

$$\frac{7!}{2!\,3!\,2!} = \frac{5040}{24} = 210$$

The same count answers a different-looking question: in how many ways can 7 distinct objects be dealt to three people in batches of sizes 2, 3, and 2? A word of K, O, and L is a record of who received each object.

Multinomial coefficient$$\frac{n!}{n_1!\,n_2!\cdots n_k!}, \qquad n_1 + n_2 + \cdots + n_k = n$$

This number answers three questions at once: permutations of a string with repeats; distributing $n$ distinct objects among $k$ numbered boxes of specified sizes; and choosing group memberships sequentially, $\binom{n}{n_1}\binom{n-n_1}{n_2}\cdots$. If equal-sized groups are not distinguishable (“partition into pairs”), divide once more by the number of ways to permute those groups. In a condition, read the word “numbered” first.

Technique 4: count quantities rather than order

Return to the fourth question in the opening example: choose a length-four multiset from $\{1, \ldots, 6\}$, with repetition allowed and order irrelevant. This is the table cell missing from the Bridge.

First, “order does not matter” is equivalent to “write the digits in nondecreasing order”: every multiset with repetitions has exactly one nondecreasing representation, and vice versa. Second, the set is completely described by how many times each of the six digits is chosen, so we need the number of nonnegative integer solutions to

$$x_1 + x_2 + \cdots + x_6 = 4$$

where $x_i$ is the number of times digit $i$ is selected. Third, this is again string encoding, with different symbols. Place four identical balls in a row and insert five dividers, splitting the row into six sections. The number of balls in section $i$ is the number of times digit $i$ was selected. Dividers may be adjacent or at the ends; that represents a digit selected zero times. The row has $4 + 5 = 9$ positions, and the string is determined by the positions of the five dividers:

$$\binom{9}{5} = \binom{9}{4} = 126$$
Sampling with replacement

Choosing $k$ objects from $n$ types, with repetition allowed and order irrelevant, gives $\binom{n + k - 1}{k}$. Remember the picture rather than the formula: $k$ balls and $n-1$ dividers in one row. If you confuse $n+k-1$ with $n+k$, test $n=2$, $k=2$: the pairs 11, 12, and 22 give exactly three.

Technique 5: count the forbidden cases

Problem. How many length-5 words over $\{a,b,c,d\}$ contain at least one $a$?

Direct counting gives five terms: exactly one $a$, exactly two, and so on through five, with a further choice of positions in every term. The indirect route is one line: words with no $a$ at all number $3^5$.

$$4^5 - 3^5 = 1024 - 243 = 781$$
The reflex

The phrases “at least one,” “one or more,” “there exists,” “none,” and “divisible by neither” all point to the same move: count the forbidden cases and subtract from the total. Direct counting in these problems is almost always longer and almost always invites an arithmetic error.

The technique fails in exactly one situation: when several forbidden conditions overlap. Simple subtraction then removes the overlaps twice. For two sets, the correction is in the Bridge: $|A \cup B| = |A| + |B| - |A \cap B|$. For three sets, the signs alternate: add singles, subtract pairs, add the triple intersection:

$$|A \cup B \cup C| = |A| + |B| + |C| - |A \cap B| - |A \cap C| - |B \cap C| + |A \cap B \cap C|$$

You can verify this by counting contributions rather than proving a formula. An element in exactly one set is counted once; an element in exactly two is counted twice in the first sum and once in the pair sum, for $2-1=1$; an element in all three contributes $3-3+1=1$. Every element is counted exactly once.

One logical detail causes more lost points than the arithmetic. If two conditions must hold simultaneously, the forbidden event is the negation of both together, and the negation of “and” is “or”: “there is both a 1 and a 2” fails when there is no 1 or no 2. Thus the forbidden set is a union and must be counted by inclusion–exclusion. Writing “there is neither a 1 nor a 2” takes only part of the forbidden set. The model problem below is built around this step.

What it looks like on the exam

“Divisible by neither 2, 3, nor 5” means $1000 - |A_2 \cup A_3 \cup A_5|$, where $A_d$ is the set of multiples of $d$ and intersections use the LCM: divisible by both 2 and 3 means divisible by 6. One of today’s three final problems has exactly this structure.

Five checks that catch an error before submission

No one reads the justification, and there is no second attempt. Each check below is part of the solution, not pedantry, and takes less than a minute.

  1. Every outcome exactly once. Take a concrete outcome and count how many paths through your scheme produce it. More than one means the answer is overcounted by that multiplicity.
  2. Add or multiply? Multiply sequential steps (“and”); add mutually exclusive cases (“or”). Test it by inserting the conjunction into the sentence describing the problem.
  3. Boundary case. Substitute $k=0$ or $k=n$; the formula must give 1. Also test small numbers whose answers you can calculate by hand.
  4. Order of magnitude. The answer lies between zero and the unrestricted number of outcomes. For fractions, estimate the probability by multiplying rough proportions, as in the check for y0101.
  5. Integer check. A counting answer is an integer. A fraction at the end means that the wrong multiplicity was divided out somewhere.

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

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

УвиделПервый ход
Порядок различает исходы, берём часть объектовOrder distinguishes outcomes; select part of the objectsПовторы разрешены — степень n в степени k; запрещены — убывающее произведение из k множителей, начиная с nRepetition allowed: use $n^k$; forbidden: use a descending product of $k$ factors starting at $n$
Порядок не различает исходы, повторов нетOrder does not distinguish outcomes; no repetitionСочетание: то же убывающее произведение, делённое на k факториал; считая руками, всегда бери меньшее из k и n−kUse a combination: the same descending product divided by $k!$; for hand calculation, always use the smaller of $k$ and $n-k$
«Ровно столько-то из такой-то группы»“Exactly this many from that group”Режу выбор на блоки: каждый блок — своё сочетание, блоки перемножаютсяSplit into groups: each group contributes its own combination, and multiply the groups
Исход — маршрут, расстановка, последовательность однотипных шаговThe outcome is a route, arrangement, or sequence of similar stepsЗапиши его строкой символов; вопрос сводится к «на каких местах стоят символы одного вида»Write it as a string of symbols; the question becomes “which positions contain symbols of one kind?”
В строке символы повторяются либо объекты раздаются порциямиSymbols repeat in a string, or objects are dealt out in batchesРаскладка на группы: факториал сверху, факториалы размеров снизу; группы равного размера без номеров — поделить ещё разUse a group allocation: factorial on top, factorials of group sizes below; if equal-sized groups are unnumbered, divide once more
«По кругу», «за круглым столом», повороты не различаем“Around a circle,” “at a round table,” rotations ignoredПосади одного на фиксированное место и считай остальных как ряд: получится (n−1) факториалPlace one object in a fixed position and arrange the rest as a row: this gives $(n-1)!$
«Не убывают», «сколько раз взяли каждый тип», одинаковые объекты по различным ящикам“Nondecreasing,” “how many of each type,” identical objects in different boxesШары и перегородки: k шаров и n−1 перегородка в одном рядуUse balls and dividers: $k$ balls and $n-1$ dividers in one row
«Хотя бы один», «ни одного», «не делится ни на»“At least one,” “none,” “divisible by neither”Считай запрещённое и вычитай из всего; если запретов несколько и они пересекаются — включения-исключенияCount the forbidden cases and subtract from the total; if forbidden cases overlap, use inclusion–exclusion
эталонная задача

Шестизначные числа, в которых есть и единица, и двойкаSix-digit numbers containing both a 1 and a 2

RU

Условие. Сколько существует шестизначных чисел, в записи которых встречается хотя бы одна цифра 1 и хотя бы одна цифра 2?

Схема этой задачи — «требований вида «хотя бы» несколько, поэтому переворачиваем в запрет» — повторяется сегодня трижды: в b0108 (два запрета), в b0105 (три запрета) и в финальной задаче y0101. Смотри не на числа, а на то, какое решение принимается на каждом шаге.

Шаг 1. Назвать исход и посчитать всё без ограничений. Исход — само шестизначное число, то есть строка из шести цифр, у которой первая не ноль. Порядок цифр, разумеется, различает исходы. Всего таких строк $9 \cdot 10^5 = 900\,000$: первая цифра из девяти, остальные пять из десяти.

Шаг 2. Решить, что считать — разрешённое или запрещённое. Прямой счёт означал бы перебор по тому, сколько в числе единиц и сколько двоек: допустимых пар «сколько-сколько» больше двадцати, и в каждой ещё выбор позиций. Оба требования — вида «хотя бы», а это рефлекс: считаем запрет.

Шаг 3. Правильно записать запрет. Здесь задачу и теряют. Запрет — это отрицание того, что оба требования выполнены сразу, то есть «нет единицы или нет двойки». Не «нет ни единицы, ни двойки»: последнее — только пересечение, кусок запрета. Обозначим через $A$ множество чисел без единицы, через $B$ — без двойки; запрет есть $A \cup B$.

Шаг 4. Посчитать части. В числе без единицы первая цифра берётся из восьми вариантов $\{2, \ldots, 9\}$, а каждая из остальных пяти — из девяти оставшихся цифр:

$$|A| = 8 \cdot 9^5 = 8 \cdot 59\,049 = 472\,392$$

По той же причине $|B| = 472\,392$. В пересечении запрещены обе цифры: первая берётся из семи вариантов $\{3, \ldots, 9\}$, остальные пять — из восьми:

$$|A \cap B| = 7 \cdot 8^5 = 7 \cdot 32\,768 = 229\,376$$

Шаг 5. Собрать и проверить.

$$|A \cup B| = 472\,392 + 472\,392 - 229\,376 = 715\,408$$$$N = 900\,000 - 715\,408 = 184\,592$$

Проверка порядком величины. Если забыть про запрет на ведущий ноль, доля чисел без единицы была бы $0{,}9^6 \approx 0{,}53$, столько же без двойки, а без обеих цифр — $0{,}8^6 \approx 0{,}26$. Доля «хороших» тогда примерно $1 - 0{,}53 - 0{,}53 + 0{,}26 = 0{,}20$, то есть около 180 тысяч из девятисот. Получили 184 592 — сходится. Обрати внимание, что прикидка воспроизводит ту же структуру «минус два, плюс пересечение»: если в основном счёте забыть вернуть пересечение, прикидка это немедленно покажет.

Алгоритм
  1. Назови исход одним предложением и посчитай общее число исходов без ограничений.
  2. Найди слова «хотя бы», «ни одного», «не делится ни на» — они означают, что считать надо запрет.
  3. Запиши запрет как отрицание условия целиком: отрицание «и» — это «или», отрицание «или» — это «и».
  4. Если запрет оказался объединением, считай его включениями-исключениями: одиночные плюс, пары минус, тройки плюс.
  5. Вычти запрет из общего числа и проверь ответ грубой оценкой доли.
EN

Problem. How many six-digit numbers contain at least one digit 1 and at least one digit 2?

The pattern in this problem—several “at least” requirements, so turn them into a forbidden event—appears three times today: in b0108 (two forbidden conditions), b0105 (three), and the final problem y0101. Focus not on the numbers, but on the decision made at each step.

Step 1. Name the outcome and count without restrictions. The outcome is the six-digit number itself, a string of six digits whose first digit is not zero. Digit order matters. There are $9 \cdot 10^5 = 900\,000$ such strings: nine choices for the first digit and ten for each of the remaining five.

Step 2. Decide whether to count allowed or forbidden outcomes. A direct count would enumerate how many 1s and how many 2s occur. There are more than twenty possible pairs of counts, each followed by a choice of positions. Both conditions say “at least,” so apply the reflex: count the forbidden outcomes.

Step 3. State the forbidden event correctly. This is where the problem is usually lost. The forbidden event is the negation of both requirements being true, namely “no 1 or no 2.” It is not “neither 1 nor 2,” which is only the intersection and covers just part of the forbidden set. Let $A$ be the set of numbers without a 1 and $B$ the set without a 2; the forbidden set is $A \cup B$.

Step 4. Count the parts. In a number without a 1, the first digit has eight choices, $\{2, \ldots, 9\}$, and each of the other five has nine choices:

$$|A| = 8 \cdot 9^5 = 8 \cdot 59\,049 = 472\,392$$

Similarly, $|B| = 472\,392$. In the intersection, both digits are forbidden: seven choices for the first digit, $\{3, \ldots, 9\}$, and eight for each of the remaining positions:

$$|A \cap B| = 7 \cdot 8^5 = 7 \cdot 32\,768 = 229\,376$$

Step 5. Assemble and check.

$$|A \cup B| = 472\,392 + 472\,392 - 229\,376 = 715\,408$$$$N = 900\,000 - 715\,408 = 184\,592$$

An order-of-magnitude check: if we ignored the leading-zero restriction, the fraction of numbers without a 1 would be $0.9^6 \approx 0.53$, and the same would hold for no 2; without either digit it would be $0.8^6 \approx 0.26$. The fraction of “good” strings would then be about $1-0.53-0.53+0.26=0.20$, or roughly 180,000 out of 900,000. Our 184,592 is consistent. Notice that the estimate reproduces the same “subtract two, add the intersection” structure; forgetting to restore the intersection in the exact count would be obvious here.

Algorithm
  1. Name the outcome in one sentence and count all unrestricted outcomes.
  2. Look for “at least,” “none,” or “divisible by neither”; these signal that you should count the forbidden cases.
  3. Write the forbidden event as the negation of the entire condition: the negation of “and” is “or,” and the negation of “or” is “and.”
  4. If the forbidden event is a union, use inclusion–exclusion: singles plus, pairs minus, triples plus.
  5. Subtract the forbidden count from the total and sanity-check the result with a rough fraction.

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

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

видеоHarvard Stat 110 · Lecture 1: Probability and CountingHarvard Stat 110 · Lecture 1: Probability and Counting EN
Блицстайн строит ту же таблицу из четырёх счётов, что в блоке «Мост»: важен ли порядок × разрешены ли повторы. Сорок минут, после которых выбор формулы перестаёт быть угадыванием.Blitzstein builds the same four-count table as the Bridge: does order matter × are repetitions allowed? Forty minutes that turns formula selection from guesswork into a decision.
видео3Blue1Brown · Binomial distributions3Blue1Brown · Binomial distributions EN
Откуда берутся биномиальные коэффициенты, показано геометрически. Смотреть, если рассуждение про деление на кратность не улеглось. Двадцать минут.A geometric explanation of where binomial coefficients come from. Watch this if the division-by-overcounting argument has not settled into place. Twenty minutes.
текстAoPS · Ball-and-urn (stars and bars)AoPS · Ball-and-urn (stars and bars) EN
Одна страница ровно про приём 4: шары и перегородки, вывод $\binom{n+k-1}{k}$ и вариант «в каждом ящике хотя бы один». Пять минут чтения и два примера снизу.One page devoted to Technique 4: balls and dividers, the derivation of $\binom{n+k-1}{k}$, and the variant “at least one in every box.” Five minutes of reading and two examples below.
текстStat 110 · Strategic Practice 1 — задачи с решениямиStat 110 · Strategic Practice 1 — problems with solutions EN
Первый PDF в списке — счёт и наивное определение вероятности. Задачи интереснее учебниковых, к каждой полное решение. Брать, если сегодняшних задач не хватило.The first PDF in the list covers counting and the naive definition of probability. The problems are more interesting than textbook drills, with complete solutions. Use it if today’s set was not enough.
текстУчебник Яндекса · Математика для анализа данныхYandex textbook · Mathematics for data analysis RU
Тот же коллектив, что делает ШАД. Раздел «Комбинаторика» — как справочник и источник дополнительных задач, а не как первый заход в тему.Written by the same group that runs the SHAD program. Use the Combinatorics section as a reference and source of extra problems, not as your first introduction to the topic.
как работать сегодня
RU

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

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

Приём финалаПростая версияМостФинал
Деление на кратность, раскладка на группыw0103, ступень 1b0104 и b0106, ступени 2 и 3y0103
Количества вместо порядка, шары и перегородкиw0101, ступень 1b0104 и b0107, ступени 2 и 3y0102
Счёт запрещённого, включения-исключенияb0108, ступень 2b0105, ступень 3y0101

b0104 стоит в двух строках таблицы не по ошибке. Это не отдельный приём финала, а общая для двух финалов ступень — кодирование расстановки строкой; из неё вырастают и раскладка на группы, и шары с перегородками. Поэтому в «Лестнице микронавыков» она отнесена именно к кодированию строкой, а не к одному из двух приёмов.

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

Минимум — 10 задач. w0101, w0103, b0104, b0105, b0106, b0107, b0108, y0101, y0102, y0103. Это ровно содержимое таблицы выше: три простые версии, четыре моста и три финала. Выброшено то, что повторяет уже отработанный приём, не добавляя нового решения.

Обязательные — 4 задачи. b0104, b0105, b0106, b0107. Пропустить любую значит прийти к финалу дня без инструмента: b0105 даёт включения-исключения для y0101, b0106 — раскладку на группы для y0103, b0107 — шары и перегородки для y0102, b0104 — строку, на которой стоят обе последние. Если день сорвался и осталось сорок минут — делаются эти четыре и мини-тест, остальное переносится.

Как пользоваться подсказкой

Открывай подсказку после пяти минут честного тупика, не раньше. Подсказка называет приём, но не раскрывает решение: тренируется именно навык «узнать приём», а на экзамене решает задачу как раз он.

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

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

EN

Today’s problems form a four-level ladder. Work through them in order: each level builds on the previous one.

The three techniques underlying the final problems each appear three times—first in a simple form, then in a bridge problem, and finally in the final:

Final techniqueSimple versionBridgeFinal
Division by overcounting, group allocationw0103, level 1b0104 and b0106, levels 2 and 3y0103
Quantities instead of order, balls and dividersw0101, level 1b0104 and b0107, levels 2 and 3y0102
Counting forbidden cases, inclusion–exclusionb0108, level 2b0105, level 3y0101

b0104 appears in two rows intentionally. It is not a separate final technique but a common level for the two finals: encoding an arrangement as a string. It leads both to group allocation and to balls and dividers. That is why the Micro-skills Ladder assigns it to string encoding rather than to either of the two final techniques.

Full workload: 16 problems. Everything on the page, including the SHAD level. This is a good-day plan that leaves two hours for problems.

Minimum: 10 problems. w0101, w0103, b0104, b0105, b0106, b0107, b0108, y0101, y0102, y0103. This is exactly the content of the table: three simple versions, four bridges, and three finals. The repetitions that add no new idea are omitted.

Required: 4 problems. b0104, b0105, b0106, and b0107. Skipping any one means reaching the final without an essential tool: b0105 supplies inclusion–exclusion for y0101, b0106 supplies group allocation for y0103, b0107 supplies balls and dividers for y0102, and b0104 supplies the string representation used by the last two. If the day goes badly and only forty minutes remain, do these four and the mini-test; postpone everything else.

How to use a hint

Open a hint after five minutes of honest deadlock, not before. A hint names the technique but does not reveal the solution: the skill being trained is recognizing the technique, and that is exactly what matters in the exam.

Answer format

All answers today are integers, entered without spaces or thousands separators. Starting tomorrow, decimal answers will appear; enter them with four digits after the decimal point.

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

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

Разминка

решено 4 из 4

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

W0101Разминкаступень 1минимумКомбинаторика✓разминка
RU

Четыре одинаковых мяча раскладывают по трём различным ящикам. Мячи между собой не различаются, ящик может остаться пустым, и раскладка задаётся только тем, сколько мячей попало в каждый ящик. Сколько существует различных раскладок?

EN

Four identical balls are placed into three distinct boxes. The balls are indistinguishable, a box may be empty, and an arrangement is determined only by the number of balls in each box. How many different arrangements are possible?

верно
Подсказка / Hint
RU

Исход — не «какой мяч куда», а тройка чисел. Изобрази раскладку одной строкой из мячей и перегородок.

EN

An outcome is not a record of “which ball went where,” but a triple of numbers. Represent an arrangement by a single row of balls and dividers.

Решение / Solution
RU

Исход — тройка целых неотрицательных чисел $x_1, x_2, x_3$, где $x_i$ — сколько мячей попало в $i$-й ящик, с единственным условием $x_1 + x_2 + x_3 = 4$.

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

Каждой раскладке отвечает ровно одна такая строка и каждой строке — ровно одна раскладка, поэтому считать можно строки. Позиций в ряду $4 + 2 = 6$, и строка полностью задана тем, на каких двух из них стоят перегородки:

$$\binom{6}{2} = \frac{6 \cdot 5}{1 \cdot 2} = 15$$
Проверка перечислением

Раскладки удобно сгруппировать по составу. Вида 4+0+0 — три штуки, вида 3+1+0 — шесть, вида 2+2+0 — три, вида 2+1+1 — три. Итого $3 + 6 + 3 + 3 = 15$. Сходится, а заодно видно, что перечислять руками дольше, чем ставить перегородки.

EN

An outcome is a triple of nonnegative integers $x_1, x_2, x_3$, where $x_i$ is the number of balls in box $i$, subject only to

$$x_1 + x_2 + x_3 = 4.$$

Place the four identical balls in a row and insert two dividers. The balls to the left of the first divider go into the first box, those between the dividers go into the second box, and those to the right of the second divider go into the third box. Dividers may be adjacent or placed at either end of the row; these are exactly the cases in which a box is empty.

Every arrangement corresponds to exactly one such row, and every row to exactly one arrangement, so it is enough to count the rows. There are $4 + 2 = 6$ positions, and a row is completely determined by the two positions occupied by the dividers:

$$\binom{6}{2} = \frac{6 \cdot 5}{1 \cdot 2} = 15$$
Check by enumeration

Group the arrangements by their counts. There are three of type 4+0+0, six of type 3+1+0, three of type 2+2+0, and three of type 2+1+1. Thus $3 + 6 + 3 + 3 = 15$. This agrees with the answer and also shows that listing the cases by hand takes longer than placing dividers.

уверенность1 — угадал, 5 — уверен полностью
W0102Разминкаступень 1Комбинаторика✓разминка
RU

Из 7 человек выбирают двоих в один и тот же наряд. Обязанности между ними не делятся, старшего нет, поэтому наряд «Петя и Ваня» и наряд «Ваня и Петя» — это один и тот же наряд. Сколькими способами можно составить наряд?

EN

Two people are selected from a group of 7 for the same duty. They have no separate roles and neither is senior, so the pair “Petya and Vanya” is the same assignment as “Vanya and Petya.” In how many ways can the pair be selected?

верно
Подсказка / Hint
RU

Условие прямо говорит, что перестановка двоих ничего не меняет. Значит из двух счётов для выбора двух объектов из семи нужен тот, где порядок исходы не различает.

EN

The statement explicitly says that swapping the two people changes nothing. Therefore, of the two standard ways to count selections of two objects from seven, use the one in which order does not distinguish outcomes.

Решение / Solution
RU

Порядок не различает исходы, повторов быть не может — это сочетания:

$$\binom{7}{2} = \frac{7 \cdot 6}{1 \cdot 2} = 21$$

Если бы в условии стояло «старший дежурный и младший», перестановка двоих давала бы другой исход, и ответ был бы $7 \cdot 6 = 42$ — ровно вдвое больше. Разница между двумя счётами целиком спрятана в одной фразе условия, поэтому читать её надо первой.

EN

Order does not distinguish outcomes, and repetitions are impossible, so we use combinations:

$$\binom{7}{2} = \frac{7 \cdot 6}{1 \cdot 2} = 21$$

If the roles had instead been “senior duty officer” and “junior duty officer,” swapping the two people would produce a different outcome, and the answer would be $7 \cdot 6 = 42$, exactly twice as large. The entire difference between the two counts is contained in one phrase of the statement, so identify that phrase first.

уверенность1 — угадал, 5 — уверен полностью
W0103Разминкаступень 1минимумКомбинаторика✓разминка
RU

Буквы слова МАМА переставляют всеми возможными способами. Сколько различных четырёхбуквенных цепочек при этом получается? Две расстановки, дающие одну и ту же цепочку букв, считаются за одну.

EN

The letters of the word MAMA are rearranged in every possible way. How many distinct four-letter strings can be obtained? Two arrangements that produce the same string of letters count as one.

верно
Подсказка / Hint
RU

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

EN

First count as if all four letters were distinct, then determine how many times each actual string has been counted.

Решение / Solution
RU

Будь все четыре буквы различны, цепочек было бы $4! = 24$.

Пометим одинаковые буквы номерами: М1, М2, А1, А2. Возьмём любую реальную цепочку, скажем МАМА, и спросим, сколько помеченных расстановок дают именно её. Две буквы М раскладываются по своим двум местам $2!$ способами, независимо от этого две буквы А — тоже $2!$ способами, итого $2! \cdot 2! = 4$.

Число 4 одно и то же для любой цепочки: оно зависит только от состава букв, а не от того, как они расставлены. Значит делить можно сразу, без разбора случаев:

$$\frac{4!}{2!\,2!} = \frac{24}{4} = 6$$
Проверка перечислением

Выпишем все цепочки целиком: ММАА, МАМА, МААМ, АММА, АМАМ, ААММ. Ровно шесть. Делай такую проверку каждый раз, когда приём деления на кратность применяется в новой для тебя ситуации: она стоит полминуты и снимает вопрос, на что именно делить.

EN

If all four letters were distinct, there would be $4! = 24$ strings.

Label equal letters: M1, M2, A1, A2. Take any actual string, say MAMA, and ask how many labeled arrangements produce it. The two M's can be assigned to their two positions in $2!$ ways; independently, the two A's can also be assigned in $2!$ ways. Thus each string is counted $2! \cdot 2! = 4$ times.

The factor 4 is the same for every string: it depends only on the multiset of letters, not on their order. We may therefore divide immediately, without considering separate cases:

$$\frac{4!}{2!\,2!} = \frac{24}{4} = 6$$
Check by enumeration

The complete list is MMAA, MAMA, MAAM, AMMA, AMAM, AAMM: exactly six strings. Whenever the divide-by-multiplicity method is new in a particular setting, this half-minute check is worth doing: it makes clear exactly what the divisor should be.

уверенность1 — угадал, 5 — уверен полностью
W0104Разминкаступень 1Комбинаторика✓разминка
RU

Вычислите $\binom{20}{18}$.

EN

Evaluate $\binom{20}{18}$.

верно
Подсказка / Hint
RU

Не считай в лоб. Есть свойство симметрии.

EN

Do not compute it directly. Use symmetry.

Решение / Solution
RU

По симметрии $\binom{20}{18} = \binom{20}{2}$, а это уже устный счёт:

$$\binom{20}{2} = \frac{20 \cdot 19}{2} = 190$$

Считать $\binom{20}{18}$ по определению значит перемножить восемнадцать множителей сверху и восемнадцать снизу. Триггер «бери меньшее из $k$ и $n-k$» из блока «Триггеры» превращает эту работу в одно умножение и одно деление.

EN

By symmetry, $\binom{20}{18} = \binom{20}{2}$, which is easy to compute mentally:

$$\binom{20}{2} = \frac{20 \cdot 19}{2} = 190$$

Computing $\binom{20}{18}$ directly from the definition would require eighteen factors in both the numerator and the denominator. The rule “use the smaller of $k$ and $n-k$” from the Triggers section reduces all that work to one multiplication and one division.

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

База

решено 8 из 8

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

B0101Базаступень 2Комбинаторика✓авторская
RU

В отделе 10 сотрудников, из них 4 женщины. Сколькими способами можно составить комиссию из 3 человек, в которой ровно одна женщина?

EN

A department has 10 employees, 4 of whom are women. In how many ways can a committee of 3 people containing exactly one woman be formed?

верно
Подсказка / Hint
RU

Разбей выбор на два независимых шага и перемножь.

EN

Split the selection into two independent steps and multiply.

Решение / Solution
RU

Порядок в комиссии не важен → сочетания. Условие «ровно одна женщина» разбивает выбор на два шага.

Женщину выбираем из четырёх: $\binom{4}{1} = 4$ способа. Двух мужчин из шести: $\binom{6}{2} = \frac{6 \cdot 5}{2} = 15$ способов.

При каждом выборе женщины мужчин можно добрать 15 способами, значит перемножаем:

$$N = 4 \cdot 15 = 60$$
Проверка себя

Если бы сложили ($4 + 15 = 19$) — ошибка. Складывают взаимоисключающие случаи, перемножают последовательные шаги. Комиссия состоит из женщины и мужчин одновременно.

EN

Order within a committee does not matter, so we use combinations. The condition “exactly one woman” splits the selection into two steps.

Choose the woman in $\binom{4}{1} = 4$ ways. Choose two men from the remaining six in $\binom{6}{2} = \frac{6 \cdot 5}{2} = 15$ ways.

For each choice of the woman, the men can be chosen in 15 ways, so we multiply:

$$N = 4 \cdot 15 = 60$$
Check your reasoning

Adding the counts ($4 + 15 = 19$) would be incorrect. Add mutually exclusive cases; multiply successive choices. The committee contains the woman and the men at the same time.

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

Сколькими способами можно рассадить 8 человек за круглым столом так, чтобы двое конкретных сидели рядом? Рассадки, отличающиеся поворотом стола, считаются одинаковыми.

EN

In how many ways can 8 people be seated at a round table if two specified people must sit next to each other? Seatings that differ only by a rotation of the table are considered identical.

верно
Подсказка / Hint
RU

Склей двоих в один объект. Дальше — приём с фиксированным местом из третьего раздела урока.

EN

Treat the two specified people as a single object. Then use the fixed-seat technique from the third section of the lesson.

Решение / Solution
RU

Шаг 1. Склеиваем двоих в один «блок». Остаётся 7 объектов: блок и шесть отдельных человек.

Шаг 2. Рассаживаем 7 объектов по кругу. В уроке это разобрано: рассадки, отличающиеся поворотом, условие не различает, поэтому одного сажают на фиксированное место, а остальные $7 - 1 = 6$ расставляются как обычный ряд: $6! = 720$.

Шаг 3. Внутри блока двое могут поменяться местами: $\times 2$.

$$N = 2 \cdot 6! = 1440$$
Что здесь легко потерять

Круговые перестановки — это $(n-1)!$, а не $n!$, и склейка двоих в блок не отменяет ни одного из двух множителей. Проверь оба: и деление за поворот, и умножение на 2 за порядок внутри блока.

EN

Step 1. Combine the two specified people into one “block.” This leaves 7 objects: the block and six individual people.

Step 2. Arrange the 7 objects around the table. As discussed in the lesson, rotations do not produce distinct outcomes, so fix one object in place and arrange the remaining $7 - 1 = 6$ objects as an ordinary row: $6! = 720$.

Step 3. The two people inside the block may swap places: multiply by 2.

$$N = 2 \cdot 6! = 1440$$
Two easy factors to lose

The number of circular permutations is $(n-1)!$, not $n!$, and combining two people into a block does not remove either factor. Check both adjustments: account for rotations and multiply by 2 for the order inside the block.

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

Из 30 студентов выбирают команду из 5 человек. Порядок в команде не важен. Сколько существует команд, в которые обязательно входит Антон?

EN

A team of 5 people is selected from 30 students. Order within the team does not matter. How many such teams include Anton?

верно
Подсказка / Hint
RU

Место Антона уже занято. Что осталось выбрать?

EN

Anton's place is already filled. What remains to be chosen?

Решение / Solution
RU

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

$$\binom{29}{4} = \frac{29 \cdot 28 \cdot 27 \cdot 26}{1 \cdot 2 \cdot 3 \cdot 4} = 23\,751$$
EN

Anton's membership is fixed, not a choice. The condition splits the 30 people into two groups, from which we take 1 and 4 people respectively; the first group contains only Anton, so there is nothing to choose there. It remains to select 4 people from the other 29:

$$\binom{29}{4} = \frac{29 \cdot 28 \cdot 27 \cdot 26}{1 \cdot 2 \cdot 3 \cdot 4} = 23\,751$$
уверенность1 — угадал, 5 — уверен полностью
B0104Базаступень 2обязательнаяКомбинаторика✓авторская
RU

Сколько существует кратчайших путей по линиям сетки из левого нижнего угла прямоугольника шириной 8 клеток и высотой 4 клетки в его правый верхний угол, если за один шаг разрешено сдвинуться только на одну клетку вправо или на одну клетку вверх?

EN

How many shortest paths along grid lines lead from the bottom-left corner of an 8-by-4 rectangle to its top-right corner if each step must move one cell either right or up?

верно
Подсказка / Hint
RU

Опиши путь словом из букв «В» и «П». Сколько букв каждого вида?

EN

Encode a path as a word made of R's and U's. How many letters of each kind are needed?

Решение / Solution
RU

Любой кратчайший путь — это последовательность из 8 шагов вправо и 4 шагов вверх, всего 12 шагов: меньше не хватит, чтобы дойти, больше — уже не кратчайший. Разным путям отвечают разные слова из В и П, разным словам — разные пути, поэтому вместо путей считаем слова.

Слово из двенадцати букв полностью определяется тем, на каких местах стоят шаги вверх. Выбираем 4 позиции из 12:

$$\binom{12}{4} = \frac{12 \cdot 11 \cdot 10 \cdot 9}{24} = 495$$
Почему эта задача обязательна

Это самая простая ситуация, где исход не сводится к «кого взяли», а его всё равно удаётся записать строкой. Дальше строка работает дважды: в задачах про перестановки букв символов становится больше двух видов, а в задачах про шары и перегородки самими символами становятся шары и перегородки. Оба финала дня, y0102 и y0103, стоят на этом ходе.

EN

Every shortest path is a sequence of 8 steps to the right and 4 steps upward, for a total of 12 steps. Fewer steps cannot reach the destination, while any longer path is not shortest. Different paths correspond to different words over R and U and vice versa, so we can count words instead of paths.

A twelve-letter word is completely determined by the positions occupied by the upward steps. Choose 4 of the 12 positions:

$$\binom{12}{4} = \frac{12 \cdot 11 \cdot 10 \cdot 9}{24} = 495$$
Why this problem is essential

This is the simplest setting in which an outcome is not merely “which objects were chosen,” yet it can still be encoded as a string. This representation returns twice later: letter-arrangement problems use more than two kinds of symbols, while stars-and-bars problems use the objects and dividers themselves as symbols. Both final problems, y0102 and y0103, rely on this idea.

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

Сколько существует строк длины 10 из букв $\{a, b, c\}$, в которых встречается каждая из трёх букв хотя бы один раз?

EN

How many strings of length 10 over the alphabet $\{a, b, c\}$ contain each of the three letters at least once?

верно
Подсказка / Hint
RU

«Хотя бы один раз» — считай дополнение. Но дополнений тут несколько, и они пересекаются.

EN

“At least once” suggests counting the complement. The complementary event is a union of several overlapping cases.

Решение / Solution
RU

Всего строк без ограничений: $3^{10} = 59\,049$.

Вычитаем «плохие» — те, где какой-то буквы нет. Внимание к формулировке запрета: требуется, чтобы были и $a$, и $b$, и $c$; значит запрет — это «нет $a$ или нет $b$ или нет $c$», то есть объединение трёх множеств.

Строк без буквы $a$: остальные две буквы на 10 мест, то есть $2^{10} = 1024$. Так же без $b$ и без $c$ — вычитаем $3 \cdot 1024 = 3072$.

Но строки, где отсутствуют две буквы (то есть все символы одинаковы), мы вычли дважды. Таких строк три: $aaaa\ldots$, $bbbb\ldots$, $cccc\ldots$. Возвращаем $+3$. Строк, где нет ни одной из трёх букв, не бывает, поэтому тройное пересечение пусто и на этом ряд обрывается.

$$N = 3^{10} - 3 \cdot 2^{10} + 3 = 59\,049 - 3072 + 3 = 55\,980$$
Формула включений и исключений

Складываем одиночные, вычитаем пары, прибавляем тройки — со знакочередованием. Она понадобится ещё не раз; сегодня достаточно увидеть, откуда берётся возврат $+3$.

EN

There are $3^{10} = 59\,049$ unrestricted strings.

Subtract the “bad” strings in which some letter is absent. Pay attention to the logical form: we require $a$, $b$, and $c$ to appear, so failure means “no $a$ or no $b$ or no $c$,” the union of three sets.

If $a$ is absent, each of the 10 positions has two choices, giving $2^{10} = 1024$ strings. The same holds for $b$ and for $c$, so initially subtract $3 \cdot 1024 = 3072$.

However, strings missing two letters—those with all symbols equal—were subtracted twice. There are three such strings: $aaaa\ldots$, $bbbb\ldots$, and $cccc\ldots$. Add back 3. No string can omit all three letters, so the triple intersection is empty.

$$N = 3^{10} - 3 \cdot 2^{10} + 3 = 59\,049 - 3072 + 3 = 55\,980$$
Inclusion-exclusion

Add the single sets, subtract pairwise intersections, and add triple intersections, with alternating signs. This principle will appear repeatedly; for now, notice exactly why the correction term $+3$ is needed.

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

Буквы слова МАТЕМАТИКА переставляют всеми возможными способами. Сколько различных цепочек из десяти букв при этом получается? Две расстановки, дающие одну и ту же цепочку букв, считаются за одну.

EN

The letters of the word MATEMATIKA are rearranged in every possible way. How many distinct ten-letter strings can be obtained? Two arrangements that produce the same string count as one.

верно
Подсказка / Hint
RU

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

EN

First count the strings as if all ten letters were distinct, then determine how many times each actual string has been counted.

Решение / Solution
RU

Состав слова: А — три штуки, М — две, Т — две, а Е, И и К — по одной. Всего десять букв.

Шаг 1. Считаем так, будто все буквы различны. Пометим одинаковые буквы номерами: А1, А2, А3, М1, М2, Т1, Т2, а Е, И, К оставим как есть. Различных расстановок помеченных букв ровно $10! = 3\,628\,800$.

Шаг 2. Находим кратность. Возьмём любую реальную цепочку, например МАМАТЕТИКА. Сколько помеченных расстановок дают именно её? Три буквы А раскладываются по своим трём местам $3! = 6$ способами, две М — $2!$ способами, две Т — $2!$, и эти перестановки независимы:

$$3!\,2!\,2! = 6 \cdot 2 \cdot 2 = 24$$

Число 24 одно и то же для любой цепочки: оно зависит только от состава букв, а не от того, как они расставлены. Значит, делить можно сразу, без разбора случаев.

Шаг 3. Делим.

$$N = \frac{10!}{3!\,2!\,2!} = \frac{3\,628\,800}{24} = 151\,200$$
Тот же счёт — про группы

Цепочка букв — это указание, какая позиция досталась какой букве. Поэтому то же число отвечает на вопрос «сколькими способами раздать 10 пронумерованных мест буквам порциями 3, 2, 2, 1, 1, 1». Финальная задача дня устроена ровно так, только про людей и группы.

EN

The word contains three A's, two M's, two T's, and one each of E, I, and K: ten letters total.

Step 1. Count as if every letter were distinct. Label repeated letters A1, A2, A3, M1, M2, T1, T2, and leave E, I, K unchanged. There are exactly $10! = 3\,628\,800$ arrangements of the labeled letters.

Step 2. Find the multiplicity. Take any actual string, for example MAMATETIKA. How many labeled arrangements produce it? The three A's can be assigned to their three positions in $3! = 6$ ways, the two M's in $2!$ ways, and the two T's in $2!$ ways. These assignments are independent:

$$3!\,2!\,2! = 6 \cdot 2 \cdot 2 = 24$$

The multiplicity 24 is the same for every string: it depends only on the multiset of letters, not on their positions. We can therefore divide without considering separate cases.

Step 3. Divide.

$$N = \frac{10!}{3!\,2!\,2!} = \frac{3\,628\,800}{24} = 151\,200$$
The same count describes groups

A letter string specifies which positions are assigned to each letter. Therefore, the same number answers the question “in how many ways can 10 numbered positions be allocated to letters in groups of sizes 3, 2, 2, 1, 1, 1?” The final problem of the day uses exactly the same count, but with people and groups.

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

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

EN

Eight identical candies are distributed among four distinct boxes; a box may be empty. How many different distributions are possible? A distribution is determined only by the number of candies placed in each box.

верно
Подсказка / Hint
RU

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

EN

The candies are indistinguishable, so count a quadruple of numbers, not “which candy goes where.” Represent a distribution by a row of objects and dividers.

Решение / Solution
RU

Раскладка — это набор целых неотрицательных чисел $x_1, x_2, x_3, x_4$, где $x_i$ — сколько конфет попало в $i$-ю коробку, с единственным условием

$$x_1 + x_2 + x_3 + x_4 = 8$$

Перебирать такие наборы долго, поэтому переведём их в объект, который считать умеем.

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

Каждой раскладке отвечает ровно одна такая картинка, и каждой картинке — ровно одна раскладка, поэтому считать можно картинки. В ряду $8 + 3 = 11$ позиций, и картинка полностью задаётся тем, на каких трёх из них стоят перегородки:

$$N = \binom{11}{3} = \frac{11 \cdot 10 \cdot 9}{1 \cdot 2 \cdot 3} = 165$$
Проверка на маленьком случае

Две конфеты по трём коробкам: раскладок шесть — 200, 020, 002, 110, 101, 011. Формула даёт $\binom{2 + 3 - 1}{2} = \binom{4}{2} = 6$. Сходится. Это та же проверка, что делалась руками в разминочной задаче w0101, только теперь она нужна как страховка, а не как счёт.

Общий вид

Разложить $k$ одинаковых объектов по $n$ различным ящикам — то же самое, что выбрать $k$ объектов из $n$ типов с повторениями, и то же самое, что выписать неубывающую последовательность длины $k$ из $n$ символов: $\binom{n + k - 1}{k}$. Финальная задача дня про неубывающие цифры — этот же вопрос в другой одежде.

EN

A distribution is a quadruple of nonnegative integers $x_1, x_2, x_3, x_4$, where $x_i$ is the number of candies in box $i$, subject only to

$$x_1 + x_2 + x_3 + x_4 = 8$$

Listing these quadruples would be tedious, so encode them as an object that we know how to count.

Place eight identical objects in a row and insert three dividers. Objects to the left of the first divider go into the first box, those between the first and second dividers into the second box, and so on. Dividers may be adjacent or placed at either end; these are precisely the cases in which some boxes are empty.

Every distribution corresponds to exactly one diagram, and every diagram to exactly one distribution. The row has $8 + 3 = 11$ positions and is completely determined by the three positions occupied by dividers:

$$N = \binom{11}{3} = \frac{11 \cdot 10 \cdot 9}{1 \cdot 2 \cdot 3} = 165$$
Check a small case

For two candies and three boxes, the six distributions are 200, 020, 002, 110, 101, 011. The formula gives $\binom{2 + 3 - 1}{2} = \binom{4}{2} = 6$. This agrees with the direct check in warm-up problem w0101; here the check is a safeguard rather than the main method.

General form

Distributing $k$ identical objects among $n$ distinct boxes is equivalent to choosing $k$ objects from $n$ types with repetition, or to writing a nondecreasing sequence of length $k$ over $n$ symbols. The count is $\binom{n + k - 1}{k}$. The final problem about nondecreasing digits is the same question in different clothing.

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

Сколько натуральных чисел от 1 до 200 включительно не делятся ни на 4, ни на 6?

EN

How many positive integers from 1 through 200 are divisible by neither 4 nor 6?

верно
Подсказка / Hint
RU

Считай запрещённые числа — те, что делятся хотя бы на один из двух делителей, — и вычитай. Осторожно с пересечением: «делится и на 4, и на 6» — это не «делится на 24».

EN

Count the forbidden integers—those divisible by at least one of the two divisors—and subtract. Be careful with the intersection: “divisible by both 4 and 6” does not mean “divisible by 24.”

Решение / Solution
RU

Пусть $A_4$ — числа от 1 до 200, делящиеся на 4, а $A_6$ — делящиеся на 6. Запрещены числа из объединения $A_4 \cup A_6$.

$$|A_4| = \left\lfloor \tfrac{200}{4} \right\rfloor = 50, \qquad |A_6| = \left\lfloor \tfrac{200}{6} \right\rfloor = 33$$

Пересечение — это числа, делящиеся одновременно на 4 и на 6, то есть кратные наименьшему общему кратному: НОК$(4, 6) = 12$. Перемножать делители нельзя — четвёрка и шестёрка не взаимно просты.

$$|A_4 \cap A_6| = \left\lfloor \tfrac{200}{12} \right\rfloor = 16$$

Плохих чисел

$$|A_4 \cup A_6| = 50 + 33 - 16 = 67$$

и остаётся

$$N = 200 - 67 = 133$$
Где теряют эту задачу

Написать $\lfloor 200/24 \rfloor = 8$ вместо 16 — самая частая ошибка места. Произведение делителей годится только тогда, когда они взаимно просты; в общем случае пересечение задаётся наименьшим общим кратным.

Проверка периодом

Картинка делимости повторяется с периодом 12. В каждой дюжине подряд идущих чисел кратны четырём три, кратны шести два, кратно и тому и другому одно, значит плохих $3 + 2 - 1 = 4$, а хороших восемь. В 200 числах помещается 16 полных дюжин (это 192 числа) и хвост 193, ..., 200, в котором плохие — 196, 198 и 200, то есть хороших пять. Итого $16 \cdot 8 + 5 = 133$. Сходится.

EN

Let $A_4$ be the set of integers from 1 through 200 divisible by 4, and $A_6$ those divisible by 6. The forbidden integers form $A_4 \cup A_6$.

$$|A_4| = \left\lfloor \tfrac{200}{4} \right\rfloor = 50, \qquad |A_6| = \left\lfloor \tfrac{200}{6} \right\rfloor = 33$$

The intersection consists of integers divisible by both 4 and 6, hence by their least common multiple: $\operatorname{lcm}(4, 6) = 12$. We cannot simply multiply the divisors because 4 and 6 are not coprime.

$$|A_4 \cap A_6| = \left\lfloor \tfrac{200}{12} \right\rfloor = 16$$

Thus the number of forbidden integers is

$$|A_4 \cup A_6| = 50 + 33 - 16 = 67,$$

leaving

$$N = 200 - 67 = 133.$$
The common trap

Writing $\lfloor 200/24 \rfloor = 8$ instead of 16 is the most frequent error. The product of the divisors works only when they are coprime; in general, the intersection is determined by the least common multiple.

Check by periodicity

The divisibility pattern repeats every 12 integers. In each block of twelve consecutive integers, three are divisible by 4, two by 6, and one by both, so $3 + 2 - 1 = 4$ are forbidden and eight are allowed. The first 200 integers contain 16 complete blocks of twelve (192 integers) and the tail 193, ..., 200. The forbidden integers in the tail are 196, 198, and 200, leaving five allowed. Thus $16 \cdot 8 + 5 = 133$, as required.

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

Уровень YMLS

решено 2 из 2

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

Y0101Уровень YMLSступень 4минимумКомбинаторика✓уровень YMLS
RU

Сколько натуральных чисел от 1 до 1000 включительно не делятся ни на 2, ни на 3, ни на 5?

EN

How many positive integers from 1 through 1000 are not divisible by 2, 3, or 5?

верно
Подсказка / Hint
RU

Считай «плохие» числа — те, что делятся хотя бы на одно из трёх. Не забудь про пересечения.

EN

Count the “bad” integers—those divisible by at least one of the three numbers. Remember to account for intersections.

Решение / Solution
RU

Пусть $A_2, A_3, A_5$ — множества чисел, делящихся на 2, 3 и 5.

$$|A_2| = \left\lfloor \tfrac{1000}{2} \right\rfloor = 500, \quad |A_3| = 333, \quad |A_5| = 200$$

Пересечения — это делимость на наименьшее общее кратное, а поскольку 2, 3 и 5 попарно взаимно просты, это просто произведение:

$$|A_2 \cap A_3| = \left\lfloor \tfrac{1000}{6} \right\rfloor = 166, \quad |A_2 \cap A_5| = 100, \quad |A_3 \cap A_5| = 66$$$$|A_2 \cap A_3 \cap A_5| = \left\lfloor \tfrac{1000}{30} \right\rfloor = 33$$

По включениям-исключениям:

$$|A_2 \cup A_3 \cup A_5| = 500 + 333 + 200 - 166 - 100 - 66 + 33 = 734$$$$N = 1000 - 734 = 266$$
Проверка за 15 секунд

Доля «хороших» чисел должна быть примерно $\left(1 - \tfrac12\right)\left(1 - \tfrac13\right)\left(1 - \tfrac15\right) = \tfrac{4}{15} \approx 0.267$, то есть около 267 штук. Получили 266 — сходится. Такая прикидка ловит ошибку в знаках, а стоит она полминуты.

EN

Let $A_2, A_3, A_5$ be the sets of integers divisible by 2, 3, and 5, respectively.

$$|A_2| = \left\lfloor \tfrac{1000}{2} \right\rfloor = 500, \quad |A_3| = 333, \quad |A_5| = 200$$

Intersections are determined by least common multiples. Since 2, 3, and 5 are pairwise coprime, those least common multiples are simply products:

$$|A_2 \cap A_3| = \left\lfloor \tfrac{1000}{6} \right\rfloor = 166, \quad |A_2 \cap A_5| = 100, \quad |A_3 \cap A_5| = 66$$$$|A_2 \cap A_3 \cap A_5| = \left\lfloor \tfrac{1000}{30} \right\rfloor = 33$$

By inclusion-exclusion,

$$|A_2 \cup A_3 \cup A_5| = 500 + 333 + 200 - 166 - 100 - 66 + 33 = 734$$$$N = 1000 - 734 = 266$$
A 15-second sanity check

The proportion of allowed integers should be approximately $\left(1 - \tfrac12\right)\left(1 - \tfrac13\right)\left(1 - \tfrac15\right) = \tfrac{4}{15} \approx 0.267$, or about 267 integers out of 1000. We obtained 266, which is consistent. This quick estimate catches sign errors in inclusion-exclusion.

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

Сколько существует шестизначных чисел, у которых цифры идут в неубывающем порядке (каждая следующая цифра не меньше предыдущей)?

EN

How many six-digit integers have digits in nondecreasing order, meaning that each digit is at least as large as the preceding one?

верно
Подсказка / Hint
RU

Сначала пойми, может ли в таком числе встретиться ноль. Потом: число задаётся не порядком цифр, а тем, сколько раз каждая цифра встречается.

EN

First decide whether 0 can appear. Then observe that the number is determined not by a choice of order, but by how many times each digit occurs.

Решение / Solution
RU

Шаг 1. Ноль невозможен. Если бы в числе была цифра 0, то при неубывающем порядке она стояла бы первой — а шестизначное число не может начинаться с нуля. Значит все цифры из $\{1, 2, \ldots, 9\}$.

Шаг 2. Порядок не нужно выбирать. Как только мы решили, сколько раз берём каждую цифру, само число восстанавливается однозначно — цифры обязаны идти по возрастанию. Значит выбор сводится к вопросу: сколько раз взять каждую из девяти цифр, если всего цифр шесть?

Шаг 3. Шары и перегородки. Это число решений уравнения

$$x_1 + x_2 + \cdots + x_9 = 6, \qquad x_i \ge 0$$

Представим шесть единиц в ряд и восемь перегородок, делящих их на девять групп. Всего позиций $6 + 8 = 14$, выбираем, на каких восьми стоят перегородки:

$$N = \binom{14}{8} = \binom{14}{6} = 3003$$
Сочетания с повторениями

Выбрать $k$ объектов из $n$ типов, когда повторы разрешены, а порядок не важен:

$$\binom{n + k - 1}{k}$$

Здесь $n = 9$ типов цифр, $k = 6$ позиций: $\binom{14}{6} = 3003$.

EN

Step 1. Zero is impossible. If 0 occurred, nondecreasing order would force it to be the first digit, but a six-digit integer cannot begin with zero. Thus every digit belongs to $\{1, 2, \ldots, 9\}$.

Step 2. There is no order to choose. Once we decide how many times each digit occurs, the number is uniquely determined because its digits must appear in nondecreasing order. The problem therefore asks how many times to use each of nine digits when there are six digits total.

Step 3. Stars and bars. We count the solutions of

$$x_1 + x_2 + \cdots + x_9 = 6, \qquad x_i \ge 0.$$

Represent the six units in a row and use eight dividers to split them into nine groups. There are $6 + 8 = 14$ positions; choose the eight occupied by dividers:

$$N = \binom{14}{8} = \binom{14}{6} = 3003$$
Combinations with repetition

The number of ways to choose $k$ objects from $n$ types when repetition is allowed and order does not matter is

$$\binom{n + k - 1}{k}.$$

Here $n = 9$ digit types and $k = 6$ positions, giving $\binom{14}{6} = 3003$.

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

Уровень ШАД

решено 0 из 1

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

S0101Уровень ШАДступень 4КомбинаторикаЭкзамен ШАД 2024, задача D «Координаты в квадрате»
RU

На клетчатой бумаге нарисован квадрат $n \times n$ по линиям сетки. Левая нижняя клетка имеет координаты $(1,1)$, правая верхняя — $(n,n)$. Внутри него по линиям сетки рисуют квадрат $(n-1) \times (n-1)$, внутри того — квадрат $(n-2) \times (n-2)$, и так далее, пока не получится квадрат $1 \times 1$. Он оказался клеткой с координатами $(x, y)$.

Сколько существует различных последовательностей квадратов с таким свойством? Дайте ответ для $n = 10$, $x = 4$, $y = 7$.

EN

An $n \times n$ square is drawn along the grid lines of graph paper. The bottom-left cell has coordinates $(1,1)$ and the top-right cell has coordinates $(n,n)$. Inside it, an $(n-1) \times (n-1)$ square is drawn along the grid lines; inside that, an $(n-2) \times (n-2)$ square is drawn, and so on until a $1 \times 1$ square remains. The final square is the cell with coordinates $(x, y)$.

How many different sequences of squares have this property? Give the answer for $n = 10$, $x = 4$, and $y = 7$.

Подсказка / Hint
RU

Как из квадрата $k \times k$ получается квадрат $(k-1) \times (k-1)$? Сколько у этого шага независимых решений?

EN

How can a $(k-1) \times (k-1)$ square be obtained from a $k \times k$ square? How many independent choices does each step involve?

Решение / Solution
RU

Ключевое наблюдение. Квадрат $(k-1) \times (k-1)$ помещается внутрь квадрата $k \times k$ ровно четырьмя способами: нужно отрезать один столбец — левый или правый — и одну строку — верхнюю или нижнюю. Причём отрезания столбцов и строк независимы.

Всего шагов $n - 1$. На каждом шаге мы отрезаем один столбец (слева или справа) и одну строку (сверху или снизу).

Столбцы. Закодируем историю отрезаний столбцов строкой из $n-1$ символов: Л, если на этом шаге отрезали левый столбец, П — если правый. Если за все $n-1$ шагов слева отрезали $x - 1$ столбец, то финальная клетка имеет первую координату $x$. Строк с ровно $x-1$ буквой Л ровно $\binom{n-1}{x-1}$ — вопрос снова свёлся к «на каких местах стоят символы одного вида».

Строки. Аналогично: $\binom{n-1}{y-1}$.

Любая комбинация даёт свою последовательность, поэтому перемножаем:

$$N = \binom{n-1}{x-1}\binom{n-1}{y-1}$$

Подставляем $n = 10$, $x = 4$, $y = 7$:

$$\binom{9}{3}\binom{9}{6} = 84 \cdot 84 = 7056$$
Что здесь стоит забрать

Приём разделения на независимые оси. Задача выглядела как перебор вложенных квадратов, а свелась к двум независимым строкам — «в каком порядке отрезали столбцы» и «в каком порядке отрезали строки». Как только удаётся расщепить задачу на независимые части, ответ становится произведением. Этот ход встретится ещё много раз.

EN

Key observation. A $(k-1) \times (k-1)$ square can be placed inside a $k \times k$ square in exactly four ways: remove either the left or the right column, and either the top or the bottom row. The choices for rows and columns are independent.

There are $n - 1$ steps in total. At each step, one column (left or right) and one row (top or bottom) are removed.

Columns. Encode the history of column removals by a string of $n-1$ symbols: L if the left column was removed at that step and R if the right column was removed. The final cell has first coordinate $x$ exactly when a total of $x - 1$ columns were removed from the left. The number of strings with exactly $x-1$ occurrences of L is $\binom{n-1}{x-1}$; once again, the problem reduces to choosing the positions occupied by one type of symbol.

Rows. Similarly, there are $\binom{n-1}{y-1}$ possible row-removal histories.

Every pair of histories gives a distinct sequence of squares, so we multiply:

$$N = \binom{n-1}{x-1}\binom{n-1}{y-1}$$

Substituting $n = 10$, $x = 4$, and $y = 7$ gives

$$\binom{9}{3}\binom{9}{6} = 84 \cdot 84 = 7056$$
Main takeaway

Split the problem along independent axes. What looked like a search through nested squares becomes two independent strings: the order in which columns were removed and the order in which rows were removed. Whenever a problem splits into independent parts, the total count is the product of the counts for those parts. This technique will return often.

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

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

20 минут

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

Y0103Уровень YMLSступень 4минимумКомбинаторика✓уровень YMLS
RU

Десять человек распределяют по четырём группам, у которых есть номера: в группу №1 попадают три человека, в группу №2 — три человека, в группу №3 — два, в группу №4 — два. Размеры закреплены за номерами именно так, менять их местами нельзя. Два распределения считаются разными, если хотя бы один человек попал в группы с разными номерами. Сколькими способами это можно сделать?

EN

Ten people are assigned to four numbered groups. Group 1 must contain three people, group 2 three people, group 3 two people, and group 4 two people. These sizes are fixed for the stated group numbers and may not be swapped. Two assignments are different if at least one person is placed in groups with different numbers. How many assignments are possible?

верно
Подсказка / Hint
RU

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

EN

Choose the membership of the groups in order, beginning with group 1. Remember that groups of the same size are still distinguished by their numbers.

Решение / Solution
RU

Группы пронумерованы, то есть различимы: «Петя в группе №1» и «Петя в группе №2» — разные исходы, хотя обе группы состоят из трёх человек.

Выбираем состав каждой группы по очереди. Для группы №1 берём 3 человек из 10, для группы №2 — 3 из оставшихся 7, для группы №3 — 2 из оставшихся 4, в группу №4 попадают последние двое:

$$N = \binom{10}{3}\binom{7}{3}\binom{4}{2}\binom{2}{2} = 120 \cdot 35 \cdot 6 \cdot 1 = 25\,200$$

То же самое короче — мультиномиальный коэффициент:

$$\frac{10!}{3!\,3!\,2!\,2!} = 25\,200$$
Развилка, на которой теряют задачу

Если бы группы были неразличимы — «разбить на компании по 3, 3, 2 и 2 человека» без номеров, — пришлось бы дополнительно поделить на $2!$ (перестановки двух троек между собой) и ещё на $2!$ (двух двоек), и ответ был бы $25\,200 / 4 = 6300$. Одно слово в условии меняет ответ вчетверо, поэтому оно вынесено в условие явно, а не подразумевается.

EN

The groups are numbered and therefore distinct: “Petya is in group 1” and “Petya is in group 2” are different outcomes, even though both groups have three members.

Choose the membership of each group in sequence. For group 1 choose 3 of the 10 people; for group 2 choose 3 of the remaining 7; for group 3 choose 2 of the remaining 4; the final two people go into group 4:

$$N = \binom{10}{3}\binom{7}{3}\binom{4}{2}\binom{2}{2} = 120 \cdot 35 \cdot 6 \cdot 1 = 25\,200$$

Equivalently, use the multinomial coefficient:

$$\frac{10!}{3!\,3!\,2!\,2!} = 25\,200$$
The decision point that often costs the problem

If the groups were indistinguishable—if we were merely partitioning the people into groups of sizes 3, 3, 2, and 2 with no labels—we would also divide by $2!$ for swapping the two groups of three and by another $2!$ for swapping the two groups of two. The answer would then be $25\,200 / 4 = 6300$. A single word in the statement changes the answer by a factor of four, which is why it is stated explicitly rather than left implicit.

уверенность1 — угадал, 5 — уверен полностью
день закрыт, когда
По тексту любой сегодняшней задачи за 30 секунд говоришь вслух: важен ли порядок, разрешены ли повторы, различимы ли объекты — и называешь один из пяти приёмов дняFor any problem today, say aloud within 30 seconds whether order matters, repetitions are allowed, and objects or groups are distinguishable—and name one of the five techniques
Считаешь $\binom{n}{k}$ для $n \le 20$ устно через убывающие множители, беря меньшее из $k$ и $n-k$; на $\binom{12}{4}$ уходит не больше 15 секундCompute $\binom{n}{k}$ for $n \le 20$ mentally using descending factors, choosing the smaller of $k$ and $n-k$; compute $\binom{12}{4}$ in no more than 15 seconds
Увидев «хотя бы один», «ни одного» или «не делится ни на», начинаешь с подсчёта запрещённого и правильно записываешь сам запрет: b0108 и b0105 решены этим ходом без разбораWhen you see “at least one,” “none,” or “divisible by neither,” begin by counting the forbidden set and state it correctly; solve b0108 and b0105 this way without case enumeration
Увидев «сколько раз взяли каждый тип», «цифры не убывают» или одинаковые объекты по разным ящикам, за 15 секунд рисуешь $k$ шаров и $n-1$ перегородку и пишешь $\binom{n+k-1}{k}$; y0102 решена без подсказкиWhen you see “how many times each type,” “nondecreasing digits,” or identical objects in different boxes, draw $k$ balls and $n-1$ dividers within 15 seconds and write $\binom{n+k-1}{k}$; solve y0102 without a hint
Все четыре обязательные задачи (b0104, b0105, b0106, b0107) решены без подсказки и без разбораSolve all four required problems (b0104, b0105, b0106, b0107) without hints or solutions
Мини-тест y0103 сдан за 20 минут с первого ввода, и ты можешь сказать, во сколько раз изменился бы ответ, если бы группы были неразличимыSubmit mini-test y0103 within 20 minutes on the first attempt, and explain by what factor the answer would change if the groups were indistinguishable
аудит дня
RU

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

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

EN

Separate errors into two types and log each one. Type 1: you chose the wrong technique—you misread order, repetition, or group distinguishability, or missed an “at least” phrase. Type 2: you chose the right technique but the answer still failed—arithmetic, a missing factor, a forgotten multiplicity, or an intersection counted with a product instead of an LCM.

The diagnoses are different. Type 1 is treated with triggers; Type 2 with the five checks at the end of the lesson. If you make more than two Type 1 errors today, spend tomorrow’s first 15 warm-up minutes rereading the trigger block instead of reviewing flashcards.