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

  • 305 — ищет все посты, содержащие 305, найдет посты про Раунд 305
  • andrew stankevich contests — можно писать сразу много слов, будут искаться все
  • user:mikemirzayanov title:сазанка — ищет все посты в названии со словом "сазанка" авторства MikeMirzayanov
  • "vk cup" — можно использовать кавычку, чтобы искать точные совпадения
  • title:educational — искать в названии

Результаты

1.
Автор Rhodoks, история, 4 года назад, По-английски
Codeforces Round #810 Editorial Sorry for the late editorial. May this editorial help you. If you have questions, feel free to ask. [problem:1711A] <spoiler summary="hint1."> The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). </spoiler> <spoiler summary="solution"> Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$. </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; } ~~~~~ </spoiler> [problem:1711B] <spoiler summary="hint1."> See the party as a graph. </spoiler> <spoiler summary="hint2."> Divide the vertices into two categories according to their degrees' parity. </spoiler> <spoiler summary="solution"> Let's consider ...
the number of edges whose both endpoints are deleted. In particular, there must be at least two

Полный текст и комментарии »

Разбор задач Codeforces Round 810 (Div. 1)
Разбор задач Codeforces Round 810 (Div. 2)
  • Проголосовать: нравится
  • +3132
  • Проголосовать: не нравится

2.
Автор MikeMirzayanov, 6 лет назад, По-английски
Goodbye 2020. Hello 2021! <img src="/predownloaded/f4/1f/f41ff0beb745fb2f84a55d9f2cc451273efc6267.jpg" style="width:300px; float:right; margin: 0 1em 1em 1em"/> Hello Codeforces! This unusual and difficult 2020 has come to an end! What will the new year be like? I wish all of us that we have the opportunity to meet in person so that the contests take place not only online. I ask you to think of something important and good. Let this wish come true! We have had a large number of rounds this year. I hope we have pleased you with interesting problems. Thanks to the round coordinators and writers! You make our community richer. Please make us happy in 2021! I wish the participants victories over yourself (and over problems!) and development of your skills, interest and curiosity! Hello, 2021! And we have traditional gifts! #### <img src="https://assets.codeforces.com/images/wand.png"/> Change Handle Feature Hurry! Only until the 10th of January, you can change your handle (<b>but only onc...
and good. Let this wish come true! We have had a large number of rounds this year. I hope we, We have had a large number of rounds this year. I hope we have pleased you with interesting

Полный текст и комментарии »

  • Проголосовать: нравится
  • +2135
  • Проголосовать: не нравится

3.
Автор MikeMirzayanov, 10 лет назад, По-русски
Codeforces: summing up 2016 year <center> <img src="http://assets.codeforces.com/images/Happy-New-Year-HD-Wallpapers.jpg"/> </center> Somehow it turns out that for me, each coming the New Year means more and more. This is an excellent opportunity to take stock, to breathe fresh air and to go through a kind of catharsis. This is a rare opportunity to be with the family, dress up in Santa Claus and just have fun. Holidays give me a clear criterion that I do the right things. If during the holidays, I begin to think about it, to recall some deferred ideas, eager to implement something new. So I’m doing right things. My things. And now exactly the same as in several recent years: during New Year holidays I write code for Codeforces, trying new technology or simply I’m making minor changes in testlib. It is necessary to me: at this moment are no deadlines, do not press the obligation. Just now, at 3 am, I can not break away from being able to do something new. I would like to take a moment and realize that spun in ...
load become higher, large number of improvements have been made in the backend of the system, this, short, we have a fun live. The system load become higher, large number of improvements have been made

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1405
  • Проголосовать: не нравится

4.
Автор EvenImage, история, 7 лет назад, По-английски
A problem collection of ODE and differential technique ##A problem collection of ODE and differential technique *This problem might be well-known in some countries, but how do other countries learn about such problems if nobody poses them.* For those who are interested in well-known problems in China. Thank [user:Elegia,2020-04-23] and [user:djq_cpp,2020-04-23] for developing this technique. Thank [user:tEMMIE.w.,2020-04-23] for reviewing this article. ####[Chain Reaction](http://uoj.ac/problem/50) in UOJ Round 3 By [user:vfleaking,2020-04-23] **Statement** ​ You are given a set $A$, you need to compute $g_{i} = \frac{1}{2} \sum_{j,k}{i-1 \choose j}{i-1-j \choose k} g_jg_k$ where $i-1-j-k \in A$. **Solution** ​ Let the EGF of $g$ be $x(t)$ and EGF of $A$ be $a(t)$. Thus $x'(t)=\frac{1}{2} a(t) x^2(t)+1$. We can solve this equation by D&C and FFT in $O(n\log^2 n)$. But there is a <s>slower</s> solution in $O(n\log n)$. ​ For a polynomial equation $f(x(t))=0$, we can use the Newton's method to solve it. If we find ...
/1096/G), or computing Catalan numbers, [Large Schröder numbers](http://oeis.org/A006318). Also, we, ://codeforces.com/problemset/problem/1096/G), or computing Catalan numbers, [ Large Schröder numbers](http://oeis.org

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1044
  • Проголосовать: не нравится

5.
Автор MikeMirzayanov, история, 20 месяцев назад, По-английски
My Reply on "Mike, please stop ignoring your userbase" This is a response to [this post](https://codeforces.me/blog/entry/141442). Originally, I intended to leave it as a comment, but the text turned out to be quite long. So I decided to publish it as a separate post. Hi! Let me start with the main idea: I don't think I ignore too many issues (though I do ignore some). In most cases, I do work on them, but these days I just don't feel like writing about it. That kind of communication takes a lot of energy &mdash; which I currently don't have. Oh, it looks like you edited the beginning of the blog, and now it triggers less of an internal protest in me. Honestly, lately I've been in a difficult emotional state, and I just don't have the energy or desire to interact much. It's not just about Codeforces &mdash; it's generally harder for me to engage than it used to be. I won't go into details (health, relocation, family issues, changes in the nature of my work due to bots) &mdash; all of that affects my mental state and willingne...
wouldn't solve the problem — there are large pools of phone numbers available for rent that attackers, . These bots aren't simple scripts — they're part of large-scale, organized operations. Some

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1425
  • Проголосовать: не нравится

6.
Автор Geothermal, история, 7 лет назад, По-английски
Remove Virtual Contestants from Contest Leaderboards As most of you are likely aware, cheating in virtual contests (typically by submitting prewritten or copied solutions in order to appear at the top of the leaderboard) is very common. Most recently, [user:wannabecandidatemaster,2020-05-28] submitted solutions to all problems in [this round](https://codeforces.me/contest/1358/standings) in order to take first place in the standings, and [user:bemandrei,2020-05-28] competed virtually in [this round](https://codeforces.me/contest/1360/standings) after competing in the round officially, and ended up in second place on the leaderboard. In response to the rise of VC cheating (as well as some other issues with the VC system I'll describe below), I'd like to make a simple proposal: **Remove all virtual participants from the contest leaderboards.** The one exception is that you should see your own name on leaderboards for contests you VCed (that is, virtual contestants should be visible only to themselves). Similarly, virtual participan...
compete officially, so it has an exceptionally broad scope and affects a large number of users., , so it has an exceptionally broad scope and affects a large number of users. Second, and more

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1001
  • Проголосовать: не нравится

7.
Автор -is-this-fft-, история, 5 лет назад, По-английски
[Tutorial] Collection of little techniques #### Introduction There are a number of "small" algorithms and facts that come up again and again in problems. I feel like there I have had to explain them many times, partly because there are no blogs about them. On the other hand, writing a blog about them is also weird because there is not that much to be said. To settle these things "once and for all", I decided to write my own list about about common "small tricks" that don't really warrant a full tutorial because they can be adequately explained in a paragraph or two and there often isn't really anything to add except for padding. This blog is partly inspired by [user:adamant,2022-03-15]'s [blog](48417) from a few years ago. At first, I wanted to mimic adamant's blog structure exactly, but I found myself wanting to write longer paragraphs and using just bolded sentences as section headers got messy. Still, each section is short enough that it would not make much sense to write separate blogs about each of these things. A...
counting the number of ways), we can use a variation of this trick. We will still count thenumber of, #### Introduction There are a number of "small" algorithms and facts that come up again and, The number of times line 8 is hit must therefore be no larger than the number of different pairs of, ~~~~~ 1 for k in 1..MAX_A: 2 # cnt_multiples[k] is the number of multiples of k in the array

Полный текст и комментарии »

  • Проголосовать: нравится
  • +804
  • Проголосовать: не нравится

8.
Автор dario2994, 6 лет назад, По-английски
About Problemsetting (for AtCoder and Codeforces) Since the amount of information available about the preparation of a competitive programming contest for AtCoder/Codeforces is very little, I decided to collect here what was my experience. I will try to both describe my experiences and give some general advice to wannabe problemsetters. I hope that this will be useful to future problemsetters who are "out of the loop". Moreover, participants might be curious to know what happens behind the scenes (and maybe the platforms may consider this as a form of constructive feedback). *Acronyms*: - AGC = Atcoder Grand Contest - GR = Codeforces Global Round ### Why I know something about problemsetting? I am in the competitive programming world since ~8 years: I have participated in IOI/ICPC/GCJ and a number of contests on AtCoder/Codeforces (and lately Codechef). I am not a top participant but, being in this world for so long, I know, more or less, all the standard tricks. Recently, I was the author of the *flagship conte...
coordinator). In both cases, I was expecting a large number of questions but the real amount was, mistake in the preparation would have been noticed. For the Global Round there was alarge number of, 1. The number of participants was much larger, which is cool. 2. I was not stressed by the fact, For the Global Round there was a large number of testers. The issue here was that some of the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +936
  • Проголосовать: не нравится

9.
Автор MikeMirzayanov, 8 лет назад, По-русски
Hello, ITMO! <img src="https://assets.codeforces.com/images/itmo-logo.png" style="margin:1em 1em 1em 1em; float:right;"/> Hi Codeforces! For you, perhaps it was yet another Codeforces round. But not for me. [contest:1066] is the first round tested on new judging servers at ITMO University. And this is not just an update of location. Ta-dam! Now your solutions will be judged on the new Intel i3-8100 processors. And this is not all news. The number of judging servers has increased, which means fewer queues during rounds! I am pleased to announce that now I live in St. Petersburg, I work at ITMO, and Codeforces is gradually moving from the walls of dear to me Saratov University to ITMO University. The decision to move was not easy for me. My plan is that, based on ITMO, I can focus more on Codeforces development and work on the platform. The number of world champions per square meter is simply overwhelming, and working with a large team of such enthusiasts (and professionals!) of sports pro...
processors. And this is not all news. The number of judging servers has increased, which means fewer, work on the platform. The number of world champions per square meter is simply overwhelming, and

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1331
  • Проголосовать: не нравится

10.
Автор MikeMirzayanov, 10 лет назад, По-русски
About the Round 382 Good afternoon! I've decided to share my thoughts on the round 382. Of course, it turned upset not only to me, but also to the round coordinator [user:GlebsHP,2016-11-28]. In this round the main negative feedback were caused by two problems: [problem:735D] and [problem:735C]. Regarding [problem:735D]. I do not share the criticism to this problem. In fact, to solve it would be nice to be familiar with <a href="https://en.wikipedia.org/wiki/Goldbach&apos;s_conjecture"> Goldbach's Conjecture</a> and better with <a href="https://en.wikipedia.org/wiki/Prime_number_theorem">Prime Number Theorem</a>. These facts are medium-popular in the world of programming contests. Familiarity with them is useful, gives useful insight into primes. It is important: in this problem it was necessary to perform a simple, but nevertheless, additional step to find solution. It seems to me that it's okay to use problems that have a reduction to some popular and semi-popular topics. Otherwise, it is th...
a problem is familiar to somebody. It is important to understand, that huge number of problems have, ratings been updated. Taking into account large number of participants who didn't notice the issue, Taking into account large number of participants who didn't notice the issue, who solved problems

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1288
  • Проголосовать: не нравится

11.
Автор NXIST_buster, история, 6 лет назад, По-английски
Corruption, Cheating at ICPC Yinchuan This blog is about Corruption and Cheating at ICPC YinchuanRegional. ICPC Yinchuan Regional is one of the ICPC regional contests for students competing in the geographic area of Asia East Continent. I. Background: General Info ------------------ Ningxia Institute of Science of Technology, or NXIST is a higher education institute in China. Since 2019, NXIST has held two regional contests. The and both were considered by many participants as jokes, yet until today participants are unaware of the NXIST's extent of evil. Zhihu is a Chinese website similar to Quora, and I will refer to this website for information. II. Background: Before 2021 ------------------ Regional competitions in China consists of two stages: The online selection contest and the onsite regional contest. As there are many contestants in China, the online contest is considered serious and rules are usually strictly enforced, with entire universities where some participant cheats disqualified from attend...
number of places is the number of teams participating in Ningxia, and the competition in Ningxia

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1685
  • Проголосовать: не нравится

12.
Автор Qingyu, 17 месяцев назад, По-английски
About the Universal Cup, the Semifinals, and myself... Hey'all! This gonna be a long post, so let me put an important TLDR here first: we are going to host **The 3rd Universal Cup Semifinals**, which will take place on August 24, 2025 **online**, at [11:00 (UTC)](https://www.timeanddate.com/worldclock/fixedtime.html?msg=The+3rd+Universal+Cup+Semifinals&iso=20250824T19&p1=33&ah=5). This contest will be a part of our Finals Team Selection, which the detailed rules and announcements will be published later next week. --- Now for some extra context, if you're interested. Last week, we hosted the [last online stage](https://codeforces.me/blog/entry/143954) of The 3rd Universal Cup. After that, I posted a [feedback form](https://docs.google.com/forms/d/1g5Txhiirh_lRsvGfkYWRozu0WDDGK31IAXjB7VgeVoM/edit) on our discord server. I received lots of thoughtful responses (P.S — it's still open, so feel free to fill it out if you haven't yet!). I've read through all the feedback, and I'd like to share a few thoughts. ### On the Number...
decent number of new sources, we will consider to open the UCup Olympiad Track. But for now, it’s, Number of Stages Last year, we had 40 stages, which is a huge number, especially compared to the 28

Полный текст и комментарии »

  • Проголосовать: нравится
  • +814
  • Проголосовать: не нравится

13.
Автор neal, 8 лет назад, По-английски
Blowing up unordered_map, and how to stop getting hacked on it C++ has always had the convenient data structures `std::set` and `std::map`, which are tree data structures whose operations take $O(\log n)$ time. With C++11, we finally received a hash set and hash map in `std::unordered_set` and `std::unordered_map`. Unfortunately, I've seen a lot of people on Codeforces get hacked or fail system tests when using these. In this post I'll explain how it's possible to break these data structures and what you can do in order to continue using your favorite hash maps without worrying about being hacked [cut] . So how are they hackable? We always assume hash maps are $O(1)$ per operation (insert, erase, access, etc.). But this depends on a key assumption, which is that each item _only runs into $O(1)$ collisions on average_. If our input data is completely random, this is a reasonable assumption. But this is no longer a safe bet when the input isn't random, especially so if someone is adversarially designing inputs to our code (a.k.a. hacking ph...
can easily generate a large number of different inputs that all collide, thus causing an $O(n^2, hash functions: multiplying by a random large odd number (and overflowing mod $2^64$) is likely, phase). In particular, if they know our hash function, they can easily generate alarge number of, produce a large number of collisions, so the first thing we should do is add some non-determinism

Полный текст и комментарии »

  • Проголосовать: нравится
  • +753
  • Проголосовать: не нравится

14.
Автор lotusblume, 16 месяцев назад, По-английски
Worst-Case Graphs for Maximum Flow Algorithms Maximum flow algorithms are known to perform significantly better in practice than their worst-case time complexities would suggest. So in this blog, I will present graphs on which the following maximum flow algorithms actually achieve their worst-case running time: | Algorithm | Time Complexity | | ----------------------- | ------------------------------ | | Ford-Fulkerson with DFS | $\mathcal{O}\big(m^2 \cdot U)$ | | Edmonds-Karp | $\mathcal{O}\big(n \cdot m^2\big)$ | | Dinic | $\mathcal{O}\big(n^2 \cdot m\big)$ | | DFS with Scaling | $\mathcal{O}\big(m^2 \cdot \log(U)\big)$ | | Dinic with Scaling | $\mathcal{O}\big(n \cdot m \cdot \log(U)\big)$ | | Most Improving Augmenting Paths | $\mathcal{O}\big(m \cdot \log(U) \cdot (m + n \cdot \log(n))\big)$ | | FIFO Preflow Push | $\mathcal{O}\big(n^3\big)$ | | Highest-Label Preflow Push | $\mathcal{O}\big(n^2 \cdot \sqrt{m}\big)$ | Here and in the rest of this blog: - $n =$ number of vertices, ...
Initially a large flow excess is pushed into $p$. All this flow will then be pushed into $a_1$ and, }\big(n^2 \cdot \sqrt{m}\big)$ | Here and in the rest of this blog: - $n =$ number of vertices

Полный текст и комментарии »

  • Проголосовать: нравится
  • +927
  • Проголосовать: не нравится

15.
Автор maomao90, 3 года назад, По-английски
Editorial for Hello 2024 ### [problem:1919a] Author: [user:maomao90,2024-01-02] <spoiler summary="Hint 1"> When does the game end? </spoiler> <spoiler summary="Solution"> Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choices will still be valid. The only way that the game ends is when both players have $0$ coins. Since each operation decreases the total amount of coins by exactly $1$, the only way for Alice to win the game is if $a + b$ is odd. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if ((a + b) % 2 == 0) { cout << "Bob\n"; } else { cout << "Alice\n"; } } ...
$(-1, 1)$ into the array to fix the number of occurrences of prefix sum starting from the largest value, values of $p_1 \le s \le p_n$ and sum up the number of ways for each possible sum.

Полный текст и комментарии »

Разбор задач Hello 2024
  • Проголосовать: нравится
  • +760
  • Проголосовать: не нравится

16.
Автор parveen1981, история, 5 лет назад, По-английски
I compiled a list of almost all useful blogs ever published on Codeforces [update: till 09.06.2021] <h3 style="color:red">If there are any blogs that I have missed, please tell in the comment section. Thank you.</h3> # Mathematics Stuff - [Number Theory in Competitive Programming [Tutorial]](https://codeforces.me/blog/entry/46620) - [Number of points on Convex hull with lattice points](https://codeforces.me/blog/entry/62183) - [FFT, big modulos, precision errors.](https://codeforces.me/blog/entry/48465) - [Number of ways between two vertices](https://codeforces.me/blog/entry/19078) - [Mathematics For Competitive Programming](https://codeforces.me/blog/entry/76938) - [FFT and NTT](https://codeforces.me/blog/entry/19862) - [Burnside Lemma](https://codeforces.me/blog/entry/51272) - [Number of positive integral solutions of equation 1/x+1/y=1/n!](https://codeforces.me/blog/entry/76836) - [On burnside (again)](https://codeforces.me/blog/entry/64860) - [Simple but often unknown theorems/lemmas/formula? Do you know?](https://codeforces.me/blog/entry/55912) - [Probabili...
Implementation](https://codeforces.me/blog/entry/67149) - [[Insight] Number of Topological Orderings of a, . Thank you. # Mathematics Stuff - [Number Theory in Competitive Programming [Tutorial

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1500
  • Проголосовать: не нравится

17.
Автор adamant, история, 19 месяцев назад, По-английски
Complex FFT is not as bad as you think ... Probably. Hi everyone! As some of you _might_ already know, I don't like NTT. Primary reasons for this are: - I don't like modular arithmetic optimizations (Montgomery, etc). - I don't like NTT mods, and prefer good, old $10^9+7$. - I do like algebra of complex numbers. But, to my regret, the overwhelming mainstream in modern competitive programming is NTT. Primary reasons are: - It's allegedly faster. - It needs less memory. - It has no precision issues. - People don't like algebra of complex numbers. There is nothing I can do about the last, but today I'll address the first 3. Optimizing complex FFT was on my mind for quite some time, but I didn't really work on it _that much_ until the [blog](https://codeforces.me/blog/entry/142063) by [user:Qwerty1232,2025-04-24] on optimizing NTT has dropped, which motivated me to actually put some serious effort into this. In this blog, we will primarily focus on optimizations that are specific to complex arithmetic...
[Convolution (Large)](https://judge.yosupo.jp/problem/convolution_mod_large) with complex FFT in **[2393, dedup solutions by same authors). - I was finally able to get AC on [Convolution (Large)](https, resulting numbers would be up to $nM \approx 5.24 \cdot 10^{14}$, which is still quitelarge, but at, If we look just on how large the numbers can be in the output, the trivial estimate would be $n C^2

Полный текст и комментарии »

  • Проголосовать: нравится
  • +731
  • Проголосовать: не нравится

18.
Автор zscoder, история, 10 лет назад, По-английски
[Tutorial] Non-trivial DP Tricks and Techniques Hi everyone! Today I want to share some DP tricks and techniques that I have seen from some problems. I think this will be helpful for those who just started doing DP. Sometimes the tutorials are very brief and assumes the reader already understand the technique so it will be hard for people who are new to the technique to understand it. Note : You should know how to do basic DP before reading the post DP + Bitmasks ------------------ This is actually a very well-known technique and most people should already know this. This trick is usually used when one of the variables have very small constraints that can allow exponential solutions. The classic example is applying it to solve the Travelling Salesman Problem in $O(n^{2} \cdot 2^{n})$ time. We let $dp[i][j]$ be the minimum time needed to visit the vertices in the set denoted by $i$ and ending at vertex $j$. Note that $i$ will iterate through all possible subsets of the vertices and thus the number of states is $O(2^{n} \cdo...
dimensions of the grid is too large here. Note that the number of blocked cells is not toolarge, letter 'S' and large numbers with the letter 'L'. For each L, it increases the number of inversions by, How do we count this value? We'll count the number of such tuples where each element is positive, Note that the number of blocked cells is not too large though, so we can try to dp on them. Let $S

Полный текст и комментарии »

  • Проголосовать: нравится
  • +612
  • Проголосовать: не нравится

19.
Автор MikeMirzayanov, история, 11 лет назад, По-русски
How to come up with the solutions: techniques As I work with students I often face the situation when if a problem doesn't seem clear to a student at the first sight, it makes them unable to solve it. Indeed, you always hear about specific methods and techniques. But you don't hear about how to think in order to apply them. In this note I'll try to sum up my experience of solving programming contest problems. However, some pieces of advice will also be applicable for olympiads in mathematics and your first steps in academic research. So you've read a problem and you don't know how to solve it. Try the following techniques, some of them can often come handy. ##### Technique 1: "Total Recall" Try to remember some similar problems that you had to solve. Quite many problems do not have a brand new idea. So probably, you can use your experience of solving a similar problem to solve this one. ##### Technique 2: "From Specific to General" Let's say that you've found the solution for the problem (hurray!). Let's consider ...
solution always exists; * item the number of states isn't large. ##### Technique 4: "To solve a, solving a problem, generate answers for a large number of tests on large limits and meditate on, * the solution always exists; * item the number of states isn't large.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +731
  • Проголосовать: не нравится

20.
Автор Yandex, 7 лет назад, По-русски
Happy Birthday, Codeforces! Dear Codeforces, <img src="/predownloaded/32/a6/32a6b841dd1f306d9f2f1b232ef710ed9a27c350.jpeg" style="float:right; margin:0 1em 1em 1em;"/> Happy 10th anniversary from Yandex! Over the past ten years, you have become more than just a platform for competitions having developed into a community hub where people can socialize, discuss interesting tasks and make useful contacts — a large part of life for every competitive programmer. Keep it up – continue growing and developing! Codeforces, with its immense contribution to competitive programming, is very important to the entire community of sport programmers around the world. Yandex actively supports programming contests and competitions and appreciates what Codeforces does, having benefitted from a large number of talented employees with a background in competitive programming. It wouldn’t be the same without this community. We would also like to use this opportunity to thank [user:MikeMirzayanov,2020-04-01] for Polygon, which ...
and competitions and appreciates what Codeforces does, having benefitted from a large number of, competitions and appreciates what Codeforces does, having benefitted from a large number of talented employees

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1417
  • Проголосовать: не нравится

21.
Автор dario2994, 6 лет назад, По-английски
Editorial of Global Round 11 #### General comments Broadly speaking, problems A-B-C-D were "div2 problems", while F-G-H were "strong grandmaster problems" (with E staying in the middle). I did not expect anyone to solve all the problems and thus I decided to give the scoring F+G=H (so that maybe someone would have solved H). <br><br> Many of the problems (A, C, D, E, G) admit multiple solutions. Sometimes the core of the solution is the same (C, D) and sometimes the solutions are truly different (A, E, G). <br><br> If you are an experienced participant, I would like to hear your opinion on the problems. Feel free to comment on this post or send me a private message. <br><br> <spoiler summary="Overview of the problemset" > The easiest problem of the contest, *A-Avoiding Zero*, is about rearranging an array of numbers. It is intended as a very easy problem that still requires to think. Then, in *B-Chess Cheater* an intuitive (but nontrivial to prove) greedy approach is the way to go. *C-The Hard Work of P...
difference between *D* and *E-Xum* is pretty large. Problem *E* asks to produce thenumber $1, somewhat similar). The difficulty difference between *D* and *E-Xum* is pretty large. Problem *E

Полный текст и комментарии »

Разбор задач Codeforces Global Round 11
  • Проголосовать: нравится
  • +758
  • Проголосовать: не нравится

22.
Автор Geothermal, история, 3 года назад, По-английски
Four Proposals Regarding FSTs While I very much enjoy Codeforces rounds overall, FSTs are by far my least favorite part of the Codeforces contest format. There are two reasons I dislike contests with weak pretests. The first is stylistic: I don't care very much about penalizing people who don't rigorously prove their solutions before submitting (which is the main justification for having weak pretests) and I think it's essentially impossible to FST these solutions without more frequently FSTing contestants who make minor mistakes in their code. (The vast majority of my FSTs are due to this sort of minor glitch rather than an error in the underlying idea). The second is that FSTs introduce an element of hidden information to Codeforces rounds. During a contest, you have no way of knowing whether the authors have written strong pretests. If you act as though the pretests are weak, you will be at a disadvantage if pretests are actually strong (because if you knew pretests are strong, you could have e.g. submit...
a large number of test cases is not especially expensive when a problem receives very few solutions, larger maximal cases (though this is fairly rare because most modern D2As have small inputs andlarge, More generally, running a large number of test cases is not especially expensive when a problem

Полный текст и комментарии »

  • Проголосовать: нравится
  • +502
  • Проголосовать: не нравится

23.
Автор MikeMirzayanov, 10 лет назад, По-русски
For contest writers: proposal tracking system <i>In 2021, some details (including requirements for problem writers) were changed. Read <a href="https://codeforces.me/blog/entry/85259">the link</a> for details.</i> Hello, Codeforces! New year brings changes to the Codeforces team. <a href="/blog/entry/49466">As you probably know</a> [user:GlebsHP,2017-01-04] completed his work as the chief coordinator of Codeforces. Gleb, thanks a lot! You did an excellent job and coordinated a lot of interesting rounds. You're a professional, an interesting person, you have impeccable taste to problems, and you proved to be brilliant and talented writer. Thank you that you were with us! Hope to see your tasks on Codeforces many times again! Nikolay [user:KAN,2017-01-04] Kalinin came to Gleb's place. He is also an experienced participant, Nikolay has already held several rounds as a coordinator. [user:KAN,2017-01-04] seriously engaged in programming contests since he was 12 years old. His major achievements: he won twice All-Russian Scho...
">offered a large number of problems — the chance to give an interest to participants is, ://codeforces.com/contests/writer/MikeMirzayanov">offered a large number of problems — the chance to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +730
  • Проголосовать: не нравится

24.
Автор Ra16bit, история, 5 лет назад, перевод, По-русски
Competitive Programming Hall of Fame — cphof.org Hi Codeforces! Today I'd like to introduce the new [Competitive Programming Hall of Fame](https://cphof.org) project that is available at [cphof.org](https://cphof.org) ![ Logo ](/predownloaded/12/35/1235b4fcce22b33f83cf26221d889087e06d8592.png) #### Background A long time ago I've noticed that there is no single source of information with the results of previously held large programming competitions. Moreover, plenty of older championships don't maintain their websites anymore, and it becomes hard or even impossible to find any details about them, which is pretty sad. So I've decided to create [Competitive Programming Hall of Fame](https://cphof.org). #### About the project Competitive Programming Hall Of Fame is a project created to preserve the history of international championships in competitive programming. This website collects the results of the final stages for both worldwide and regional contests. By international championship we mean a contest consisting ...
noticed that there is no single source of information with the results of previously heldlarge

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1176
  • Проголосовать: не нравится

25.
Автор MikeMirzayanov, 4 года назад, По-английски
About Problem Coincidences Hi. Of course, there was an unpleasant incident with the problem today. In fact, the problem almost coincided with another problem in the old round, which was hosted 5 years ago. You, of course, are shocked. You, of course, think that the round should be unrated. You are wrong. Here's why. [cut] We need to clearly distinguish between two scenarios with coincided problems in our rounds. First. The writer has knowingly plagiarized. This is an outrageous scenario. Such behavior knows no excuse and it is a conscious detriment to our community. Shame on the writer! Second. The problem was matched unintentionally. The writer was unaware of some old problem. This happens. The coordinator had not seen this old problem before or had forgotten it. We are all human. The round was tested, but the testers did not indicate such a coincidence. Too bad, it happens. Who can we blame for this situation? The writer? Most likely, the writer did a lot of work to prepare the ro...
Have you noticed that every Codeforces round has been tested by a much larger number of testers in

Полный текст и комментарии »

  • Проголосовать: нравится
  • +662
  • Проголосовать: не нравится

26.
Автор antontrygubO_o, 7 лет назад, По-английски
On setting D2A and D2B problems Disclaimer: as always, everything in this blog is just my opinion. Some problemsetters don't take easy problems seriously. One very popular opinion is that the D2A-B problems are just stupid implementation exercises intended for beginners to learn how to code. ![ ](https://i.imgur.com/ioTMeKL.png) ![ ](https://i.imgur.com/TJ2IPzb.png) It's true that D2A-B problems are mostly like this on most platforms. This is one of the reasons why a lot of people don't like combined rounds: they think that solving D2A-B problems can't be interesting and just takes time which could be spent on solving fascinating problems of higher level. From point of view of most participants, easy problems just can't be good, because if problem requires some thinking than it's not easy enough for D2A-B level. Easy problems can't be interesting, they say! ![ ](https://i.imgur.com/aRe2p6l.png) ![ ](https://i.imgur.com/wLKlixu.png) This situation really upsets me. This kind of attitude from the ...
After all, the first problems are the ones that the largest number of participants will try to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +515
  • Проголосовать: не нравится

27.
Автор Everule, история, 5 лет назад, По-английски
Essentials of Elementary Number Theory This is a blog starting from the very basics of number theory, in a way that flows fluidly from one concept to another and is based in developing an intuitive feeling for the basics of elementary number theory. This is not a blog to simply gloss over. I consider more of a guided exploration into the world of discovering things in the world of number theory, and I don't expect anyone to immediately understand all the insights in this blog. But if you put an honest effort into discovering how I find these insights you will find much use for my blog. If you do not know some notation or some elementary theorem I use you should refer to this. <spoiler summary="Elementary definitions"> We start with the basic definition that is at the heart of number theory. Let $a \mid b$ (read a divide(s) b) for some $a,b \in \mathbb{Z}$ for some if there exists $k \in \mathbb{Z}$ such that $b = ak$. Similarly $a \not\mid b$ if there does not exist such $k$. If $g \mid a$, then $g \mid ab$. ...
Essentials of Elementary Number Theory, Theorem"> This function is at the heart of most elementary number theory. $\gcd(x,y)$ is defined as the, This is a blog starting from the very basics of number theory, in a way that flows fluidly from one

Полный текст и комментарии »

  • Проголосовать: нравится
  • +308
  • Проголосовать: не нравится

28.
Автор platelet, 3 года назад, По-английски
CodeTON Round 5 Editorial ### [problem:1842A] <spoiler summary="Tutorial"> Let's view it as when monsters $x$ and $y$ fight, their health changes into $\max(x-y,0)$ and $\max(y-x,0)$ respectively. So any monster with $0$ health is considered dead. Therefore, a player loses when the health of his monsters are all $0$. Notice that $\max(x-y,0)=x-\min(x,y)$ and $\max(y-x,0)=y-\min(x,y)$. Therefore, after each step, the sum of the health of monsters decrease by the same amount for both players. Therefore, we only need to know $\sum a_i$ and $\sum b_i$ to determine who wins. If $\sum a_i > \sum b_i$, Tsondu wins. Else if $\sum a_i < \sum b_i$, Tenzing wins. Else, it is a draw. </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int T; cin >> T; while (T--) { int n, m, a[50], b[50]; long long sumA = 0, sumB = 0; cin >> n >> m; for (int i = 0; i < n;...
sorting $y_{1\cdots n}$ from small to large is $y_{p_1},y_{p_2},\cdots,y_{p_n}$, then each permutation $p

Полный текст и комментарии »

  • Проголосовать: нравится
  • +573
  • Проголосовать: не нравится

29.
Автор zscoder, история, 7 лет назад, По-английски
[Tutorial] Generating Functions in Competitive Programming (Part 2) Welcome to Part 2 of my tutorial on generating functions. The [first part](https://codeforces.me/blog/entry/77468) focused on introducing generating functions to those without any background in generating functions. In this post, I will demonstrate a few applications of generating functions in CP problems. Let us start with some relatively straightforward examples. Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually $998244353$). Also, $[n]$ denotes the set $\\{1,2,...,n\\}$. ### Blatant Applications in Counting Problems **Problem.** [AGC 005 Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices. For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T$ which contains all vertices in $S$. For all $1 \le k \le n$, find the sum of $f(S)$ over all subsets $S$ with $|S| = k$. Constraints: $n \le 2 \cdot 10^{5}$. <spoiler summary="Solution"> First, ...
simple form given by the [Pentagonal number theorem](https://en.wikipedia.org/wiki, . For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T

Полный текст и комментарии »

  • Проголосовать: нравится
  • +518
  • Проголосовать: не нравится

30.
Автор -is-this-fft-, история, 4 года назад, По-английски
[Tutorial] FFT If I was a YouTuber, this would be the place where I fill the entire screen with screenshots of people asking me to make this. Anyway, not so long ago I gave a lecture on FFT and now [user:peltorator,2023-01-11] is giving away [free money](https://codeforces.me/blog/entry/110840), so let's bring this meme to completion. In this blog, I am going to cover the basic theory and (competitive programming related) applications of FFT. There is a long list of generalizations and weird applications and implementation details that make it faster. Maybe at some point I'll write about them. For now, let's stick to the basics. **The problem.** Given two arrays $a$ and $b$, both of length $n$. You want to quickly and efficiently calculate another array $c$ (of length $2n - 1$), defined by the following formula. $$c_k = \displaystyle \sum_{i + j = k} a_i \cdot b_j.$$ Solve it in $O(n \log n)$. First of all, why should you care? Because this kind of expression comes up in combinatorics a...
the number of things modulo some large prime. Remember that modulo $p$, some polynomial equations, What about other kinds of number systems? In competitive programming, especially in counting

Полный текст и комментарии »

  • Проголосовать: нравится
  • +436
  • Проголосовать: не нравится

31.
Автор Phantasmagorias, история, 5 лет назад, По-английски
Codeforces Round #745 Editorial I'm very sorry about all the inconvenience, and I would like to bear the blame. Much thanks to those who help me prepare this round. It's not their fault. And much thanks to your participation. [problem:1581A] ------------------ idea: [user:interlude,2021-09-30] preparation: [user:CQXYM,2021-09-30] tutorial: [user:CQXYM,2021-09-30] Assume a permutation $p$, and $\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\forall 1 \leqslant i \leqslant 2n, q_i=2n-p_i$. We can know that $\forall 2 \leqslant i \leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ should be counted. All in all, the half of all the permutaions would be counted in the answer. Thus, the answer is $\frac{1}{2}(2n)!$. The time complexity is $O(\sum n)$. If you precalulate the factors, then the complexity will be $O(t+n)$. ----- <spoiler summary="solution"> ~~~~~ #include<stdio.h> int f[100001]; int m...
the number of periods is less than $\sqrt m$. For the trains of $x+y \leqslant \sqrt m$, thenumber of, +y \leqslant \sqrt m$, the number of the periods can be large. In this case, we set the blocks, each

Полный текст и комментарии »

Разбор задач Codeforces Round 745 (Div. 1)
Разбор задач Codeforces Round 745 (Div. 2)
  • Проголосовать: нравится
  • +799
  • Проголосовать: не нравится

32.
Автор adamant, история, 4 года назад, По-английски
Osijek Competitive Programming Camp 2023 winter Hi everyone! <center><a href="https://ocpc.mathos.unios.hr/index.php"><img src="https://ocpc.mathos.unios.hr/images/ocpc.svg" height="100px"></a></center> I am happy to announce the [Osijek Competitive Programming Camp](https://ocpc.mathos.unios.hr) that is scheduled to happen on **18-26 February 2023** in Osijek, Croatia. The camp is hosted by the [Department of Mathematics at J. J. Strossmayer University of Osijek](https://www.mathos.unios.hr/index.php/en/) and is brought to you by the organizing team of [user:adamant,2022-12-21] (that's me!), [user:-is-this-fft-,2023-01-06], [user:mblazev,2023-01-06], [user:Tomx,2023-01-06] and [user:antontrygubO_o,2023-01-05]. The camp is inspired by various competitive programming camps that we attended during our active years in ICPC, and is aimed to help college students prepare for ICPC regional contests and finals. The camp will consist of 7 ICPC-style contests and 2 days off. Up until now, most top competitive programming training...
desirable for a large number of participants, and we hope to offer a European alternative to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +465
  • Проголосовать: не нравится

33.
Автор errorgorn, 5 лет назад, По-английски
Linear Basis (Xor Basis Extended) As part of the graduation requirements for my school, I have to complete a simple research project, so I decided to do something related to data structure and algorithms. I believe I have come out with a data structure that maintains the basis of vectors in $(\mathbb{Z}/m\mathbb{Z})^d$, where $m$ **may not be prime**. Since this was related to competitive programming, I think it is a good idea to share it here. Hopefully, this algorithm is actually novel :P I would like to thank: - [user:icypiggy,2021-12-26] for being my research mentor and tolerating my dumb questions - [user:rama_pang,2021-12-26] and [user:adamant,2021-12-28] for their helpful suggestions and comments Please comment under the blog or message me on codeforces if any parts are unclear or wrong. Also, I hope that some LGMs can help solve the open problems in this blog. # Introduction Maintaining the basis of vectors in $(\mathbb{Z}/2 \mathbb{Z})^d$, also known as the xor basis algorithm is a well-studie...
lexicographically largest vector. We will now show that the matrix $A$ also maintains thenumber of representable, vectors in $S$ in $O(d^2)$ time online. Additionally, we can also query other things such as thenumber, $ can be done in $O(1)$ time, where $n$ is the number of vectors we add. This algorithm can also be

Полный текст и комментарии »

  • Проголосовать: нравится
  • +381
  • Проголосовать: не нравится

34.
Автор -is-this-fft-, история, 5 лет назад, По-английски
[Tutorial] The command line: how to read input from file without #ifdef and much more #### Introduction Instead of algorithms and math, I'll be doing something completely different here. There is something that has bothered me for a long time: people not understanding the tools they use to participate in contests and thus failing to take real advantage of them. And it all goes back to not understanding the command line. Some of you might say, "well surely, the command line is something obsolete and you're only clinging to it because you [insert ridiculous amateur-psychology here]?" No! The command line is not obsolete, and unless competitive programming becomes so mainstream that software vendors start writing professional-grade tools aimed specifically at us, it won't be. [cut] $~$ What is the command line? Any of these: ![ ](/predownloaded/bd/b6/bdb6c157b9b3ce5ae046c9064e469e0081f8c0fe.png) As you can see, it comes in many background colors and fonts, but the basic idea is always the same. It's a box you can type commands in, which it will ...
large (let's say, 60 MB). For a number of people, the workflow included _opening these files_ and

Полный текст и комментарии »

  • Проголосовать: нравится
  • +443
  • Проголосовать: не нравится

35.
Автор Endagorion, 12 лет назад, По-русски
Codeforces Round #283: editorial (with bonuses!) Each problem comes with a challenge &mdash; a bonus task somehow related to the problem; you may tackle at the challenges for fun and practice, also feel free to discuss them at the comments. =) [problem:496A] For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^2)$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the difference between the neighbours of the removed element (whatever is larger); thus, the difficulty for every option of removing an element can be found in $O(1)$, for the total complexity of $O(n)$. Any of these solutions (or even less efficient ones) could pass the tests. **Challenge**: suppose we now have to remove exactly $k$ arbitrary elements (but the first and the last elements have to stay in their places). How small the maximal difference between adjacen...
that the number of pairs in the answer is large; in the actual tests the maximalnumber is 128, which, to find a test such that the number of pairs in the answer is large; in the actual tests the

Полный текст и комментарии »

Разбор задач Codeforces Round 283 (Div. 2)
  • Проголосовать: нравится
  • +336
  • Проголосовать: не нравится

36.
Автор adamant, 12 месяцев назад, По-английски
Finding all primes up to half a billion in 83 ms Hi everyone! I was itching to apply SIMD in another problem, and this time my attention picked the following problem: --- **[Library Checker &mdash; Enumerate Primes](https://judge.yosupo.jp/problem/enumerate_primes)**. You are given $N$, $A$ and $B$. Find $\pi(N)$, and print all $p_{kA + B} \leq N$. It is guaranteed that $N \leq 5 \cdot 10^8$ and that the total number of primes to print is at most $10^6$. --- After some tweaking, I managed ([#336744](https://judge.yosupo.jp/submission/336744)) to reduce my time consumption in this problem to **83 ms** and memory consumption to **25 MiB**, which makes it a top-1 submission on the Library Checker. For comparison, the top-2 solution ([#148169](https://judge.yosupo.jp/submission/148169)) takes 172 ms and 15 MiB, meaning that what I describe here is a 2x improvement in terms of the running time. We can also compare it to what appears to be the state of the art of sieving, the [primesieve](https://github.com/kimwalisch/...
+ B} \leq N$. It is guaranteed that $N \leq 5 \cdot 10^8$ and that the total number of primes to, multiples of each prime number. Core observation here is that for each prime, compressed indices of its, separate optimizations for small and large primes. In the standard sieve, we go over all prime numbers, large $n$, it is an improvement to do so over sieving individual numbers in $\lfloor \frac{n}{p_1

Полный текст и комментарии »

  • Проголосовать: нравится
  • +375
  • Проголосовать: не нравится

37.
Автор YouKn0wWho, 4 года назад, По-английски
[Tutorial] Common Mistakes in Competitive Programming and How to Avoid Them One thing is for sure. You do make mistakes. I also make miskates and that's what makes us human. But what we can surely do is &mdash; to try to minimize the errors that we make throughout our life. I have compiled some of the mistakes that I made in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in C++ as it is the most used language for CP. **So, if you are new to CP, stick with me as you might don't wanna repeat the mistakes that I made when I was a beginner.** #### Mistake 1 Check out the following code: <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int a = 1000'000'000,b = 1000'000'000; long long product = a * b; cout << product << '\n'; return 0; } ~~~~~ </spoiler> The outp...
[Don't use rand(): a guide to random number generators in C++](https://codeforces.me/blog/entry/61587, ` variable has been set to $10^6$, which is not large enough. So always make sure that the initialized

Полный текст и комментарии »

  • Проголосовать: нравится
  • +634
  • Проголосовать: не нравится

38.
Автор neal, 6 лет назад, По-английски
Unofficial Editorial for Educational Round 94 (Div. 2) Haven't done one of these for a while! Here are my approaches to the problems: #### [problem:1400A] We just need to make sure our string of $n$ characters matches each of the $n$ substrings in at least one spot. The easiest way to do this is to take every other character from $s$. Code: [submission:90908018] Another fun solution: we can generate random strings and check them until we find one that matches everything. This works because the probability of failing to match any particular substring is $\frac{1}{2^n}$, so as $n$ gets bigger the probability of failing gets extremely low. Code: [submission:90999219] #### [problem:1400B] First iterate on the number of swords we will personally take. Then we should greedily take as many war axes as we can until we run out of money. At this point, our follower needs to take as many items as possible. They can do this by greedily taking whichever of swords or war axes are cheaper until they run out, followed by taking the more expensi...
the number of mercenaries we'll choose and find the number of choices for each count. The key, . Code: [submission:90999219] #### [problem:1400B] First iterate on the number of swords we will, . We can just use an array of size $n^2$ and convert the pair $(a_i, a_j)$ to thenumber $a_i \cdot n

Полный текст и комментарии »

  • Проголосовать: нравится
  • +416
  • Проголосовать: не нравится

39.
Автор Monogon, 4 года назад, По-английски
[Tutorial] Supporting Priority-Queue-like Undoing on DS _Good morning!_ In this blog, I will present an online algorithm that can perform priority-queue-like undoing on a data structure, given a few assumptions. I will also present and solve a generalization of that problem. For context, I highly recommend reading this blog that shows how to solve the easier problem of queue-like undoing. That blog gave me the inspiration for the trick I will describe here, but I will still try to write this blog so that it can be understood without it. Thank you [user:Noam527,2023-01-08] for introducing such a great trick to the competitive programming community. [[Tutorial] Supporting Queue-like Undoing on DS](https://codeforces.me/blog/entry/83467) Acknowledgment ----------------- Huge thanks go to [user:peltorator,2023-02-20] for hosting a [blog contest](https://codeforces.me/blog/entry/110840). His generous prize of $300 got many people to write blogs on new, interesting ideas, and it was one of the main reasons I wrote this blog. I'm...
the highest priority. Let's say that the stack-depth of an update is the number of updates currently, update, we need to decide the number of updates to pop from the stack. Let's choose the smallest

Полный текст и комментарии »

  • Проголосовать: нравится
  • +409
  • Проголосовать: не нравится

40.
Автор pajenegod, 3 года назад, По-английски
Shallowest Decomposition Tree Hi Codeforces! Today I want to tell you about a really cool and relatively unknown technique that is reminiscent of Centroid decomposition, but at the same time is also completely different. The most common and well known decomposition tree algorithm out there is the centroid decomposition algorithm (running in $O(n \log n)$). It is a standard algorithm that is commonly used to solve tons of different kind of divide and conquer problems on trees. However, it turns out that there exists another closely related decomposition tree algorithm, that is in a sense optimal, and can be implemented to run in $O(n)$ time in around $30$ lines of code. I have chosen to call it the _Shallowest Decomposition Tree_. This blog will be all about the shallowest decomposition tree. Something I want to remark on before we start is that I did not invent this. However, very few people know about it. So I decided to make this blog in order to teach people about this super cool and relatively unknown tec...
used in the labeling. So it follows from this claim that the greedy algorithm uses the fewestnumber

Полный текст и комментарии »

  • Проголосовать: нравится
  • +403
  • Проголосовать: не нравится

41.
Автор okwedook, 6 лет назад, По-русски
Codeforces Round #703 (Div. 2) Editorial [problem:1486A] <spoiler summary="Hint1"> What's the lower bound for the amount of blocks for the answer to be $\texttt{YES}$? </spoiler> <spoiler summary="Hint2"> Check the predicate for every prefix. </spoiler> <spoiler summary="Solution"> Let's consider the smallest amount of blocks we need to make the first $i$ heights ascending. As heights are non-negative and ascending the heights should look like $0, 1, 2, 3, ..., i - 1$, so the minimum sum is $\frac{(i - 1) \cdot i}{2}$. It turns out that this is the only requirement. If it's not the case for every prefix the answer is $\texttt{NO}$ because we can't make some prefix ascending. Otherwise the answer is $\texttt{YES}$ because you can move the blocks right till there is at least $i$ blocks in the $i$-th stack and this would make the heights ascending. </spoiler> Solution using C++: [submission:107892022]<br> Solution using Python: [submission:107892053] [problem:1486B] <spoiler summary="Hint1"> Is proble...
can be done using some data structure (small-to-large for example) or some subtree dynamic, just need to calculate the number of good points on a line with points having coordinates $x$ and

Полный текст и комментарии »

Разбор задач Codeforces Round 703 (Div. 2)
  • Проголосовать: нравится
  • +481
  • Проголосовать: не нравится

42.
Автор Dominater069, 2 года назад, По-английски
How to Solve Questions [Dominater Version] Recently, I got a request asking me to write down my thought process while solving questions. So, here is the promised blog. I would like to thank [user:Iceknight1093,2024-08-30], [user:qwexd,2024-08-30], [user:Sana,2024-08-30], [user:Everule,2024-08-30] and [user:NovusStellachan,2024-08-30] for proof reading and suggesting edits in the blog. Special thanks to [user:satyam343,2024-08-30] for discussing most of the blog with me. <h3> 1. Overview </h3> The blog contains my solutions to $7$ problems in a wide range of ratings, starting from $1200$ all the way upto $2700$. Each problem has a step-by-step solution and you can notice how there are no large jumps in logic, but everything comes naturally. I do not claim that this is always possible in each problem, however I solve majority of CF problems in such a manner. There are certainly other high rated people who will have completely different methods of solving. However, this is about what works for me. There are some meta ...
$ naturally. We know that the number of divisors isn't too large even for a number of the order $10^9$ (we

Полный текст и комментарии »

  • Проголосовать: нравится
  • +263
  • Проголосовать: не нравится

43.
Автор neal, 6 лет назад, По-английски
Unofficial Editorial for Educational Round 95 (Div. 2) Here are my approaches to the problems today: #### [problem:1418A] Since the second trade is the only way to get coal, we clearly need to perform the second trade $k$ times. So how many times do we need to do the first trade? We can see that in order to end up with enough sticks and coal by the end, we need to obtain $ky + k$ sticks ($ky$ to convert to coal and $k$ to save as sticks). Since the first trade really just gives us $x - 1$ new sticks each time, we'll need to make $\displaystyle \left \lceil \frac{ky + k - 1}{x - 1} \right \rceil$ first trades ([reference to floor and ceiling functions](https://en.wikipedia.org/wiki/Floor_and_ceiling_functions) for anyone unfamiliar). For implementation details, note that for positive integers $a$ and $b$, $\displaystyle \left \lceil \frac{a}{b} \right \rceil = \left \lfloor \frac{a + b - 1}{b} \right \rfloor$. Code: [submission:92851684] #### [problem:1418B] We can think about the problem as follows: we want to order the $a_i$ to...
$a$-th big monster. In particular, if $a$ is larger than $big$ (the number of big monsters), we, DP value is the number of hard bosses our friend had to fight, which we want to minimize. For each, quick O(1) check to determine whether any number in $[y_{low}, y_{high}]$ is divisible by $a$. This has

Полный текст и комментарии »

  • Проголосовать: нравится
  • +368
  • Проголосовать: не нравится

44.
Автор Geothermal, история, 7 месяцев назад, По-английски
My Solutions to Spectral::Cup 2026 Round 1 (CF Round 1094) Since the editorial for today's Div. 1 hasn't been published yet, I thought I'd share solution sketches. Some of these won't include all of the specific details, but hopefully they should communicate the main ideas. (I didn't compete officially, but I got AC on all of the problems using the below approaches, so I'm fairly confident in correctness.) Feel free to leave questions below and I'll respond if I have time. ## A &mdash; A Wonderful Contest If any problem has $100$ subtasks, the answer is yes: we can achieve an arbitrary score by solving some of the other problems fully and by solving the right number of subtasks of the $100$-subtask problem. Otherwise, there is no way to achieve a score of 1, so the answer is no. ## B &mdash; Artistic Balance Tree Note that each of the reversal operations swaps odd positions with odd positions and even positions with even positions, as $u-i$ and $u+i$ differ by $2i$ and thus have the same parity. Thus, when we are to mark an od...
careful bookkeeping by adding the number of heavy vertices with score under $x$ to the answer for value $k, solving the right number of subtasks of the $100$-subtask problem. Otherwise, there is no way to, that if there are no positive numbers, we must mark the largest remaining number as long as $k > 0$.)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +181
  • Проголосовать: не нравится

45.
Автор MikeMirzayanov, 6 лет назад, По-английски
Codeforces: Results of 2020 [Annual Report] Hi Codeforces! Yes, I know it's already April. Time flies so fast lately! Exactly a year ago we were just learning all the "delights" of lockdown. So let's remember this 2020! What was it like? I don't know about you, but we had a hell of a lot of work. I will now show you some graphs and you will be very surprised. Lockdown effect? Of course, but we did our best too. Many thanks to everyone who did not stand aside! In 2020, we celebrated our 10th anniversary and crowdfunding money helps us grow and move forward. You helped us and each other. Thank you. <a href="https://codeforces.me/10years/supporters">Thank you for your contribution!</a> We've been working hard all year to make this community a better place. Did it work out? It's up to you to judge. Many thanks to everyone who invested time and effort: * [user:geranazavr555,2021-04-09], [user:kuviman,2021-04-09], [user:cannor147,2021-04-09] helped a lot with development and new features; * [user:Una_Shem,2021-...
, having at least +100 votes. The total number of posts is not interesting, because a lot of trash

Полный текст и комментарии »

  • Проголосовать: нравится
  • +612
  • Проголосовать: не нравится

46.
Автор adamant, история, 5 лет назад, По-английски
Theoretical grounds of lambda optimization Hi everyone! This time I'd like to write about what's widely known as "Aliens trick" (as it got popularized after 2016 IOI problem called [Aliens](https://ioinformatics.org/files/ioi2016problem6.pdf)). There are already some articles about it here and there, and I'd like to summarize them, while also adding insights into the connection between this trick and generic Lagrange multipliers and Lagrangian duality which often occurs in e.g. linear programming problems. Familiarity with a [previous blog](https://codeforces.me/blog/entry/98524) about ternary search or, at the very least, definitions and propositions from it is expected. Great thanks to [user:mango_lassi,2022-01-01] and [user:300iq,2022-01-01] for useful discussions and some key insights on this. Note that although explanation here might be quite verbose and hard to comprehend at first, the algorithm itself is stunningly simple. Another point that I'd like to highlight for those already familiar with "Aliens tr...
possible number such that $\lambda \cdot x \geq c$ for all $x \in X$. Equivalently, $c$ is the infimum of, unsafe on large numbers, consider fixed number of iterations double m = (l + r) / 2, Let $d_{v}(k, p, s)$ be the the largest number we can obtain on a segment $[l, r)$ corresponding to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +286
  • Проголосовать: не нравится

47.
Автор -14, история, 4 года назад, По-английски
ChatGPT passed ABC280D under human coaching [ChatGPT](https://openai.com/blog/chatgpt/) is a NLP model released recently, and I found it unexpectedly strong. Here's the evidence. [The Problem : ABC 280 D](https://atcoder.jp/contests/abc280/tasks/abc280_d) You are given an integer $K$ greater than or equal to $2$. Find the minimum positive integer $N$ such that $N!$ is a multiple of $K$. Here, $N!$ denotes the factorial of $N$. Under the Constraints of this problem, we can prove that such an $N$ always exists. Constraint: $2 \leq K \leq 10 ^ {12}$ [ChatGPT correct submission](https://atcoder.jp/contests/abc280/submissions/37030555) Here are the interactions. ChatGPT spoke Chinese to me (which I didn't figure out how to configure it), so I'd provide some translations here. --- **Human**: (The problem statement with hint to use long long) **ChatGPT**: We can use code to implement the above algorithm. (Code follows) ![ ](/predownloaded/d8/42/d8421bdc886cfeab1543ec0f1076ce94e4809502.png) --- *...
where the factorial is too large. We can use enumeration to find the smallest positivenumber N that, ) --- **Human**: This code can not process the case when the factorials are large. You can enumarate the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +509
  • Проголосовать: не нравится

48.
Автор errorgorn, 4 года назад, По-английски
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
Firstly, one of the problems of subtree operations is that if the number of children is verylarge, Ok, so now we want to figure out what is the largest possible number of edges of the smaller

Полный текст и комментарии »

  • Проголосовать: нравится
  • +245
  • Проголосовать: не нравится

49.
Автор errorgorn, история, 6 лет назад, По-английски
Codeforces Round #723 (Div. 2) Editorial [problem:1526A] ------------------ Setter: [user:antontrygubO_o,2021-05-28] Preparer: [user:errorgorn,2021-05-28] <spoiler summary="Hint 1"> Notice that the array size is even length. Usually in such problems, we would split the array into $2$ equal parts. Can you figure out what those $2$ parts are? </spoiler> <spoiler summary="Hint 2"> We sort the array and split it into the big half and the small half. </spoiler> <spoiler summary="Solution"> The main idea is that we can split the numbers into the two halves, the big half and small half, we can place the bigger half at the odd positions and the smaller half at the even positions. This works because the smallest big number is larger than the biggest small number. Hence, the mean of any two small numbers is smaller than any big number, and the mean of any two big numbers is bigger than any small number. </spoiler> <spoiler summary="Code (C++)"> ```c++ //雪花飄飄北風嘯嘯 //天地一片蒼茫 #include <bits/stdc++.h> #inc...
This works because the smallest big number is larger than the biggest small number. Hence, the mean

Полный текст и комментарии »

Разбор задач Codeforces Round 723 (Div. 2)
  • Проголосовать: нравится
  • +199
  • Проголосовать: не нравится

50.
Автор djm03178, 2 года назад, По-английски
Common mistakes on Dijkstra algorithm and how to hack them As many people may have noticed, I've done quite a number of TL hacks on [problem:2000G]. The hacked submissions even include many masters' and grandmasters' solutions, and most of them don't even have suspicious running time on the original tests. I predict many more solutions will fail on system testing because I've checked only some of C++20 and C++17 submissions and haven't tried running all the hack cases. So, how did they get time limit exceeded? They're actually caused by a few different mistakes, and we need different strategies to hack each of them. For convenience I'll assume that $\mathcal{O}(n)$ = the number of nodes = the number of edges, because whether the factor becomes $n$ or $m$ can vary depending on the implementation, and the number of edges is likely to be at least the number of nodes. Also for convenience (and as this problem is like that) I'll assume that the graph is bidirectional, but it works the same for directed graphs (only a bit harder to slowdown du...
3. Visiting in order of node number ------------------ This also happens a lot because many, As many people may have noticed, I've done quite a number of TL hacks on [problem:2000G]. The

Полный текст и комментарии »

  • Проголосовать: нравится
  • +401
  • Проголосовать: не нравится

51.
Автор adamant, история, 4 года назад, По-английски
Partitions and pentagonal number theorem Hi everyone! In today's blog I'd like to write about the theorem that allows to efficiently solve the following problems: - What is the number of partitions of a non-negative number $n$ for $n \leq 10^5$? - What is the number of partitions of a non-negative number $n$ for $n \leq 10^5$, so that no summand repeats $d$ or more times? - What is the number of partitions of a non-negative number $n$ for $n \leq 10^5$, so that no summand is divisible by $d$? - **[HackerEarth &mdash; Perfect Permutations](https://www.hackerearth.com/de/problem/algorithm/perfect-permutations-september-clash/)**: What is the number of permutations of length $n$ with $k$ inversions for $k \leq n \leq 10^5$? - **[problem:102354E]**: Let $\phi = \frac{9}{10} \cdot \frac{99}{100} \cdot \frac{999}{1000} \cdot \dots$, what is the $k$-th digit of $\phi$ for $k \leq 10^{18}$? - **[SNSS-2018 Round 5 &mdash; Investment Portfolio](https://contest.yandex.ru/contest/8703/problems/C/)**: You have $2n$ dollars and ...
Partitions and pentagonal number theorem, these problems efficiently is the pentagonal number theorem: $$ \large \boxed{\prod\limits_{k=1, $$ \large \boxed{\prod\limits_{k=1}^\infty (1-x^k) = 1 + \sum\limits_{k=1}^\infty (-1)^k\left(x, $$ \large \phi = 1 + \sum\limits_{k=1}^\infty (-1)^k\left(10^{-\frac{k(3k+1)}{2}} + 10^{-\frac{k, $$ \large \prod\limits_{k=1}^\infty (1-x^k) = 1 + \sum\limits_{k=1}^\infty (-1)^k\left(x^{\frac{k, $$\begin{gather}\large \begin{matrix} \bullet & \bullet & \bullet & \bullet & \color{royalblue, $$\large \begin{matrix} \bullet & \bullet & \bullet & \bullet & \bullet & \bullet & \color, )$, we either decrease each summand by $1$ when they're all greater than $1$, or decrease thenumber, number $3$), meaning that the partition is not strict, as needed for the bijection.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +172
  • Проголосовать: не нравится

52.
Автор adamant, история, 4 года назад, По-английски
Big integers with negative digits: The Trygub numbers Hi everyone! Today we will talk about something that might be useful in programming competitions. Yay! Also great thanks to [user:antontrygubO_o,2023-04-30] for sharing this with me and others in a Discord server. Let's implement a data structure that maintains a big number $N$ in base $b$ and supports the following: - Given (possibly negative) integers $|x|, |y| \leq n$, add $x b^y$ to $N$. - Given $k$ and assuming $N \geq 0$, print the $k$-th digit of $N$. - Check if $N$ is positive, negative or equals to $0$. Each operation should take at most $O(\log n)$ amortized time and $O(q)$ memory. While some approach you may think of immediately would imply using segment tree, or a similar structure, the solution proposed here only requires `std::map`, so it's much shorter and easier to implement (at the slight expense of increased constant factor). It may be used in the following problems: - [#2302. 「NOI2017」整数](https://loj.ac/p/2302) - [problem:1817E] - [problem:1810F] ...
a Discord server. Let's implement a data structure that maintains a big number $N$ in base $b, to frequently change large segments between the values of $0$ and $b-1$.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +263
  • Проголосовать: не нравится

53.
Автор Endagorion, история, 9 лет назад, перевод, По-русски
Yandex.Algorithm 2017, third elimination round: editorial (with challenges, bells and whistles) This time I've decided to play with spoilers to faciliate the presentation as some of the guys here did before. Tell me what you think about this write-up! #### Problem A. Shifts Topics: dynamic programming. Summary: the first "hard" problem of the contest. Knowing your basic DP problems helps a lot, but coming up with the precisely correct solution may take a lot of persistence. Solution: Suppose that we are allowed to make left circular shifts as well as right ones. <spoiler summary="Can you solve the problem in this case?"> First of all, making a shift is effectively moving a character to a different position in the string. Clearly, moving a character more than once makes no sense since we could have just moved it to its final destination instead without wasting any operations. Also, it obvious that the number of occurences of each character should be the same in both strings since it is preserved by shifts. Now, consider the characters that are *not* moved by ...
Solution: Since we aim to maximize the number, let us look what is the largest first digit we can

Полный текст и комментарии »

  • Проголосовать: нравится
  • +255
  • Проголосовать: не нравится

54.
Автор AlexSkidanov, история, 9 лет назад, По-английски
Are we close to machines solving ICPC problems? Hi, all, I with few other folks at [NEAR](http://near.ai/blog) work on teaching machines to program. A particularly exciting sub-project of that is teaching machines to solve competitive programming problems. In this post I would like to give a quick overview of where the state of the art is today, what the major challenges are, why this is not a popular area of research, and how the CodeForces community can help to address some of the issues the program synthesis community is facing today. We also have a certain budged allocated for this project, and we are paying to the CodeForces members who help us with some data annotation challenges. We have paid more than $10k in our first two annotation projects, and are launching three more projects today. Scroll to the end if you are interested. Competitive programming as a benchmark ====================================== With the emergence of deep learning, neural networks started performing almost at a human level in many ta...
`b` also appears in the array, and the largest number among `a`, `b` and `c` is smaller than the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +336
  • Проголосовать: не нравится

55.
Автор antontrygubO_o, 7 лет назад, По-английски
Are subtasks evil? Everything in this blog is only my opinion, motivated by the recent round. If you disagree with it, let's discuss in the comments! It's always hard to prepare a balanced problem set, and when the contest turns out to be unbalanced, an army of angry coders will destroy you in the comments section. But how can setters make Codeforces contests balanced? Before, authors usually had to spend more time coming up with new problems which would close a too large gap between some $2$ problems. But now we have an easier solution! Any time there is a big difficulty gap in a contest, add subtasks to it! [View](https://codeforces.me/blog/entry/67810?#comment-520212) on subtasks by [user:MikeMirzayanov,2019-11-24]: Subtasks became really widely used in Codeforces contests recently. I looked at last $30$ contests rated for Div1 users. In turns out that: Rounds $30 - 21$ had only $1$ subtasks in total, Rounds $20 - 11$ had $3$ subtasks in total, The last $10$ rounds already had $7...
some very large gap, then maybe try to close it with a subtask. This means that subtasks should be

Полный текст и комментарии »

  • Проголосовать: нравится
  • +487
  • Проголосовать: не нравится

56.
Автор MikeMirzayanov, 8 лет назад, перевод, По-русски
Codeforces Global Rounds Hello! It is always satisfying and important for me when former contest participants offer their help to the community and support the development of programming competitions. And now I am in a hurry to share the news that thanks to the support of <a href="https://www.xtxmarkets.com/">XTX Markets</a> and the personal participation of Yuri Bedny and Alexander Gerko, we are launching a new line of Codeforces Global Rounds. Hooray! <img src="/predownloaded/2e/e2/2ee2f0f95f05aae6ca6f47812dae2dc2aabf277b.png" style="width:200px; float:right; margin: 0 1em 1em 1em"/> Like many of you, I had never heard of <a href="https://www.xtxmarkets.com/">XTX Markets</a> before but it is one of the largest quantitative-driven electronic liquidity providers in the world. I understand little about the financial sector, but with their 34,148 cores and 42 petabytes of usable storage in their research cluster, XTX’s rapid growth and strong market share globally speak for themselves. So, in 2019, w...
hours, depending on the number and complexity of the problems. All such rounds will be rated for all

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1206
  • Проголосовать: не нравится

57.
Автор KADR, 15 лет назад, По-русски
Codeforces Beta Round #97 <p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><p</p><div>Hello everyone!<br /></div><div><br /></div><div>Codeforces Beta Round #97 will take place on Friday, December 9th at <a href="http://timeanddate.com/worldclock/fixedtime.html?day=9&amp;month=12&amp;year=2011&amp;hour=19&amp;min=0&amp;sec=0&amp;p1=166">19:00 MSK</a>. This will be my second classical Codeforces round and I hope it won't be the last one :)</div><div><br /></div><div>I'd like to thank [[user:maksay,2011-12-08]], [[user:Shtrix,2011-12-08]], [[user:it4.kp,2011-12-08]], [[user:RAD,2011-12-08]] and [[user:Delinur,2011-12-08]] for their help in preparing contest, testing problems and translating them into English.</div><div><br /></div><div>Good luck!</div><div><br /></div><div><b>UPD: </b>Due to technical reasons the round start time is shifted 5 minutes forward.</div><div><br /></div><div><b>UPD 2: </b>Due to the large number of participants and large number of tests the testing wi...
UPD 2: Due to the large number of participants and large number of tests the testing

Полный текст и комментарии »

  • Проголосовать: нравится
  • +237
  • Проголосовать: не нравится

58.
Автор emorgan, 6 лет назад, По-английски
[Tutorial] Slight Generalization of Grundy Numbers **Prerequisites**: Grundy numbers (aka nimbers, I will refer to them as Grundy numbers), the connection of Grundy numbers to mex and bitwise xor. **Note about mex**: We know the the mex of a set of non-negative integers is the smallest non-negative integer which is not in the set. This definition works fine for any proper subset of $\mathbb{N}$, since $\text{mex}(S)=\min(\mathbb{N}\setminus S)$, and min is well-defined for any non-empty subset of $\mathbb{N}$. However, the minimum of an empty set is not well-defined, so neither is $\text{mex}(\mathbb{N})$, so we will define a new object $\omega=\text{mex}(\mathbb{N})$. Most of the properties of this object as it relates to mex are pretty straight-forward, for example <br><br> $$ \text{mex}(\mathbb{N}\cup\{\omega\}) = \omega+1 $$ $$ \text{mex}(\{a\omega+b\,|\,a,b\in\mathbb{N}\}) = \omega^2 $$ **Games with Finite States**: Given any finite impartial game (i.e. an impartial game which is guaranteed to terminate in a finite number o...
Note that this game is guaranteed to terminate in a finite number of moves, however thatnumber, number could be arbitrarily large depending on the choices of the players. That is, it is impossible to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +282
  • Проголосовать: не нравится

59.
Автор Endagorion, 12 лет назад, По-английски
Codeforces Round #300 Editorial (+challenges) As usual, a challenge comes with every problem. I tried not to repeat the mistakes of my previous editorials and made sure that all challenges have a solution =) (except for the _italics_ parts that are open questions, at least for me). Go ahead and discuss them in the comments! General questions about problems and clarification requests are welcomed too. **UPD**: I added codes of my solutions for all the problems. I didn't try to make them readable, but I believe most part of them should be clear. Feel free to ask questions. [problem:538A] Let me first clarify the statement (I really wish I didn't have to do that but it seems many participants had trouble with the correct understanding). You had to erase exactly one substring from the given string so that the rest part would form the word `CODEFORCES`. The (somewhat vague) wording `some substring` in the English translation may be the case many people thought that many substrings can be erased; still, it is beyond my understa...
somewhat traditional question: how many (modulo some prime number) large Latin letter strings of, **Challenge (easy)**. A somewhat traditional question: how many (modulo some primenumber) large, Are there more effective solutions? Sure enough. First of all, one can notice that thenumber of

Полный текст и комментарии »

Разбор задач Codeforces Round 300
  • Проголосовать: нравится
  • +312
  • Проголосовать: не нравится

60.
Автор feecIe6418, 4 года назад, По-английски
Editorial of Codeforces Global Round 21 Thanks for participation! If your solution to D involves any data structures and is not $O(n)$ -- please read the "solution 1". I believe it is very interesting, but to make the difficulty suitable for D we allowed not $O(n)$ solutions. [problem:1696A] <spoiler summary="Hint 1"> How many operations will we perform? <spoiler summary="Answer"> At most one. Why? </spoiler> </spoiler> <spoiler summary="Solution"> Suppose we can only perform exactly one operation. In this case the answer is $S=\max_{1\le i\le n}(a_i\mathrm{\ or\ }z)$. In fact, we can prove that this is the answer. Define $a_i'$ as the value of $a_i$ after some operations. It suffices to prove the answer will never exceed $S$. Note that $z$ will always become a submask of itself after any number of operations, so $a_i$ will always be a submask of $(a_i\mathrm{\ or\ }z)$ after any number of operations. This leads to the conclusion that $a_i'\le (a_i\mathrm{\ or\ }z)$ for all $i$. Thus $\max_{1\le i...
answer will never exceed $S$. Note that $z$ will always become a submask of itself after anynumber of, . Otherwise, take $K$ numbers with the maximum absolute value. If there is an evennumber of negative

Полный текст и комментарии »

Разбор задач Codeforces Global Round 21
  • Проголосовать: нравится
  • +332
  • Проголосовать: не нравится

61.
Автор FairyWinx, 5 лет назад, По-русски
The number of prefix maxima on the segment with changes and with linear memory The following task is given: an array of integer $a_1, \ldots, a_n$ is given, as well as $q$ queries of one of two types: 1. $a_i+=x$, where $l \leq i \leq r$. 2. find out the number of indexes $i$, where $l\leq i\leq r$ and $a_j < a_i$, for all $j:$ $l \le j < i$. (Or humanly &mdash; the number of prefix maxima on the segment) We want to solve this faster than for $O(sqrt(n))$ per request. Let's consider an easier option when we don't have change requests. Then we can make a just Segment Tree, where a sorted list of prefix maxima is stored at the vertex, if our segment is the segment corresponding to the vertex of the segment tree. Then we should just make an algorithm, anological Merge Sort Tree, only we should consider the vertices into which we split the query from left to right and store the maximum among the previous elements on a suitable segment, and add to the answer the number of elements in the vertex larger than the maximum before, and then update the maximum. ...
The number of prefix maxima on the segment with changes and with linear memory, )$, which will count the number of prefix maxima of strictly large $x$ on the segment of the vertex, Then we implement the function $f(v, x)$, which will count the number of prefix maxima of strictly, number of elements in the vertex larger than the maximum before, and then update the maximum.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +140
  • Проголосовать: не нравится

62.
Автор adamant, история, 18 месяцев назад, По-английски
Finding a billion factorials in 60 ms with SIMD Hi everyone! _This blog is not about asymptotic optimization. Refer to [this comment](https://codeforces.me/blog/entry/63491?#comment-474051) for those._ There is a problem on Library Checker that goes as follows: <hr> **[Many Factorials](https://judge.yosupo.jp/problem/many_factorials)**: You're given $n_1,\dots,n_t$, where $t \leq 10^5$. For each $i$, find $n_i! \bmod M$, where $M = 998\;244\;353$. <hr> In this blog, we will learn how to solve this task in 61 ms, without precalc and **without** FFT. That's right, we will take the dumbest solution we can imagine, and will improve its constant factor until its decent enough. How much decent? Well, let's use the following baseline: <spoiler summary="Naive solution"> ```cpp vector<int> facts(vector<int> args) { const int block = 1 << 16; vector<int> args_per_block[mod / block + 1]; vector<int> res(size(args)); for(auto [i, x]: args | views::enumerate) { args_per_block[x / block].push_b...
and multiply them by a really large power of $2$.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +274
  • Проголосовать: не нравится

63.
Автор DrSwad, история, 7 лет назад, По-английски
A Beautiful Technique for Some XOR Related Problems ## Inspiration I'm very excited about this blog, as it took me quite a lot of effort and scavenging through the internet to completely grasp the concept of this technique(That's probably because I have almost zero knowledge in Linear Algebra or I'm just plain dumb). So I feel like I genuinely conquered a challenge, and I really want to share it with someone. But there's no way my CP friends circle will believe it, they'll think I'm just trying to show off :P So here I am, sharing it on CF. I also created a [personal blog](https://drschwad.github.io/), so that if I ever feel like sharing something again(not only about CP), I can write a blog there. I also added this same post [there](https://drschwad.github.io/2019-08-06-z2-space-xor-trick/), you can read it there if you prefer dark theme. I'll be pleased to hear any thoughts on the blog or if I can improve it in some way ^\_^ ## Introduction Since it concerns Linear Algebra, there needs to be a lot of formal stuff going on ...
6. And there cannot possibly be larger number of independent vectors than basis in a set. If $d$ is

Полный текст и комментарии »

  • Проголосовать: нравится
  • +425
  • Проголосовать: не нравится

64.
Автор 4fecta, история, 6 лет назад, По-английски
An Introduction to Plug DP So I realized that there are literally 0 resources written in English on Plug DP, which is one of my favourite DP tricks/techniques that I know of so far. Thus, I hope this serves as a soft introduction for English speakers to this technique, and maybe sheds some light on how powerful it can be. Before we start, I would recommend having a solid understanding of bitmask DP in general in order to get the most out of this blog. Now, let's begin. ### What is Plug DP? In short, Plug DP is a bitmasking technique that allows us to solve complicated problems with relatively simple states and transitions. To illustrate Plug DP in its most primitive form, let's visit a rather classical problem: **How many ways can we fully tile an $N \times M$ grid with $1 \times 2$ dominoes?** This problem can be solved with a standard row-by-row bitmasking approach, but the transitions for that DP state is annoying and unclear at best. Instead, let's investigate an approach that uses a slightly differ...
`MOD` since the number of tilings grows rapidly for larger $N$ and $M$. The time complexity is

Полный текст и комментарии »

  • Проголосовать: нравится
  • +428
  • Проголосовать: не нравится

65.
Автор Hoks_, история, 12 месяцев назад, По-английски
Maybe It’s Time to Stop Unrated Accounts from Submitting Recently, we’ve run into an unpleasant situation: some large companies have been using a huge number of accounts to submit AI-generated solutions purely for model training, which ended up causing serious “in queue” congestion for everyone else. **Maybe it’s time to consider restricting submissions from unrated users.** If those AI-driven accounts were required to participate in at least one contest before being allowed to submit normally, it would drastically cut down the number of accounts they could abuse. On top of that, we could improve AI-detection during contests and apply stricter monitoring to accounts that submit massive amounts of AI-generated code. For regular users, the requirement is trivial — just join a single Codeforces round, and you’re good to go. Compared to the awful experience of having the queues jammed for hours, this small inconvenience might be a reasonable trade-off. That’s the best idea I can think of at the moment. What do you think? How can we ...
Recently, we’ve run into an unpleasant situation: some large companies have been using a huge

Полный текст и комментарии »

  • Проголосовать: нравится
  • +636
  • Проголосовать: не нравится

66.
Автор PersistentLife, история, 3 месяца назад, По-английски
As an CNOI Gold Medalist: How I Train CNOI Gold Medal Winning Competitive Programmers UPD: [Curated Problem Set #1](Thhttps://codeforces.me/blog/entry/156427) is released. Please join our Discord server to receive the latest updates: https://discord.gg/DsHSfmVgG UPD: Curated problem set #1 (both normal and advanced) **for subscribers** is ready! Feel free to join our Discord server and subscribe! This post is about: 1. The Main Two Abilities You Need in Competitive Programming 2. How to Choose Problems of an Appropriate Difficulty 3. How Should You Work on a Problem 4. When You Should Learn New Knowledge (Like New Algorithms) 5. How to Train Before an Important Contest 6. Free Content, Personalized Subscription Services, and Potential Opportunity for One-to-One Coaching 7. Survey About the Services I won a gold medal at NOI 2024 in my second year of high school and was admitted to the Turing Class at Peking University. After securing my admission, I continued pursuing competitive programming: I began studying new material at university in advance whi...
solving a large number of problems or memorizing problems you have already seen cannot replace an

Полный текст и комментарии »

  • Проголосовать: нравится
  • +358
  • Проголосовать: не нравится

67.
Автор gojira, 5 лет назад, По-английски
A look at Competitive Programming post-hibernation Hello friends! As I've recollected in a previous [post](https://codeforces.me/blog/entry/97566), I am an old competitor who hadn't really participated since ~2014, and recently got a bout of nostalgia to return to Competitive Programming. So, I did a couple Topcoder SRMs, suffered through some SNWS rounds, participated in [three regional 5hr competitions](https://contest.yandex.ru/3QF2021) on three consecutive days, and dozed off at every Codeforces contest I tried to wake up for. A lot of things are still the same as 8 years ago: [user:tourist,2022-01-26] is still at the top, grey coders still ask for how many minutes to solve a problem before reading the editorial, Russian university teams [continue winning](https://icpc.global/worldfinals/results) ACM ICPC, and Snarknews never gives up on his alternate competition formats. But in this post, I want to focus on the new patterns that emerged since my last time around. #### #1: Codeforces rounds timing Did you know that t...
value modulo a large prime. The most common reason for this is that we are counting thenumber of

Полный текст и комментарии »

  • Проголосовать: нравится
  • +371
  • Проголосовать: не нравится

68.
Автор sum, история, 3 года назад, По-английски
Editorial for Codeforces Round #919 (Div. 2) ##Information about the round <spoiler summary="Rating predictions (inspired by BucketPotato's editorial)"> | Person | A | B | C | D | E | F1 | F2 | |--------------------------------------------|------|------|------|------|------|------|------| | [user:sum,2024-01-13] | 800 | 1300 | 1500 | 1900 | 2000 | 2200 | 2900 | | [user:oursaco,2024-01-13] | 800 | 1100 | 1300 | 1600 | 1800 | 2100 | 3100 | | [user:omeganot,2024-01-13] | 900 | 1000 | 1400 | 1700 | 1900 | 2200 | 2800 | | [user:sriniv,2024-01-13] | | | | 1900 | 2000 | 1900 | | | [user:apple_method,2024-01-13] | 1000 | 1200 | 1400 | 1900 | 1600 | | | | [user:awesomeguy856,2024-01-13] | 800 | 1100 | 1400 | 1800 | 1900 | 2000 | 2800 | | [user:nonrice,2024-01-13] | 900 | 1000 | 1400 | 1750 | | | | | [user:null_aw...
the number of elements Alice removes. For each $i$, we know that Alice will remove the $i$ largest, . So in order to minimize the damage Bob will do, Alice should always remove somenumber of largest

Полный текст и комментарии »

Разбор задач Codeforces Round 919 (Div. 2)
  • Проголосовать: нравится
  • +314
  • Проголосовать: не нравится

69.
Автор Endagorion, 12 лет назад, перевод, По-русски
Codeforces Round #295 Editorial (now with bonuses!) We would like to thank the testers of this round's and Winter Computer Camp olympiad's problems: [user:alger95,2015-03-02], [user:thefacetakt,2015-03-02], [user:adamant,2015-03-02], [user:dragonic,2015-03-02], [user:Who179,2015-03-02], [user:ASverdlov,2015-03-02]. Make sure to comment if you find any mistakes. **UPD**: I've just remembered to put up the usual challenges for the problems. So, here they go. [problem:520A] Idea: [user:Endagorion,2015-03-02] Preparation: [user:Endagorion,2015-03-02] To check that every letter is present in the string we can just make a boolean array of size 26 and for every letter set the corresponding variable to TRUE. In the end check that there are 26 TRUEs. That is an $O(n)$ solution. Also don't forget to change all letters to lowercase (or all to uppercase). To make all the letters lowercase, one could use standard functions, like `tolower` in Python. Also, it is known that the letters from `a` to `z` have consecutive ASCII numbe...
numbers, as well as `A` to `Z`; an ASCII number of symbol is `ord(c)` in most languages. So, to get the, vertices and edges leading from one number to another if an operation can be made to change onenumber, number, and the second should choose the minimal one.

Полный текст и комментарии »

Разбор задач Codeforces Round 295 (Div. 2)
Разбор задач Codeforces Round 295 (Div. 1)
  • Проголосовать: нравится
  • +151
  • Проголосовать: не нравится

70.
Автор gabrielwu, история, 5 лет назад, По-английски
[Tutorial] Expected number of coin flips required to achieve a given string (You can find a slightly different version of this article, tailored more for a non-CP audience, on my [website](https://gabrieldwu.github.io/flipping-coins).) Thank you to [user:smax,2022-01-07] for his feedback on this post. *Prerequisites:* - expected value, linearity of expectation - basic linear algebra - familiarity with string algorithms such as KMP (only in certain sections) <h2> The Problem </h2> Say you're given a string of coin flips, such as **HTTH** or **TTTHHT**. What is the expected number of times you must flip a coin until you encounter that string? A common initial (incorrect) intuition about this problem is that all strings of length $n$ should have the same answer -- something like $2^n$. We sense that there should be some sort of symmetry between heads and tails, so it feels odd that **HHHH** should appear any earlier or later than **HTHT**. But in this case, our intuition is simply wrong. It is true that the answer will always be on the order o...
[Tutorial] Expected number of coin flips required to achieve a given string, a large number of times (say you do $N = 10^9$ total flips). The total number of trials you end up, because I see no efficient way to compute the approximate number of disjoint occurrences of, say, " by flipping the coin a large number of times (say you do $N = 10^9$ total flips). The totalnumber, large numbers. The integer values encountered in this problem grow exponentially in $n$, so they can be

Полный текст и комментарии »

  • Проголосовать: нравится
  • +185
  • Проголосовать: не нравится

71.
Автор zscoder, история, 6 лет назад, По-английски
April Fools Day Contest 2021 — ZS Edition Hi everyone, April Fools is near and as usual we have an [April Fools Day Contest](https://codeforces.me/blog/entry/88840) on Codeforces this year. In addition to that, I usually try to host some form of mini April Fools Contest for my friends every year (or almost every year). This year, I am trying to host a bigger April Fools Day contest than usual and I invite everyone to participate! In view of the April Fools contest on Codeforces, the round will begin at [31 March 10pm (GMT+8)](https://www.timeanddate.com/worldclock/fixedtime.html?msg=April+Fools+Day+Contest+2021+%28ZS%29&iso=20210331T22&p1=122) and lasts for exactly $24$ hours (and thus it will end ~35 minutes before the CF April Fools round). The contest will consist of several unusual tasks, and I hope that everyone will at least find something interesting. The problems will not be sorted by increasing order of difficulty (if the word difficulty is even applicable), so it is **highly advisable** to read (and try!)...
there exists enough solutions using 5 distinct numbers, where the largest 4 numbers used arelarge (e.g

Полный текст и комментарии »

  • Проголосовать: нравится
  • +247
  • Проголосовать: не нравится

72.
Автор EvenImage, история, 22 месяца назад, По-английски
IAEPC Preliminary Contest (Codeforces Round 999, Div. 1 + Div. 2) Editorial Thank you for participating in this round! Problems I are authored by [user:orzdevinwang,2025-01-20] and the rest by me. Sorry for the weak pretest in problem B. [problem:2061A] <spoiler summary="Hint 1"> What is the parity of $s$ after an operation? </spoiler> <spoiler summary="Solution"> [tutorial:2061A] </spoiler> [problem:2061B] <spoiler summary="Hint 1"> What is the condition for four edges to form an isosceles trapezoid? </spoiler> <spoiler summary="Hint 2"> How do you find two bases after fixing the length of the legs? </spoiler> <spoiler summary="Hint 3"> How do you choose two legs? </spoiler> <spoiler summary="Solution"> [tutorial:2061B] </spoiler> [problem:2061C] <spoiler summary="Hint 1"> How can you solve the problem in $O(n^2)$? </spoiler> <spoiler summary="Hint 2"> **No two liars can stand next to each other** is important. </spoiler> <spoiler summary="Solution"> [tutorial:2061C] </spoiler> [problem:2061D] <sp...
For the part that the difference between the number of victories is not, If the difference between the number of victories is large, he will, summary="Hint 2"> If the difference between the number of victories is large, he will either always

Полный текст и комментарии »

  • Проголосовать: нравится
  • +86
  • Проголосовать: не нравится

73.
Автор Proof_by_QED, история, 17 месяцев назад, По-английски
EPIC Institute of Technology Round Summer 2025 (Codeforces Round 1036, Div. 1 + Div. 2) Editorial Thanks for participation! We hope you loved the contest. #### [problem:2124A] Problem Credits: [user:Lilypad,2025-07-01] <br> <spoiler summary="Hint"> When is there definitely *not* a solution? </spoiler> <spoiler summary="Solution"> First, note that since relative order is preserved no matter which elements are deleted, if $a$ is originally sorted in nondecreasing order, the array cannot be a derangement no matter which elements are deleted. If $a$ is not sorted, we can note that any two elements that form an inversion pair satisfies the requirements. The total runtime is $O(n)$. </spoiler> <spoiler summary="Code"> ``` #include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int> arr(n); for(auto &x : arr) cin >> x; for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(arr[i] > arr[j]){ cout << "YES\n2\n"; cout << arr[i] << " " << a...
$j$ (which is more than $1$ index ago), plus one number. From our analysis above, we know this, the largest number possible in each interval, and call our function recursively. Finally, if there

Полный текст и комментарии »

  • Проголосовать: нравится
  • +309
  • Проголосовать: не нравится

74.
Автор Sharon, история, 9 лет назад, По-английски
Grandmasters HATE this one weird trick!!! Top ten tips to speed up your program (NUMBER THREE WILL SHOCK YOU!!) It is currently 12:00AM, March 32nd. I was digging through the deep web and I found out about a couple tricks that legendary grandmasters have been using on this website for ages, though it was kept secret from the rest of humanity. These tricks are too dangerous for dangerous people to know (Kim Jong Un if you are reading this please stop). However, I am personally sick of the inequality and I think it is time to let the world know the secrets to make your programs run super fast. Trick 1: The O(N) to O(1) trick. Consider [this problem](http://codeforces.me/problemset/problem/955/C). The bounds are clearly too large for an O(N) solution (looping from L to R). However, what if I told you that you could easily modify your O(N) code to make it O(1)? Consider this piece of code: ~~~~~ long sum = 0; for(long i = 0; i < N; i++){ sum += i; } ~~~~~ We can clearly see that for large N, such as 10^18, the program will take a long time to run. BUT!!! We can turn every...
Grandmasters HATE this one weird trick!!! Top ten tips to speed up your program (NUMBER THREE WILL, ). The bounds are clearly too large for an O(N) solution (looping from L to R). However, what if I, We can clearly see that for large N, such as 10^18, the program will take a long time to run. BUT, large for an O(N) solution (looping from L to R). However, what if I told you that you could easily

Полный текст и комментарии »

  • Проголосовать: нравится
  • +501
  • Проголосовать: не нравится

75.
Автор zscoder, история, 4 года назад, По-английски
[Contest] Statement Not Found: Season 2 #### Do you think you can solve CP problems without reading the problem statements? Let's find out! On [August 28, 2022 (Sunday) 19:30-22:00 GMT+8](https://www.timeanddate.com/worldclock/fixedtime.html?msg=Statement+Not+Found+-+Season+2&iso=20220828T1930&p1=122&ah=2&am=30), I will hold an unofficial fun contest called Statement Not Found. As you can deduce from the title, there will be no problem statements (except title and samples). Your goal is to collect as many points as possible within 2.5 hours :) Obviously, this round is **unrated**. It is somewhere between April Fools contest and a legitimate contest. The contest will be OI-style, meaning there will be no time penalty. You are allowed to use any resources online to help solve the problems. There will be **12** problems. **Scoring Distribution:** 200-400-700-700-700-800-800-900-1100-1100-1100-1500 (Total: 10000) **Please read all problems** as problem difficulty is very subjective and a 1100-point problem might b...
This criterion counts the number of rows and columns

Полный текст и комментарии »

  • Проголосовать: нравится
  • +308
  • Проголосовать: не нравится

76.
Автор Error_Yuan, 15 месяцев назад, По-английски
Codeforces Round 1046 (Div. 1, Div. 2) Editorial <spoiler summary="Rate the Contest!"> - Amazing round: - Good round: - Average round: - Bad round: - Horrible round: </spoiler> [problem:2136A] Idea: [user:Alan_dong,2025-08-25] Preparation: [user:Register,2025-08-25] <spoiler summary="Hint"> If one team got a score of $x$ in the first half, what is the maximum score the other team could get? </spoiler> <spoiler summary="Solution"> We can consider the first half and the second half separately. The dream might come true if and only if the scores in both halves are possible. In the second half, the RiOI team scored $(c - a)$ goals, while the KDOI team scored $(d - b)$ goals. Suppose the RiOI team scored $x$ goals in some half. Denoting the score of the KDOI team as $y$, one can see that the maximal value of $y$ is $2\cdot x + 2$, under the goal order $\tt{\color{red}K\color{red}K\color{black}RK\color{red}K\color{black}R...RK\color{red}K\color...

Полный текст и комментарии »

Разбор задач Codeforces Round 1046 (Div. 1)
Разбор задач Codeforces Round 1046 (Div. 2)
  • Проголосовать: нравится
  • +218
  • Проголосовать: не нравится

77.
Автор AquaMoon, 3 года назад, По-английски
Harbour.Space Scholarship Contest 2023-2024 (Div. 1 + Div. 2) Editorial Thank you for participation and we hope you enjoy this round ヽ(^ o ^)/. During the contest, there was a small issue in problem D. For those affected, we have skipped your duplicate submissions (if your duplicate submissions were not skipped, please let us know). We apologize again for any inconvenience caused. In addition, we are honored to invite you to our unofficial round tomorrow (*╹▽╹*) [Invitation to TheForces Round #22 (Interesting-Forces)](https://mirror.codeforces.com/blog/entry/119771) ### [1864A-Increasing and Decreasing](https://mirror.codeforces.com/contest/1864/problem/A) Idea : [user:wuhudsm,2023-08-27] <spoiler summary="Tutorial"> We use the following greedy construction: For all $i$ ($1<i<n$), set $a_i=a_{i+1}-(n-i)$. If $a_2-a_1 \geq n-1$, we've found a solution, otherwise there is no solution. Proof. Assume there's a solution which includes an index $i$ ($1<i<n$) such that $a_{i+1}-a_i>n-i$. We can make $a_j:=a_j+\Delta$ for all $j$ ($2 \le j ...
connected components will then share the largest value. In other words, when we pick the largestnumber for

Полный текст и комментарии »

  • Проголосовать: нравится
  • +201
  • Проголосовать: не нравится

78.
Автор Geothermal, история, 6 лет назад, По-английски
AtCoder Beginner Contest 169 Unofficial Editorial I just did my first ABC in a while, so I decided to write up and share my solutions below. Feel free to leave questions in the comments! There were several questions this round that had the potential to create precision issues; however, the solutions below give approaches that sidestep those errors altogether. Sadly, I think compiling and testing my A prevented me from winning the round :( #A &mdash; Multiplication 1 Just multiply the numbers and print them out. It's not that hard. Time Complexity: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc169/submissions/13800320) --- #B &mdash; Multiplication 2 This turns out not to be quite as easy as the last problem. Multiplying numbers this large is actually a challenge in C++ because the result is likely to be greater than $2^{63}$, and thus will cause long long overflow. Thus, in C++, we can't just multiply the numbers and check if the result is greater than $10^{18}$. One possible appr...
the last problem. Multiplying numbers this large is actually a challenge in C++ because the result, This turns out not to be quite as easy as the last problem. Multiplying numbers thislarge is, number of integers from $Y$ to $Z$, which is $Z-Y+1$.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +281
  • Проголосовать: не нравится

79.
Автор TLE, история, 8 лет назад, По-английски
Avito Cool Challenge 2018 Editorial [problem:1081A] Idea: [user:yjq_naiive,2018-12-17] Developer: [user:yjq_naiive,2018-12-17] <spoiler summary="Hint"> 1 sounds like the minimum value we can get. Why? Is it always true? </spoiler> <spoiler summary="Solution"> When $n \leq 2$, we can do nothing. When $n \geq 3$, since $1<\frac{n}{n-1}<2$, $n-1$ isn't a divisor of $n$, so we can choose it and get $1$ as the result. </spoiler> <spoiler summary="Code (yjq_naiive)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); if (n == 2) { puts("2"); } else { puts("1"); } return 0; } ~~~~~ </spoiler> [problem:1081B] Idea: [user:yanQval,2018-12-17] Developer: [user:yanQval,2018-12-17] <spoiler summary="Hint"> Consider the number of people wearing hats of the same color. </spoiler> <spoiler summary="Solution"> let $b_i=n-a_i$ represent the number of people wearing the same type of hat of $i$-th person. Notice that the person wear...
Suppose $t$ be some arbitary large number (you can think of it as $\infty$), then $x_1$ is a suffix

Полный текст и комментарии »

  • Проголосовать: нравится
  • +154
  • Проголосовать: не нравится

80.
Автор cry, 23 месяца назад, По-английски
Codeforces Round 998 (Div. 3) Editorial <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | |--------------------------------------------|------|------|------|------|------|------|------| | [user:Proof_By_QED,2025-01-15] | 800 | 1000 | 1100 | 1300 | 1600 | 1900 | 2400 | | [user:cry,2025-01-15] | 800 | 1000 | 1000 | 1200 | 1700 | 2000 | 2400 | | [user:chromate00,2025-01-15] | 800 | 1000 | 1000 | 1400 | 1700 | 2000 | 2400 | | [user:DivinePunishment,2025-01-15] | 800 | 1200 | 1100 | 1200 | 1700 | 2000 | 2300 | | [user:-firefly-,2025-01-15] | 800 | 1000 | 1000 | 1400 | 1800 | 2000 | 2400 | | [user:Error_Yuan,2025-01-15] | 800 | 1100 | 1200 | 1600 | 1800 | 2100 | 2400 | | [user:macaquedev,2025-01-15] | 800 | 1000 | 1500 | 1400 | 1300 | 2000 | 1900 | | [user:In...
Now, let $x$ be the largest number such that $op_x$ is in $b$. Since at least one of $a_x,a_{x+1, The number of non-$1$ elements can't be so large.

Полный текст и комментарии »

Разбор задач Codeforces Round 998 (Div. 3)
  • Проголосовать: нравится
  • +126
  • Проголосовать: не нравится

81.
Автор ToxicPie9, 4 года назад, По-английски
[Tutorial/Parody Post] Common Mistakes in Competitive Programming and How to Avoid Them Yesterday [user:YouKn0wWho,2023-01-11] posted a [blog](https://codeforces.me/blog/entry/111217) explaining common mistakes in competitive programming and how to avoid them. I was greatly inspired by that post so I decided to make my own. I have compiled some of the mistakes that I didn't make in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in Rust as it is the most beloved language for CP. #### Mistake 1 Check out the following code: <spoiler summary="Code"> ``` fn main() { let x: i32 = 1_000_000_000; let y: i32 = 1_000_000_000; println!("{}", x * y); } ``` </spoiler> The output should be $10^{18}$. But if you run the code, you will get a different output. Why? <spoiler summary="Reason"> Because it won't even compile....
$. To store large numbers like $10^{18}$, you'll need bigger integer types like `i64`.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +337
  • Проголосовать: не нравится

82.
Автор SecondThread, история, 6 лет назад, По-английски
Petition to revoke unrated account permissions to post comments/blogs Unrated Account Disaster ================== Recently there have been an obscene number of unrated accounts showing up. Several of them have inappropriate names, so I won't give examples because I want to keep this post clean, but I'm sure you have seen them in the comments. They are likely all by the same individual, possibly with a few copy-cat troublemakers as well. Recently, certain ones have begun to spam useless comments on old posts to clog up the recent actions, effectively hiding all relevant conversations except on the blog posts they spam on. For whatever reason, these are overwhelmingly on [user:Errichto,2020-07-10]'s old blog posts. Occasionally there are also a flood of obscene blog posts made by the user themselves. Here's an example of what I mean: ![ ](https://wumbogames.github.io/cfPictures/Spam.png) #### This is obnoxious and I would like to see it stop. The current solution clearly doesn't work. As soon as they get banned or muted or whatever, they c...
Unrated Account Disaster ================== Recently there have been an obscene number of

Полный текст и комментарии »

  • Проголосовать: нравится
  • +761
  • Проголосовать: не нравится

83.
Автор SomethingNew, история, 3 года назад, По-русски
CodeTON Round 6 (Div. 1 + Div. 2, Rated, Prizes!) Editorial We apologize for the technical difficulties in Task B. We hope you enjoyed the rest of the contest. We will add hints soon. [problem:1870A] <spoiler summary="Tutorial"> Note that if $min(n, x+1) < k$, then the answer is $-1$. Otherwise, there are two cases: - If $k=x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, \dots, k-1]$. - If $k \ne x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, x, \dots, x]$. In both cases, we can construct the array and calculate its sum in linear time. The overall complexity is $O(n \cdot t)$. </spoiler> [problem:1870B] <spoiler summary="Tutorial"> Note that after performing the operation on $b_j$, which has some bit set to 1, this bit will become 1 for all numbers in $a$ (and will remain so, as a bit cannot change from 1 to 0 in the result of an OR operation). If $n$ is even, then in the final XOR, this bit will become 0, as it will be equal to the XOR of an even number of ones. If $n$ is odd, then ...
extremes, and at most one where it is the larger. Therefore, the total number of irreplaceable segments, - Create the number $x$ and clear the multiset. This is the same as creating the number $x$, but we

Полный текст и комментарии »

  • Проголосовать: нравится
  • +205
  • Проголосовать: не нравится

84.
Автор __baozii__, история, 17 месяцев назад, По-английски
DAG with exactly k distinct paths from vertex 1 to n Introduction ------------------ This blog is inspired by [this blog](https://codeforces.me/blog/entry/144391), which is an interesting constructive problem: - How to construct a DAG with no multiple edges, such that there exists exactly $k$ distinct paths from vertex $1$ to $n$? Obviously, there is a trivial solution which requires $2k$ edges and $k+2$ vertices. Simply connect vertex $1$ to each vertex numbered from $2$ to $k+1$, then connect each of these vertices to vertex $k+2$. In this blog, we shall discuss how to minimise the number of edges used. #### Using no more than $4 \log k+1$ edges This is likely to be the first way that many people will approach this problem. Consider the following structure: ![ ](/predownloaded/69/fb/69fbf07576dea0fe8e04164c6666037266e25bce.png) There are exactly $2$ distinct paths from $1$ to $3$. If we chain them together as such: ![ ](/predownloaded/84/56/8456f60da2c69e06416aef6e298baecf392c756c.png) There will be $2^3=8$ di...
case where all bits are set. However, in the fibonacci method, the number of distinct fibonacci, $. In this blog, we shall discuss how to minimise the number of edges used. #### Using no more than

Полный текст и комментарии »

  • Проголосовать: нравится
  • +214
  • Проголосовать: не нравится

85.
Автор installb, история, 15 месяцев назад, По-английски
Codeforces Round 1048 (Div. 1, Div. 2) Editorial [2139A &mdash; Maple and Multiplication](https://codeforces.me/contest/2139/problem/A) Idea: [user:installb,2025-09-08] Preparation: [user:installb,2025-09-08],[user:2014CAIS01,2025-09-08] <spoiler summary="Solution"> If $a=b$ we need $0$ steps. If $a$ can be divided by $b$, we only need $1$ step, which is to multiply $b$ by $\frac{a}{b}$. Same for the case when $b$ can be divided by $a$. Otherwise, we need at most $2$ steps. As both $a$ and $b$ are positive integers, we can first multiply $a$ by $b$ and then multiply $b$ by the original value of $a$. Both number will be equal to $a\times b$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; int solve(){ int a,b; cin >> a >> b; if(a == b) return 0; if(a % b == 0 || b % a == 0) return 1; return 2; } int main(){ ios::sync_with_stdio(false); int TC; cin >> TC; while(TC --){ cout <<...
To maximize the total number of cakes collected, ovens with larger $a_i$ should be visited later

Полный текст и комментарии »

Разбор задач Codeforces Round 1048 (Div. 1)
Разбор задач Codeforces Round 1048 (Div. 2)
  • Проголосовать: нравится
  • +235
  • Проголосовать: не нравится

86.
Автор Flamire, история, 12 месяцев назад, По-английски
Codeforces Round 1064 (Div. 1, Div. 2) Editorial [2166A &mdash; Same Difference](https://codeforces.me/contest/2166/problem/A) idea & solution: [user:le0n,2025-11-17] <spoiler summary="Tutorial"> It can be observed that $s_n$ will not change throughout the operations, therefore, for the final string to have every character the same, every character must be equal to $s_n$. To change every character to $s_n$, we can iterate over all characters from right to left, repeatedly setting $s_{i-1}\leftarrow s_i$ if $s_{i-1}\neq s_n$. Through this, we can need one operation for every character not equal to $s_n$, which is also obvious as a lower bound. Time complexity: $O(n)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; char s[100005]; int main() { int n, t, i, m; scanf("%d", &t); while(t--) { scanf("%d", &n); scanf("%s", s + 1); m = 0; for(i = 1; i < n; i++) m += (s[i] != s[n]); printf("%d\n", m); } return 0; } ~~~~~ </spoiler> ...
To analyze this, we can try performing scanline on the $val_3$ from large to small, we can perform

Полный текст и комментарии »

Разбор задач Codeforces Round 1064 (Div. 1)
Разбор задач Codeforces Round 1064 (Div. 2)
  • Проголосовать: нравится
  • +203
  • Проголосовать: не нравится

87.
Автор errorgorn, 5 лет назад, По-английски
Catalan Numbers and Generating Uniform Balanced Bracket Sequences Hi everyone! Today [user:nor,2022-05-27] sir and I would like to talk about generating uniform bracket sequences. Over the past few years when preparing test cases, I have had to generate a uniform bracket sequence a few times. Unfortunately I could not figure out how, so I would like to write a blog about this now. Hopefully this blog would be useful to future problem setters :) Scroll down to the end of the blog to copy our generators. First, let's define some things. A bracket sequence is a string with $n$ $\texttt{(}$ s and $n$ $\texttt{)}$ s. A **balanced** brackets sequence is a bracket sequence with the additional constraint that it becomes a valid arithmetic expression when we add some $\texttt{1}$ s and $\texttt{+}$ s. Let $p$ be the prefix sum array of a bracket sequence (we assign $1$ to $\texttt{(}$ and $-1$ to $\texttt{)}$ and take the prefix sum). For example, if our bracket sequence is $\texttt{())()((())}$, then $p=[1,0,-1,0,-1,0,1,2,1,0]$. An alternate way to thi...
\log n)$ anyways, but probably with a significantly large logarithm base., sequence as the number of lines in the above diagram that is below the $0$-line. So, the badness of our

Полный текст и комментарии »

  • Проголосовать: нравится
  • +205
  • Проголосовать: не нравится

88.
Автор adamant, 10 лет назад, По-русски
General ideas **// Finally translated!** Hi everyone! Do you like ad hoc problems? I do hate them! That's why I decided to make a list of ideas and tricks which can be useful in mane cases. Enjoy and add more if I missed something. :) [cut]<br> **1. Merging many sets in $O(n\log{n})$ amortized.** If you have some sets and you often need to merge some of theme, you can do it in naive way but in such manner that you always move elements from the smaller one to the larger. Thus every element will be moved only $O(\log{n})$ times since its new set always will be at least twice as large as the old one. Some versions of DSU are based on this trick. Also you can use this trick when you merge sets of vertices in subtrees while having dfs. **2. Tricks in statements, part 1.** As you may know, authors can try to hide some special properties of input to make problem less obvious. Once I saw constraints like $\relax 1 \leq a \leq b \leq 10^5, \dots, ab \leq 10^5$. Ha-ha, nice joke. It is actually...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +296
  • Проголосовать: не нравится

89.
Автор cadmiumky, 2 года назад, По-английски
Height-wise Small-to-Large Trick Hello Codeforces, I will present today, and in any day in the future, a means to correctly calculate a corner case of the well known small-to-large trick, and how this can be employed to solve a set of certain problems. This blog is written with encouragement from the [Month of Blog Posts](https://codeforces.me/blog/entry/133806) initiative. <spoiler summary="Forenote; Height definition"> The *height* of a node, as will be used throughout this blog, refers to the maximum distance in a rooted tree from a node to any of the leaves within its subtree. As a corollary, hereby it is considered that a leaf has a height of 1. </spoiler> ### The standard example. Let's try to solve the following problem: [Cat In a Tree, BOI 2017](https://oj.uz/problem/view/BOI17_catinatree). Although this problem can be solved employing some greedy algorithm, assume we have no idea what greedy is or how it could be correct, and revert to the basics: #### The standard DP. How can we formul...
Height-wise Small-to-Large Trick, along it, determine the sum of costs of all the paths whose length in number of edges is between $L, calculate a corner case of the well known small-to-large trick, and how this can be employed to solve a, equal to the number of nodes in the green chain (which signify one of the paths from that node to the, once. As such, the number of transitions is linear with respect to the number of nodes in the tree

Полный текст и комментарии »

  • Проголосовать: нравится
  • +208
  • Проголосовать: не нравится

90.
Автор Tony2_CF, история, 11 месяцев назад, По-английски
The Time Complexity Lower Bound for Segment Tree Beats is log^2 Original Post: https://jiry-2.blog.uoj.ac/blog/1404 The following content is translated by Gemini 2.5 Pro. ## Part 1: Introduction to the Hacking Method ### How to Map the Hack Sequence to a Segment Tree First, we are given a Hack sequence of length $len$. After $O(1)$ range addition operations and $\Theta(\log len)$ global $\text{chkmax}$ operations, this sequence becomes a cyclic shift (rotation) of the original sequence. Since a cyclic shift does not affect our range addition and global $\text{chkmax}$ operations (we can simply shift the indices for the range addition accordingly), we can consider the sequence as unchanged. If we have such a sequence, let $len=n^{\frac{1}{3}}$, and place such a sequence at intervals of $n^{\frac{2}{3}}$. Each sequence corresponds exactly to a segment tree interval. A subtree of size $n^{\frac{2}{3}}$ contains exactly one such segment tree interval. For the Hack sequence, the range addition operations are performed one by one on eac...
the $\text{chkmax}$ operation is performed uniformly $\log len=\log n$ times, the totalnumber of

Полный текст и комментарии »

  • Проголосовать: нравится
  • +767
  • Проголосовать: не нравится

91.
Автор Vladithur, история, 4 года назад, По-английски
Codeforces Round #842 (Div. 2) Editorial Hope you liked the problems! <spoiler summary="(from thanhchauns2) Before the round starts"> This is my second contest on Codeforces, inspiring coordination has been done for the last several months, cannot wait until the third round is released! <spoiler summary="Testers' predictions"> <table> <tr style ="background-color:#D3D3D3"> <th>Tester</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> <tr> <td>[user:xiaoziya,2022-12-13]</td> <td>900</td> <td>1000</td> <td>1400</td> <td>1800</td> <td>2100</td> <td>3000</td> </tr> <tr> <td>[user:feecle6418,2022-12-13]</td> <td>900</td> <td>1200</td> <td>1400</td> <td>1700</td> <td>2200</td> <td>2900</td> </tr> <tr> <td>[user:cadmiumky,2022-12-13]</td> <td>800</td> <td>1100</td> <td>1550</td> <td>1900</td> <td>2200</td> <td>-</td> </tr> <tr> <t...
Now try to brute force from $k - 1$ to $0$ for large numbers

Полный текст и комментарии »

Разбор задач Codeforces Round 842 (Div. 2)
  • Проголосовать: нравится
  • +237
  • Проголосовать: не нравится

92.
Автор adamant, история, 4 года назад, По-английски
Duality in linear programming. Part 1 — definition and construction Hi everyone! Previously I [wrote](https://codeforces.me/blog/entry/98334) about theoretical grounds of "aliens trick". Specifically, I introduced the concept of the Lagrangian duality and explained its connection with the trick. Today I want to elaborate a bit more on the concept of dual problems and their applications to linear programming as well as to common problems in competitive programming. I initially wanted to also write about some applications in competitive programming problems, but given that the introduction is already quite lengthy, I decided to leave it for another blog, while using most common and well-known theoretical examples here, focusing more on how to construct and interpret dual problems to begin with, rather than how to use it in contests. I think, it is a crucial first step towards using the duality in actual programming challenges. #### Prerequisites It is highly recommended to have some general understanding of basic mathematical optimization...
the largest possible number such that $\lambda^\top x \geq t(\lambda)$ for all $x \in X$. Equivalently

Полный текст и комментарии »

  • Проголосовать: нравится
  • +250
  • Проголосовать: не нравится

93.
Автор Geothermal, история, 3 года назад, По-английски
A Highly Experimental Training Plan for Beginners Very loosely inspired by some comments on [Thoughts on Reaching Cyan?](https://codeforces.me/blog/entry/101561) and [my recent AMA](https://codeforces.me/blog/entry/118845). Until now, I've avoided telling beginners to practice math before working on competitive programing problems because I haven't figured out a helpful way of doing so. This post is my attempt at telling grays to train math first in a way that might lead to improvement without an absurd time commitment. ## Introduction This section is largely motivation for why I'm proposing this training plan. If you just want to see the instructions for the training plan I'm proposing, you can skip this part. The first subsection in particular is not especially relevant to the rest of the post, but I wanted to have some documentation explaining why I still think the traditional "just solve problems" advice is good. ### The Conventional Advice on Improvement I'm frequently asked for advice on how to improve at co...
However, I've seen a large number of people, especially beginners, who at least appear to be

Полный текст и комментарии »

  • Проголосовать: нравится
  • +248
  • Проголосовать: не нравится

94.
Автор adamant, история, 2 года назад, По-английски
Double-ended eertree Hi everyone! Quite recently, a problem named [Palindromes in Deque](https://judge.yosupo.jp/problem/palindromes_in_deque) was added to the Library Checker that asks you to execute the following: 1. Add a character $c$ to the beginning or the end of a string $s$; 2. Remove a character from the beginning or the end of $s$. In-between the queries you also need to maintain the number of distinct palindromes, and the size of the largest prefix- and suffix-palindromes of the current string. The problem on Library Checker uses the approach from [Double-Ended Palindromic Trees](arxiv.org/abs/2210.02292) article by, presumably, [user:liouzhou_101,2024-06-10]. The paper is quite long though, so after briefly looking through introduction part to familiarize myself with their main concepts, I decided to do something a bit different than they did. In this blog, I will explain my approach. [cut] <hr> ### Recap First, let's briefly recall what an **eertree** is. If we consid...
In-between the queries you also need to maintain the number of distinct palindromes, and the size

Полный текст и комментарии »

  • Проголосовать: нравится
  • +133
  • Проголосовать: не нравится

95.
Автор Wind_Eagle, 5 лет назад, перевод, По-русски
Editorial of Codeforces Round 741 (Div. 2) <p align="right"><small>Will we, will you...<br>Can we, can you, can we change? <p align="left"> [problem:1562A] <spoiler summary="Hint 1"> Try to consider such segments where $l \le \lfloor \frac{r}{2} \rfloor + 1$. </spoiler> <spoiler summary="Hint 2"> Now think about what to do if this condition is not satisfied. </spoiler> <spoiler summary="Solution"> [tutorial:1562A] </spoiler> <spoiler summary="Code C++ (Wind_Eagle)"> ~~~~ #include <iostream> using namespace std; int l, r; void solve() { if (r < l * 2) { cout << r - l << endl; } else { cout << (r - 1) / 2 << endl; } } int main() { int t; cin >> t; while (t--) { cin >> l >> r; solve(); } } ~~~~ </spoiler> [problem:1562B] <spoiler summary="Hint 1"> Try to consider small numbers, such as those consisting of three digits. </spoiler> <spoiler summary="Hint 2"> Now think about what the maximum number of digits...
Now use the prime number you have found to find the largest prime, ::lower_bound_ works so fast that in an array of size $1.25 \cdot 10^7$ the same number of _std::lower_bound_, ? Maybe just **enough large** prime number would be enough? How can you find such anumber?

Полный текст и комментарии »

Разбор задач Codeforces Round 741 (Div. 2)
  • Проголосовать: нравится
  • +158
  • Проголосовать: не нравится

96.
Автор Gellyfish, 18 месяцев назад, По-английски
Codeforces Round 1028 (Div.1, Div.2) Editorial You could tell people didn't seem to like the match very much. I'm sorry I screwed up again ¯\\_(ツ)_/¯ If you're interested, I'd like to share some thoughts I have about this contest. <spoiler summary="sad story"> This time I've been trying my best to make the problems use more varied algorithms instead of just dp problems, but sadly [problem:2115C] was much harder than expected. But it seems like people are complaining more about the narrow time limit, centered on [problem:2116C] and [problem:2115C]. No one realized this before the contest, because none of the tester's code is get TLE except the wrong time complexity. I actually don't see a problem with the Time Limit of [problem:2116C]. Some of you may be puzzled, but let me try to explain this: - The intended solution is $O(\sum n \max(a) + \max(a)^2)$ and does not contain $\log \max(a)$. Computing $\gcd(x, y)$ is not $O(1)$, if you don't preprocess, then it's not unusual to actually get a TLE. - I believe the v...
We need to broaden the problem, so we try to be able to buy a negative number of cards with the

Полный текст и комментарии »

Разбор задач Codeforces Round 1028 (Div. 1)
Разбор задач Codeforces Round 1028 (Div. 2)
  • Проголосовать: нравится
  • +206
  • Проголосовать: не нравится

97.
Автор AksLolCoding, 9 месяцев назад, По-английски
Codeforces Round 1084 (Div. 3) Editorial Thanks to everyone who participated in this round! I hope you enjoyed the contest. <spoiler summary="Rate the contest!"> - Horrible contest - Bad contest - Average contest - Good contest - Peak contest </spoiler> <spoiler summary="Rate the difficulty!"> - Extreme contest - Hard contest - Normal contest - Easy contest - Trivial contest </spoiler> #### [problem:2200A] <spoiler summary="Rate the problem!"> - Horrible problem - Bad problem - Average problem - Good problem - Peak problem - Did not solve </spoiler> <spoiler summary="Tutorial"> [tutorial:2200A] </spoiler> <spoiler summary="Code (C++)"> ~~~ #include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (auto &i: a) cin >> i; ...
Making a small prime number appear in the array after a number with a

Полный текст и комментарии »

Разбор задач Codeforces Round 1084 (Div. 3)
  • Проголосовать: нравится
  • +103
  • Проголосовать: не нравится

98.
Автор pajenegod, история, 3 года назад, По-английски
Tutorial: A simple O(n log n) polynomial multiplication algorithm Hi Codeforces! I have something exciting to tell you guys about today! I have recently come up with a really neat and simple recursive algorithm for multiplying polynomials in $O(n \log n)$ time. It is so neat and simple that I think it might possibly revolutionize the way that fast polynomial multiplication is taught and coded. You don't need to know anything about FFT to understand and implement this algorithm. Big thanks to [user:nor,2023-07-10], [user:c1729,2023-07-10] and [user:spheniscine,2023-07-10] for discussing the contents of the blog with me and comming up with ideas for how to improve the blog =). I've split this blog up into two parts. The first part is intended for anyone to be able to read and understand. The second part is advanced and goes into a ton of interesting ideas and concepts related to this algorithm. Prerequisite: Polynomial quotient and remainder, see [Wiki article] (https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Euclidean_divi...
$Q(x)$ calculate $P(x) \, Q(x)$. The trick is simply to pick $n$ large enough such that $P(x) \, Q(x, unmodded polynomial product by picking $n$ large enough such that $(P(x) \, Q(x)) \% (x^n - c) = P(x

Полный текст и комментарии »

  • Проголосовать: нравится
  • +349
  • Проголосовать: не нравится

99.
Автор feecIe6418, история, 2 года назад, По-английски
Editorial of Codeforces Round 958 (Div. 2) Thanks for participation! **Update**: added alternative solutions/proofs for A,B,D,F [problem:1988A] <spoiler summary="Hint 1"> The optimal sequence of operations is very simple. </spoiler> <spoiler summary="Solution"> The optimal sequence of operations is adding $k-1$ 1-s into the set each time, at the same time decreasing $n$ by $k-1$. This implies that the answer is $\lceil \frac{n-1}{k-1}\rceil$. <spoiler summary="Why?"> I failed to find a Div2-A level proof. If you have a simpler proof please share it in the comments. Consider the number of elements that is $\equiv 1\pmod{(k-1)}$ in the set. The number of such elements increase by at most $k-1$ in each operation, and the aforementioned sequence of operation achieves the maximum increment. --- A simpler proof in the comments: consider the number of elements in the set. It increases by at most $k-1$ each time, and our construction reaches the maximum increment. </spoiler> </spoiler> <spoiler summar...
Observe that the number of 1 never increases in an operation

Полный текст и комментарии »

Разбор задач Codeforces Round 958 (Div. 2)
  • Проголосовать: нравится
  • +147
  • Проголосовать: не нравится

100.
Автор ZhouShang2003, 2 года назад, По-английски
Pinely Round 4 (Div. 1 + Div. 2) Editorial ## [1991A &mdash; Maximize the Last Element](https://codeforces.me/contest/1991/problem/A) <spoiler summary="Hint"> Consider the parity of the position. </spoiler> <spoiler summary="Solution"> The answer is the maximum value of the elements at odd indices. **Proof** <ol> <li>Any element at an odd index can be preserved until the end.<br><br> Since each element at an odd index has an even number of elements on both sides, pairs of adjacent elements can be removed from left to right until only the element at the odd index remains. For example, if you want to keep the element at the $i$-th position, you can remove the elements at positions $1$ and $2$, $3$ and $4$, and so on, until the elements at positions $i-2$ and $i-1$ are removed. Then, continue removing elements at positions $i+1$ and $i+2$, and so on, until the elements at positions $n-1$ and $n$ are removed. Therefore, any element at an odd index can be preserved through this method.<br><br> </li> <li>No ...
away our smallest number and give us the second smallest number. Thus, in the worst case, the, choosing from the large numbers in each T-shaped tile, allowing us to choose the smallnumber, indicating tiles division, green cells representing small numbers, and red cells representinglarge, interactor to choose the largest number, $n \cdot m$. , surrounding three cells with large numbers. This way, we can always select the smallestnumber from, tiles division, green cells representing small numbers, and red cells representinglarge numbers.">, If a small number is surrounded by large numbers in a tile, as the second chooser we can choose the, In the worst case, we will choose the larger number in each domino. However, the interactor will, Our strategy is as follows: If the interactor chooses a number from a domino and the othernumber, Specifically, we define $[1, 4]$ as small numbers, and $[n \cdot m - 11, n \cdot m]$ aslarge, We divide the grid into: * $4$ T-shaped tiles, each with a small number at the edge of, number, $n \cdot m$. Specifically, we can divide the grid into: * $\lfloor \frac{n \cdot m

Полный текст и комментарии »

Разбор задач Pinely Round 4 (Div. 1 + Div. 2)
  • Проголосовать: нравится
  • +164
  • Проголосовать: не нравится

101.
Автор Enchom, 4 года назад, По-английски
The 100 prisoner problem if you want NO prisoner to find their number The classical problem goes as follows: There are 100 numbered prisoners and 100 ordered boxes containing their numbers (1 per box). Each prisoner goes into the room with boxes alone and must open and look into 50 of them one by one. After leaving, all boxes are closed. A prisoner cannot reorder or otherwise modify the boxes. Each prisoner does this separately from the others and they can't leave any clues behind. The prisoners are allowed to sync on strategies beforehand. The original question asks about the best strategy if the goal is for **ALL** of them to find their own number. The answer is to follow the permutation chains, i.e. look into the box that's labeled with their own number and then look into the box with the number they saw inside it and repeat. This gives >30% success rate for arbitrary $N$ boxes ($N=100$ in the example) because if there is no permutation cycle of length larger than $N/2$, all prisoners will find their number, and the odds of that happening can be...
The 100 prisoner problem if you want NO prisoner to find their number, own number. The answer is to follow the permutation chains, i.e. look into the box that's labeled, question asks about the best strategy if the goal is for **ALL** of them to find their ownnumber. The

Полный текст и комментарии »

  • Проголосовать: нравится
  • +98
  • Проголосовать: не нравится

102.
Автор ChthollyNotaSeniorious, история, 4 года назад, По-английски
Polynomial Round 2022 (Div. 1 + Div. 2) Editorial Thanks for your participation! I am so sorry for my careless review. We were preparing for this round for many months and made some problems which writers and testers are all like. We do want to give everyone a good time to enjoy the contest. But carelessness is deadly. In problem B, some test cases should have been made, but we missed them in not only the pretests but also the final tests. In fact, we had not noticed it until some suspicious hacks appeared. I and all co-authors sincerely regret our mistake and hope you can forgive us. Besides, few people are cyberbullying authors, please do not do so. If you have a bad experience, you can downvote me because of our fault. [problem:1774A] Idea: [user:cirno_9baka,2022-12-17] <spoiler summary="Solution"> The answer is the number of $1$s modulo $2$. We can get that by adding '-' before the $\text{2nd}, \text{4th}, \cdots, 2k\text{-th}$ $1$, and '+' before the $\text{3rd}, \text{5th}, \cdots, 2k+1\text{-th}$ $1$. </spoiler...
it. We can use observation to solve the problem. Consider each element from large to small. Suppose, will result in the number of pigs generated before multiplying by $2$. Therefore, we also need to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +393
  • Проголосовать: не нравится

103.
Автор Shisuko, история, 8 лет назад, По-английски
The Intuition Behind NIM and Grundy Numbers in Combinatorial Game Theory There are already many wonderful resources online for learning the basics to combinatorial game theory, but the intention I have for _this_ guide in particular is to try to make them more intuitive. Why does XOR work for Nim? Why does mex produce the Grundy numbers? When it was taught to me, it was more or less just as 'magic' to memorize, but now I think I have a decent understanding of why they are true, so now that I have a grasp of the intuition behind it, I decided I should record my thoughts into a blog. Nim games ================== Suppose we are playing a Nim game. As we know, Nim games usually follow this sort of template: - There are $n$ piles of stones, and each pile contains $p_1, p_2, p_3, \cdots p_n$ stones, where each of the $p_i$ is some nonnegative integer. This collection of piles defines our game state. - There are two players who take turns removing stones. The current turn player may remove as many stones as they wish, so long as all the stones come f...
from the same pile. More formally, they choose a pile $i$ and a number of stones to remove $0 < s, stones" is just the same as normal Nim. Suppose I started with a Grundy number of $g$, then after making

Полный текст и комментарии »

  • Проголосовать: нравится
  • +173
  • Проголосовать: не нравится

104.
Автор Kevin114514, история, 4 года назад, По-английски
CodeForces Round 872(Div. 1&2) Editorial ## A. LuoTianyi and the Palindrome String Consider the substring of $s$ from the second character to the last, or $s_2s_3\cdots s_n$. If it's not palindrome, then the answer must be $n-1$. What if it's palindrome? This implies that $s_2=s_n$, $s_3=s_{n-1}$, and so on. Meanwhile, the fact that $s$ is palindrome implies $s_1=s_n$, $s_2=s_{n-1}$, etc. So we get $s_1=s_n=s_2=s_{n-1}=\cdots$ or that all characters in $s$ is the same. In this situation, every subsequence of $s$ is palindrome of course, so the answer should be $-1$. <spoiler summary="Code"> ```cpp #pragma GCC optimize(3,"Ofast","inline") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //#define ll int #define ft first #define sd second //#define endl '\n' #define pb push_back #define ll long long #define pll pair<ll,ll> #define no cout<<"NO"<<'\n' #define no_ cout<<"No"<<'\n' #def...
Now all the subtables have the same minimum value, we want to maximize the number of subtables

Полный текст и комментарии »

Разбор задач Codeforces Round 872 (Div. 1)
Разбор задач Codeforces Round 872 (Div. 2)
  • Проголосовать: нравится
  • +74
  • Проголосовать: не нравится

105.
Автор zltzlt, история, 2 года назад, По-английски
Codeforces Round 968 (Div. 2) Editorial Thank you for your participation! <spoiler summary="Rating Predictions"> | Person | A | B | C | D1 | D2 | E1 | E2 | F | | :----------: | :----------: | :----------: | :----------: | :----------: | :----------: | :----------: | :----------: | :----------: | | [user: zltzlt, 2024-8-25] | 800 | 1100 | 1500 | 1300 | 2100 | 2100 | 2300 | 2500 | | [user: WRuperD, 2024-8-25] | 800 | 1200 | 1400 | 1800 | 2300 | 2400 | 2600 | 2800 | | [user: Ender32k, 2024-8-25] | 800 | 1100 | 1400 | 1900 | 2200 | | | | | [user: yinhee, 2024-8-25] | 900 | 1200 | 1600 | 1500 | 1900 | 2400 | 2500 | 2700 | | [user: Jryno1, 2024-8-25] | 800 | 1100 | 1500 | 1500 | 1800 | | | | | [user: yeminghan, 2024-8-25] | 800 | 900 | 1500 | 1400 | 1900 | 2700 | 2800 | | | [user: wutongchun, 2024-8-25] | 800 | 900 | 1300 | 1500 | 1900 | 2700 | | 3000 | | [user: small_peter, 2024-8-25] | 800 | 1200 | 1600 | 1900 | 1900 | | | | | [user: DisconnectedGraph, 2024-8-25] | 800 | 1200 | 1400 | 1700 | 2000 | 2000 | 2600 | | ...
Divide all numbers into small numbers and large numbers.

Полный текст и комментарии »

Разбор задач Codeforces Round 968 (Div. 2)
  • Проголосовать: нравится
  • +117
  • Проголосовать: не нравится

106.
Автор null_awe, 2 года назад, По-английски
Codeforces Global Round 26 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-06-08] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:null_awe,2024-06-08] | 800 | 1000 | 1200 | 1700 | 2200 | 2400 | 2500 | 2900 | 3400 | | [user:buffering,2024-06-08] | 800 | 1000 | 1300 | 1800 | 2300 | 2400 | 2600 | 3100 | 3500 | | [user:redpanda,2024-06-08] | 800 | 1100 | 1200 | 1800 | | | | | | | [user:thescrasse,2024-06-08] | 800 | 1000 | 1200 | 1600 | 2200 | 2500 | 2500 | 3100 | 3400 | | [user:bronze_coder,2024-06-08] | 800 | 1000 | 1600 | 1800 | 2400 | | | 2700 | 3500 | | [user:awesomeguy856,20...
largest number to the very end, then we basically have an array of length $n - 1$ with $k = n - 3

Полный текст и комментарии »

Разбор задач Codeforces Global Round 26
  • Проголосовать: нравится
  • +294
  • Проголосовать: не нравится

107.
Автор GlowCheese, 2 года назад, По-английски
Editorial of Codeforces Round 963 (Div. 2) [problem:1993A] <spoiler summary="Hint"> What is the pattern of Tim's answer sheet that can give him maximum score? </spoiler> <spoiler summary="Solution"> Let's say there are $n$ problems take $A$ as the answer, therefore he can only get $n$ points with the answer $A$. The same is correct for $B$, $C$ and $D$. Therefore, the maximum score can be achieved is $min(n, A) + min(n, B) + min(n, C) + min(n, D)$. Time complexity: $O(4n)$ </spoiler> <spoiler summary="Code (python)"> ~~~~~ t = int(input()) for _ in range(t): n = int(input()) s = input() print(sum(min(n, s.count(c)) for c in "ABCD")) ~~~~~ </spoiler> [problem:1993B] <spoiler summary="Hint 1"> Find a way to make all the elements even. Then odd. </spoiler> <spoiler summary="Hint 2"> In the worst case, the number of operations required is the number of even elements + 1. Why? </spoiler> <spoiler summary="Solution"> First, if all elements already have the same parity, we don'...
1. If $t < s$, $s+t$ becomes largest odd number. Thus, we set $s := s+t$. This reduce thenumber of

Полный текст и комментарии »

Разбор задач Codeforces Round 963 (Div. 2)
  • Проголосовать: нравится
  • +218
  • Проголосовать: не нравится

108.
Автор TheScrasse, 5 лет назад, По-английски
Editorial of Codeforces Round #778 (Div. 1 + Div. 2, based on Technocup 2022 Final Round) [problem:1654A] Author: [user:TheScrasse,2022-02-24]<br> Preparation: [user:TheScrasse,2022-02-19] <spoiler summary="Hint 1"> Suppose you want to choose pieces of cake $i$, $j$. Can you make them adjacent in $1$ move? </spoiler> <spoiler summary="Solution"> The answer is the sum of the $2$ maximum weights. You can always pick the $2$ maximum weights: if they are $a_i$ and $a_j$ ($i < j$), you can flip the subsegment $[i, j-1]$ to make them adjacent. The result can't be larger, because the sum of the weights of any $2$ pieces of cake is never greater than the sum of the $2$ maximum weights. Iterating over all pairs of pieces of cake is enough to get AC, but you can solve the problem in $O(n \log n)$ by sorting the weights and printing the sum of the last $2$ values, or even in $O(n)$ if you calculate the maximum and the second maximum in linear time. Complexity: $O(t \cdot n^2)$, $O(t \cdot n \log n)$ or $O(t \cdot n)$ </spoiler> Official solution: [submissi...
As explained in the hints, instead of computing the fewest number of

Полный текст и комментарии »

  • Проголосовать: нравится
  • +133
  • Проголосовать: не нравится

109.
Автор employed, история, 7 недель назад, По-английски
Editorial of DeepInfra Round 1 (Codeforces Round 1126, Div. 1 + Div. 2) thanks to [user:nifeshe,2026-10-10] for making my life easier with templates [problem:2271A] <spoiler summary = "Hints"> <spoiler summary = "Hint 1"> After performing $z$ operations, the robot's $x$-coordinate is exactly $z$. </spoiler> <spoiler summary = "Hint 2"> After completing any operation, the $x$-coordinate and $y$-coordinate always have the same parity. </spoiler> <spoiler summary = "Hint 3"> Try to find a construction to reach any point $(x,y)$ where $y\le x$ and $x$ and $y$ have the same parity. </spoiler> </spoiler> <spoiler summary = "Solution"> Notice that after performing $z$ operations, the robot's $x$-coordinate will be exactly $z$, while its $y$-coordinate cannot exceed $z$. We will first consider the case $b\le a$, then handle the special case $b=a+1$. Notice that the robot can reach any point $(x,y)$ where $0\le y\le x$ and $x$ and $y$ have the same parity in exactly $x$ operations. To do so, we can first move up until reaching $y$...
Binary search on the number of splits. When processing backward

Полный текст и комментарии »

  • Проголосовать: нравится
  • +182
  • Проголосовать: не нравится

110.
Автор neal, 8 лет назад, По-английски
How randomized solutions can be hacked, and how to make your solution unhackable Hi Codeforces! In Round 507 earlier today, a large number of "mostly correct" randomized solutions on [problem:1039B] were hacked. I wanted to write a quick explanation of how it's possible to hack these, as well as a guide on how to write your code so that you aren't vulnerable to getting hacked. First to go over the solution quickly (skip down a few paragraphs if you already know the solution): one can use binary search to reduce the range of possible locations for the train to a constant multiple of $K$, such as $6K$. Just make sure to expand out both ends of the range by $K$ after every iteration. Once the range is at most $6K$, one can repeat the following: 1) Make a random guess out of the remaining numbers. The probability of success is at least $\frac{1}{6K}$. 2) Binary search again until the range is at most $6K$ again. It turns out this only takes one query, since after our previous guess our $6K$ range will become an $8K$ range, and a single query will reduce this t...
Hi Codeforces! In Round 507 earlier today, a large number of "mostly correct" randomized solutions

Полный текст и комментарии »

  • Проголосовать: нравится
  • +271
  • Проголосовать: не нравится

111.
Автор Qingyu, 5 месяцев назад, По-английски
assert in GCC 16 As you might have heard, in the newest version of GCC, `<cassert>` is no longer included by `<bits/stdc++.h>` (you can view the change [here](https://github.com/gcc-mirror/gcc/commit/eaf6b40f761049ba4f74fd8bf1bc011e3c59c53b)). This means that the following code will now fail to compile: ```cpp #include <bits/stdc++.h> int main() { assert(1); } ``` <spoiler summary="Compilation Result"> ```plain test.cpp: In function ‘int main()’: test.cpp:4:5: error: ‘assert’ was not declared in this scope 4 | assert(1); | ^~~~~~ test.cpp:2:1: note: ‘assert’ is defined in header ‘<cassert>’; this is probably fixable by adding ‘#include <cassert>’ 1 | #include <bits/stdc++.h> +++ |+#include <cassert> 2 | ``` </spoiler> I noticed this issue during a recent compiler update on QOJ, where it broke a large number of older submissions. Because of this, I have reverted the compiler back to GCC 15.2.0 for now. Of course, this is not the first ti...
I noticed this issue during a recent compiler update on QOJ, where it broke a large number of older

Полный текст и комментарии »

  • Проголосовать: нравится
  • +339
  • Проголосовать: не нравится

112.
Автор sslotin, 5 лет назад, По-английски
A chapter on SIMD algorithms Hi everyone! I'm writing [a book](https://en.algorithmica.org/hpc) on performance engineering, and a few days ago, I finished a draft of one of its main crown jewels: the [SIMD programming chapter](https://en.algorithmica.org/hpc/simd/). The main findings that are published: - You can compute [array sums](https://en.algorithmica.org/hpc/simd/reduction/) and other reductions such as the minimum 2x faster than `std::accumulate` or an auto-vectorized loop would. - You can sometimes [copy and assign memory](/hpc/cpu-cache/bandwidth/#bypassing-the-cache) 2x faster than `memcpy` and `memset` respectively. - You can [search array elements](https://en.algorithmica.org/hpc/simd/masking/#searching) 10x times faster than `std::find` or manually. - You can [count a value](https://en.algorithmica.org/hpc/simd/masking/#counting-values) in an array 1.5x faster than `std::count` or manually. - You can calculate [population counts](https://en.algorithmica.org/hpc/simd/shuffing/#shuffles-and-p...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +503
  • Проголосовать: не нравится

113.
Автор Um_nik, 8 лет назад, По-английски
How to read problem statements But [user:Um_nik,2018-10-26], we all know how to read, we have our whooping 2 month of experience! Oh, my sweet summer child, my experiments show that many people with kinda cool achievements like medals on ROI don't know how to read statements. But don't worry, I'll teach you. Well, probably you won't understand anything, because you didn't try to understand anything in your life, you expect all hard work to be done for you by someone else. Let's start! Basic rules ================== - The result of reading the statement is usually pure math model. If story helps to build correct understanding, you can keep it, but still try to discard as many unnecessary details as possible. - Imagine you want to tell the problem to someone else. What parts you want to tell? (According to my PM, this rule won't help you). - Shorter = better. - Simpler = better. - Limitations are part of problem statement. Especially small limitations, because for small data you can try all the possib...
minimal number of matchings to cover all the edges. After

Полный текст и комментарии »

  • Проголосовать: нравится
  • +381
  • Проголосовать: не нравится

114.
Автор SomethingNew, 4 года назад, перевод, По-русски
Codeforces Round #814 (Div. 1, Div. 2) Editorial Sorry for not very good samples, and late editorial. It was our first round, so it was wary stressful for us, But we hope you liked the problems despite this! [problem:1719A] <spoiler summary="Hint 1"> Try to look at the parity of $n, m$. </spoiler> <spoiler summary="Hint 2"> The player who wins does not depend on player's strategy. </spoiler> <spoiler summary="Hint 3"> The only thing that the winning player depends on is the parity of $n, m$. </spoiler> <spoiler summary="Tutorial"> Note that the game will end only when the chip is in the upper right corner (otherwise you can move it $1$ square to the right or up). For all moves, the chip will move $n - 1$ to the right and $m - 1$ up, which means that the total length of all moves is $n + m - 2$ (the length of the move is how much the chip moved per turn). Since the length of any move is odd, then after any move of Burenka, the sum of the lengths will be odd, and after any move of Tonya is even. So we can find...
$c_j, c_x$ will be greater than $F_i$, if we don't take it, then at the next step thisnumber will be, define $dp[mask][big]$ (in addition to the mask, there is a large prime $big$) and $dp[mask][case]$ (in, Let's try to type the answer greedily, going from large Fibonacci numbers to smaller ones. For the, large numbers that in the product give a number not exceeding $10 ^ 5$. There will be 4904 such pairs.

Полный текст и комментарии »

Разбор задач Codeforces Round 814 (Div. 1)
Разбор задач Codeforces Round 814 (Div. 2)
  • Проголосовать: нравится
  • +129
  • Проголосовать: не нравится

115.
Автор dreamoon_love_AA, 12 лет назад, По-английски
Codeforces Round #292 Editorial Thanks to [user:johnathan79717,2015-03-10] fo polish my words. #### [515-A Drazil and Date](http://codeforces.me/problemset/problem/515/A) If Drazil chooses the shortest path from (0,0) to (a,b), it takes $|a| + |b|$ steps. So we know that all numbers less than $|a| + |b|$ are impossible to be the number of steps that Drazil took. Now consider when the number of steps is not less than $|a| + |b|$. When Drazil arrives at $(a,b)$, he can take two more steps such as $(a,b)$ -> $(a,b+1)$ -> $(a,b)$ to remain at the same position. So we know that for all $s$ such that $s \geq |a| + |b|$ and $(s - (|a| + |b|)) \% 2 = 0$, there exists a way for Drazil to get to $(a,b)$ in exactly $s$ steps. The last part we should prove is that it's impossible for Drazil to arrive at (a,b) in exactly $s$ steps when $(s - (|a| + |b|)) \% 2 = 1$. We can color all positions $(x,y)$ where $(x+y) \% 2 = 0$ as white and color other points as black. After each step, the color of the p...
4,6,8,9 to more digits as in the conclusion, and it makes the number larger., number whose factor is different in the two ways.

Полный текст и комментарии »

Разбор задач Codeforces Round 292 (Div. 2)
  • Проголосовать: нравится
  • +132
  • Проголосовать: не нравится

116.
Автор pajenegod, история, 6 лет назад, По-английски
Explanation to weird/strange floating point behaviour in C++ # Introduction I'm writing this blog because of the large number of blogs asking about why they get strange floating arithmetic behaviour in C++. For example: "WA using GNU C++17 (64) and AC using GNU C++17" https://codeforces.me/blog/entry/78094 "The curious case of the pow function" https://codeforces.me/blog/entry/21844 "Why does this happen?" https://codeforces.me/blog/entry/51884 "Why can this code work strangely?" https://codeforces.me/blog/entry/18005 and many many more. # Example Here is a simple example of the kind of weird behaviour I'm talking about <spoiler summary="Example showing the issue"> ~~~ #include <iostream> using namespace std; double f(double a, double b) { return a * a - b; } int main() { cout.precision(60); // Calculate 10*10 - 1e-15 double ans; ans = f(atof("10"), atof("1e-15")); cout << (double) ans << '\n'; cout << (int) ans << "\n\n"; ans = f(atof("10"), atof("1e-15...
I'm writing this blog because of the large number of blogs asking about why they get strange

Полный текст и комментарии »

  • Проголосовать: нравится
  • +187
  • Проголосовать: не нравится

117.
Автор PinkieRabbit_buster, 3 года назад, По-английски
PinkieRabbit Cheated in Div. 1 Contest on Apr 27 I am writing to report an incident of cheating by PinkieRabbit during the recent contest 1965 on Codeforces. **PinkieRabbit asked help about problem D from others during the contest,** which is definitely against the contest rules. I have attached the evidence of the cheating behavior in the appendix, please read it. This evidence clearly shows the communications PinkieRabbit had with another person during the contest. It is a contest recording video published after contest by himself. As a former fan of PinkieRabbit, after seeing this video, I was shocked by how dishonest PinkieRabbit was. I believe such actions undermine the integrity of the competition and the platform as a whole. [user:win114514,2024-05-05] cheated by grouping up in contest 1905, finally punished by skipping. Therefore, I respectfully request that Codeforces take appropriate action against PinkieRabbit to maintain the fairness of the contests on Codeforces. He only cheated in one problem this round, so I sugg...
two comments may require an account registration with a phone number in order to be displayed. If

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1076
  • Проголосовать: не нравится

118.
Автор Proof_by_QED, история, 6 недель назад, По-английски
About example test cases I'm the coordinator of [contest:2261]. After the contest ended, I am disappointed to see some people complaining about the weak samples in the comments of the announcement. I agree that the samples in some problems (A, C, D1) are weak. But this was an intentional decision during the problem preparation process, and I am here to defend this decision. This post will contain an overview of what I believe samples should be used for, what good samples (not necessarily strong samples) look like from both a participant and problemsetting point of view. ### What are samples for? The most important function of samples and notes are for making sure the participant understands the problem statement. If samples and notes do not clarify confusion a participant may have about the problem after reading the statement carefully, I would say that's a bad set of samples. The second function of samples, especially for interactive and constructive problems, are for showing the output/interaction ...
code that passes samples will fail on a hidden test case. This usually means including alarge number

Полный текст и комментарии »

  • Проголосовать: нравится
  • +191
  • Проголосовать: не нравится

119.
Автор MikeMirzayanov, 8 лет назад, По-русски
Codeforces: Results of 2018 Hi Codeforces! February 2019 is already on the calendar, which means that I was late with the report for 2018. Better late than never! Let's remember last year. In 2018, [user:_kun_,2019-02-05], [user:300iq,2019-02-05] and [user:arsijo,2019-02-05] joined the team of coordinators. The work of the coordinators is headed (and is the coordinator of the coordinators) [user:KAN,2019-02-05]. I really hope that a more measured schedule of preparing rounds by a large team of coordinators will give a better insight into the contests. The main innovations in the platform are implemented by me and the developers [user:kuviman,2019-02-05], [user:fcspartakm,2019-02-05], [user:MaximShipko,2019-02-05]. Great work on the organization of events and prizes mailing was done by [user:gKseni,2019-02-05]. Special thanks to the writers of the problems and testers. It is your content that charges the community with life and unites all of us. Thank you for the problems! And now let's summarize...
really hope that a more measured schedule of preparing rounds by a large team of coordinators will

Полный текст и комментарии »

  • Проголосовать: нравится
  • +871
  • Проголосовать: не нравится

120.
Автор RDDCCD, история, 4 года назад, По-английски
Editorial of CodeTON Round 4 (Div. 1 + Div. 2, Rated, Prizes!) [A. Beautiful Sequence](https://codeforces.me/contest/1810/problem/A) <spoiler summary="Hint"> What is the necessary and sufficient condition? </spoiler> <spoiler summary="Tutorial"> The necessary and sufficient condition for a beautiful sequence is that there exist one $i$, such that $a_{i} \le i$. Just check the sequence for the condition. </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int a[100005]; void solve() { int n; scanf("%d",&n); for(int i =1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= n;i++) { if(a[i] <= i) { puts("YES"); return; } } puts("NO"); } int main() { int t;scanf("%d",&t); while(t--) solve(); } ~~~~~ </spoiler> [B. Candies](https://codeforces.me/contest/1810/problem/B) <spoiler summary="Hint"> How the binary representation changes after an operation? </spoiler> <spoiler summary="Tutorial"...
Let $num_{i}$ be the number of occurances of integer $i$ in the array

Полный текст и комментарии »

  • Проголосовать: нравится
  • +269
  • Проголосовать: не нравится

121.
Автор cfalas, 3 месяца назад, По-английски
Some IOI 2026 Statistics Hey everyone, IOI2026 is over! Congratulations to everyone who participated for their hard efforts. While all the contestants were struggling to solve the problems, I had some free time so I looked into some stats. Some notes before we get into things: - It is entirely possible that some of these are wrong/incomplete/misleading. I only made these to satisfy my own curiosity, and they are not an authoritative source - I expect this to be particularly true for medal cutoffs, where I have not accounted for unofficial contestants Thanks to all the organizers for making IOI2026 a great event! [cut] I try to break them down by category so that this blog doesn’t get too long: IOI vs Codeforces ------------------ This has been well researched before, ([here](https://codeforces.me/blog/entry/145502), [here](https://codeforces.me/blog/entry/134654), [here](https://codeforces.me/blog/entry/68981), [here](https://codeforces.me/blog/entry/57700), and [here](https://codefor...
we can see a very large number of outliers between day 1 and day 2 ranks):

Полный текст и комментарии »

  • Проголосовать: нравится
  • +283
  • Проголосовать: не нравится

122.
Автор Um_nik, 8 лет назад, По-английски
How not to read problem statements I wanted to write super-harsh blog but then I decided to split it into educational part and whining part. This is whining part. To read some cool stuff go [here](https://codeforces.me/blog/entry/62730). This one will also be educational on a slightly different topic. And there will be A LOT of harsh stuff. I'm not saying that I'm perfect. That round had some really bad problemsetting issues. Problem E was googleable, problem D had very weak tests against very stupid solution (so stupid that none of the authors and testers come up with it, moreover, it is so counter-intuitive that I don't know how so many people independently did it). In two constructive problems participants could look at jury's output, the feature of which I didn't know. And I'm sorry for these issues. BUT. [This comment](https://codeforces.me/blog/entry/62614#comment-466588) has very negative rating despite being so true. And no one are here to back me up. So I want to speak my truth as I always do. Let me ac...
CF has a large number of participants in each round. If 5% of participants think that his/her time

Полный текст и комментарии »

  • Проголосовать: нравится
  • +157
  • Проголосовать: не нравится

123.
Автор purplesyringa, история, 5 лет назад, По-английски
Analysis of polynomial hashing Unfortunately, most derivations of the chance of polynomial hashing collision are invalid, wrong, or misleading, and finding reliable public sources with proofs is incredibly difficult. This article is a formal analysis of the method. The goal of this article is to complement well-known empirical facts with theory, provide boundaries on the probability of collision, justify common choices, and advise against certain popular parameters. There is no code in this article, and it's mostly theoretical. It's more of a summa of everything we know about polynomial hashing in integers rather than a guide for beginners. You'll probably find something of interest still. I do, however, describe some methods of cracking hashes, which I can provide code and additional explanation for if someone asks in the comments and some general guidelines in the last section of the present article. ## Table of contents - The concept of polynomial hashing - Classical justification of the coprimality r...
collision probability would be 1336 times as large as that of the 20 numbers of order $M - 1$. Knowing, is a series of consecutive integers). Alas, this means $H(s)$ may be an arbitrarilylarge number

Полный текст и комментарии »

  • Проголосовать: нравится
  • +308
  • Проголосовать: не нравится

124.
Автор neal, 7 лет назад, По-английски
Improved time complexity bound for Round 614 problem F, with an elegant proof Given the numbers $1, 2, \dots, 20$, you want to choose some subset of these numbers such that no number you choose is divisible by any other number you choose. What's the largest subset you can get? One simple idea is to choose all the primes: 2, 3, 5, 7, 11, 13, 17, and 19, leading to a subset of size 8. But you can do better! Try to figure out the solution yourself before reading below. For [problem:1292F] from Round 614 Div. 1, after you make several observations and pull out a sick counting DP, you get [a solution](https://codeforces.me/contest/1292/submission/69271989) that is $\displaystyle \mathcal{O} \left (N^2 \cdot 2^S \right )$, where $S$ is the number of values in our array $A$ that are 1) not divisible by any other value in $A$ and 2) have at least two other values in $A$ divisible by it. (These are the only values we should consider using as $a_i$ in the operation described in the problem.) So what is that time complexity really? Don't worry if you haven't actu...
, \dots, 20$, what is the largest subset of these numbers we can choose such that nonumber we choose is, Every number occurs in exactly one chain, and we can never take two numbers from the same chain. So, number you choose is divisible by any other number you choose. What's the largest subset you can get

Полный текст и комментарии »

  • Проголосовать: нравится
  • +141
  • Проголосовать: не нравится

125.
Автор Errichto, 11 лет назад, По-английски
Editorial of SRM #673 Div2 ------------------ [Codes for all Div2 problems](http://ideone.com/FO7ixD) **BearSong (250p.)** There are two ways to solve this problem. The first way is to create an array $T$ of size 1000 to count occurrences of each note. For each number $x$ in the given sequence we should do `T[x]++`. After that, we should iterate over $T$ and count the number of indices with value $1$. There is an alternative $O(N^2)$ solution. For each element of the given sequence we can iterate over other elements to check whether some of them is equal to the current one. **BearSlowlySorts (500p.)** Again, there are two ways to solve a problem. The first one is quite boring. One could notice that the answer must be small and we can simulate first few moves in any possible way. Some extra observation is that after sorting the first N-1 we shouldn't sort them again in the next move. So we should either do moves in the order {first, last, first, last, ...} or {last, first, last, fir...
observation is that we care mostly about the smallest number and the largest one. - The answer is 0 only

Полный текст и комментарии »

  • Проголосовать: нравится
  • +139
  • Проголосовать: не нравится

126.
Автор adamant, история, 5 лет назад, По-английски
Fast polynomial composition Hi everyone! Today I want to describe an efficient solution of the following problem: <hr> **[Composition of Formal Power Series](https://judge.yosupo.jp/problem/composition_of_formal_power_series)**. Given $A(x)$ and $B(x)$ of degree $n-1$ such that $B(0) = 0$, compute $A(B(x)) \pmod{x^n}$. <hr> The condition $B(0)=0$ doesn't decrease the generality of the problem, as $A(B(x)) = P(Q(x))$, where $P(x) = A(x+B(0))$ and $Q(x) = B(x) - B(0)$. Hence you could replace $A(x)$ and $B(x)$ with $P(x)$ and $Q(x)$ when the condition is not satisfied. Solutions that I'm going to describe were published in Joris van der Hoeven's [article](https://www.sciencedirect.com/science/article/pii/S0747717102905626) about operations on formal power series. The article also describes a lot of other common algorithms on polynomials. It is worth noting that Joris van der Hoeven and David Harvey are the inventors of the breakthrough $O(n \log n)$ [integer multiplication algorithm](https://hal.archi...
**Large factorial**. You're given two numbers $n$ and $m$. Compute $n! \mod m$ for $n \leq 10

Полный текст и комментарии »

  • Проголосовать: нравится
  • +133
  • Проголосовать: не нравится

127.
Автор Endagorion, 12 лет назад, перевод, По-русски
Codeforces Round #265 Editorial I'll upload my example solutions and will post links to them as soon as it becomes possible. Some of the problems editorials contain an additional challenge which is apparently harder to comprehend than the original problem. Feel free to share and discuss your ideas in the comments. =) [problem:465A] If we add 1 to a number, its binary representation changes in a simple way: all the least significant $1$'s change to $0$'s, and the single following $0$ changes to $1$. It suffices to find the length of largest suffix which contains only $1$'s, suppose its length is $l$. Then the answer is $l+1$ except for the case when all the string consists of $1$, when the answer is $l$. It is amusing that div1E problem is concerned with addition of 1 to a binary integer as well. =) [problem:465B] Optimal strategy is as follows: for every segment of consecutive $1$'s open the first letter in segment, scroll until the last letter in segment, if there are more unread letters left, retu...
If we add 1 to a number, its binary representation changes in a simple way: all the least

Полный текст и комментарии »

Разбор задач Codeforces Round 265 (Div. 1)
Разбор задач Codeforces Round 265 (Div. 2)
  • Проголосовать: нравится
  • +172
  • Проголосовать: не нравится

128.
Автор Alexdat2000, 4 года назад, По-русски
Editorial of Codeforces Round #862 (Div. 2) Thank you for participating! We hope you enjoyed the problems! [problem:1805A]<br> Idea and preparation: [user:Alexdat2000,2023-04-02] <div class="spoiler"> <b class="spoiler-title">Hint 1</b> <div class="spoiler-content" style="display: none;"> Recall the basic properties of the $\oplus$ operation: $A \oplus 0 = A$, $A \oplus A = 0$, $A \oplus B = B \oplus A$. </div></div> <div class="spoiler"> <b class="spoiler-title">Hint 2</b> <div class="spoiler-content" style="display: none;"> Consider the cases of even and odd array lengths. </div></div> <div class="spoiler"> <b class="spoiler-title">Editorial</b> <div class="spoiler-content" style="display: none;"> [tutorial:1805A]</div></div> <spoiler summary="Solution"> ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) xor = 0 for x in a: xor ^= x if xor == 0: print(0) else: if n % 2 == 1: print(xor) else:...
="display: none;"> If $n$ is large enough, then $F(F(\ldots F([a_1, a_2, \ldots, a_n])\ldots)) = F(F

Полный текст и комментарии »

Разбор задач Codeforces Round 862 (Div. 2)
  • Проголосовать: нравится
  • +186
  • Проголосовать: не нравится

129.
Автор physics0523, история, 3 года назад, По-английски
How to blow up too weak hashing without thinking Sadly, until today, many people use single $\rm{mod} = 10^9+7$ or so on for hashing, so why not write how to blow up them easily, with minimized thinking process? The key idea is simple. Just use [Birthday attack](https://en.wikipedia.org/wiki/Birthday_attack). 1. Write a function to calculate the hash value 2. Write a random generator of string 3. When there are $k$ possible distinct hash values, look up $O(\sqrt{k})$ random candidates 4. Now we get a pair of strings that has exactly the same hash value! In this method, the only things we should consider are that $k$ is small enough (around $k \le 10^{12}$ ), and the number of possible candidates is large enough. We don't need to care about what the hashing function is! <spoiler summary="Example Code(C++)"> ~~~~~ #include<bits/stdc++.h> using namespace std; unsigned long long xor128(){ static unsigned long long x=123456789,y=362436069,z=521288629,w=88675123; unsigned long long t; t=(x^(x<<11));x=y;y...
^{12}$ ), and the number of possible candidates is large enough. We don't need to care about what the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +159
  • Проголосовать: не нравится

130.
Автор -firefly-, история, 16 месяцев назад, По-английски
Codeforces Round 1042 (Div. 3) Editorial I hope you all enjoyed the contest! <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | H | |------------------------------------|--------|--------|--------|--------|--------|--------|--------|--------| | [user:AksLolCoding,2025-08-10] | 800 | 900 | 1000 | 1400 | 1500 | 1800 | 1800 | &mdash; | | [user:ALnQ417,2025-08-10] | 800 | 900 | 1100 | 1300 | 1500 | 1600 | &mdash; | &mdash; | | [user:bookcat,2025-08-10] | 800 | 1200 | 1200 | 1500 | 1600 | 1600 | 1600 | 2000 | | [user:chromate00,2025-08-10] | 800 | 800 | 1000 | 1400 | 1400 | 1800 | 1800 | 2200 | | [user:cry,2025-08-10] | 800 | 1000 | 1200 | 1600 | 1700 | 2100 | 2100 | 2400 | | [user:Edeeva,2025-08-10] | 800 | 800 | 1000 | 1300 | 1400 | 1600 | 1900 | &mdash; | |...
$S$ can be represented as a binary number (though very large

Полный текст и комментарии »

Разбор задач Codeforces Round 1042 (Div. 3)
  • Проголосовать: нравится
  • +110
  • Проголосовать: не нравится

131.
Автор MikeMirzayanov, 3 года назад, По-английски
Polygon: Warnings for Packages — Incomplete Tests + Statement/Validator Mismatches Hello, Codeforces! If you're developing problems in Polygon, you might like this image to attract attention. <center> <img src="/predownloaded/b4/b6/b4b6e46dd5811c89440ee98bce405e54e3b905c6.png"/> </center> <i>For the new members of the community, I would like to remind you that Polygon (https://polygon.codeforces.com/) is a system developed and maintained by Codeforces for preparing programming problems. It is there that authors and coordinators develop all the problems for the rounds. Moreover, I believe a significant (large?) portion of the problems for other competitions is also developed there: various stages of ICPC, national competitions of different levels, educational problems for various courses, etc. <b>In 2023, more than 50000 problems were prepared in Polygon (only those for which a package was compiled are counted)!</b></i> We often implement such improvements in Polygon that make the process of preparing a problem more reliable. These often include var...
rounds. Moreover, I believe a significant (large?) portion of the problems for other competitions is

Полный текст и комментарии »

  • Проголосовать: нравится
  • +733
  • Проголосовать: не нравится

132.
Автор omsincoconut, 21 месяц назад, По-английски
Codeforces Round 1008 (Div. 1, Div. 2) Editorial I hope everyone enjoyed the tasks, and thank you for participating. Thank you to the coordinators and testers for suggesting solutions and modifications to the tasks, as I alone wouldn't be able to solve my own tasks or make it to how it is right now. Also thank you to them for dealing with me since July. Please tell me in the comments if the editorial is written incorrectly or unintelligibly somewhere. I'm not the best at phrasing some things, and would appreciate amendments to the editorial. [problem:2078A] <spoiler summary="Hint"> Something doesn't change after each operation. </spoiler> <spoiler summary="Solution"> The average of the entire array doesn't change after each operation. Simply check whether the average value of $a$ is $x$ or not. Time complexity: $\mathcal{O}(n)$ per test case. Submission: [submission:310297520] </spoiler> [problem:2078B] <spoiler summary="Hint 1"> Try to put as many people in cell $n$ as possible. </spoiler> <spoile...
Choose $a_1$ as the largest number, $a_3, a_5, \ldots, a_{2n+1}$ as the next $n$ largest numbers

Полный текст и комментарии »

Разбор задач Codeforces Round 1008 (Div. 1)
Разбор задач Codeforces Round 1008 (Div. 2)
  • Проголосовать: нравится
  • +96
  • Проголосовать: не нравится

133.
Автор thecodingwizard, история, 6 лет назад, По-английски
USACO Guide: Curated Resources for Competitive Programming & USACO **11/7/2020 Update**: Now open sourced at https://github.com/cpinitiative/usaco-guide [![USACO Guide Banner](/predownloaded/cd/f4/cdf40be60dc184cc6d1cb18e13d508a2853f75eb.jpg)](https://usaco.guide/) Link: https://usaco.guide/ Recently, a group of experienced USACO contestants (led by the legendary [user:Benq,2020-07-21]) have put together a "USACO Guide" that's designed to take you from any division to Platinum and beyond. It can be accessed here: https://usaco.guide/. Though it's structured around USACO, it can still be used by non-USACO contestants! The guide provides a curated list of tutorial resources you can use to learn a particular topic, as well as a lot of practice problems for you to practice your implementation & application skills. It also comes with progress-tracking tools to help you stay motivated :) This guide is still in the **pre-release** stage: a large number of modules, particularly the more advanced ones, are still incomplete. **We are looking for ...
This guide is still in the **pre-release** stage: a large number of modules, particularly the more

Полный текст и комментарии »

  • Проголосовать: нравится
  • +562
  • Проголосовать: не нравится

134.
Автор tourist, 4 месяца назад, По-английски
Cognition @ IOI 2026 Cognition is sponsoring the IOI this year! [user:ecnerwala,2026-08-08], [user:tourist,2026-08-08], [user:skittles1412,2026-08-08], and [user:walnutwaldo20,2026-08-08] will all be there. We'll have a booth in the Fun Zone after both contest days, and we'll generally be hanging around throughout the week. Come by and say hi, we'd love to meet you! Competitive programming runs deep at Cognition. Many of our engineers competed in high school olympiads, and our founders ([user:scott_wu,2026-08-08], [user:stevenkplus,2026-08-08], and [user:walnutwaldo20,2026-08-08]) are all IOI gold medalists. One fun fact: every IOI from 2006 through 2025 had at least one Cognition employee competing in it. Today, Cognition is one of the largest AI startups in the world. We're building the future of software engineering and working with Fortune 500 companies to transform how they build software. We hope to see you in Tashkent. Until then, here's a fun warmup problem :) <spoiler summary="Problem"...
: - _Transpose_ the grid; i.e., swap its rows and columns so that the number in row $i$, column $j$ ends up in

Полный текст и комментарии »

  • Проголосовать: нравится
  • +521
  • Проголосовать: не нравится

135.
Автор AlexLuchianov, 5 лет назад, По-английски
[Tutorial] Sparse table The most common example when talking about sparse tables is the following problem: _"Given an array of $N$ integers, your task is to process $Q$ queries of the form: what is the minimum value in range $[a,b]$?"_ A brute-force approach would be to iterate over all of the elements of each query interval. This approach has $O(NQ)$ time complexity and is quite slow. One way to improve the time complexity would be to precompute the minimum value for various intervals and then use this information to speed up the queries. For what intervals should we precompute the minimum value? For a start, let's try precomputing it for all intervals of length $2$, $4$, $8$ and so on. More formally, let $rmq[h][i]$ be the minimum value on the interval $[i, i + 2^h - 1]$. One simple and efficient way to precompute this table is by observing that one interval whose length is a power of $2$ can be split into $2$ smaller intervals. This observation translates into the following recurrence relation:...
power of 2 smaller than or equal to the original number. One thing to be careful of is that, , however since we only process intervals of length power of $2$ the total number of actually

Полный текст и комментарии »

  • Проголосовать: нравится
  • +195
  • Проголосовать: не нравится

136.
Автор Xellos, 13 лет назад, По-английски
Codeforces Trainings Season 1 Episode 10: Editorial #### **Welcome to The Editorial!** <img src="http://th04.deviantart.net/fs70/PRE/f/2013/078/b/f/mi_super_saiyan_god_remasterizado_by_salvamakoto-d5ymxyi.png" height="50%" width="50%" /> **Keep the upvotes piling up! muhehe** IZ.COMPLETE. ### A. Rasheda And The Zeriba [cut] $\ $ (difficulty: medium) The first question is: When is it possible to construct a (convex) polygon from sticks of given lengths $L_i$? This question is answered by what's sometimes known as Polygon inequality theorem, which states that the sufficient and necessary condition is for every $L_i$ to be strictly less than the sum of all other $L_i$. You can imagine that it works because for the endpoints of every side, the shortest path between them (equal to the length of that side) must be smaller than any other path, including the other one along the perimeter of the polygon; constructing such a polygon, even a convex one, is pretty easy, just imagine it as having sticks linked to each other that...
or too large), so we have ${N-3 \choose 8}$ possibilities; that's around $10^7$ for $N=36$., points in 2D). Let's just sort and re-number the values of every parameter by their order, starting from, With the "small to large" merging technique, every vertex is merged into another component at most

Полный текст и комментарии »

  • Проголосовать: нравится
  • +108
  • Проголосовать: не нравится

137.
Автор kien_coi_1997, 12 лет назад, По-английски
An amazing way to calculate 10^18-th fibonacci number using 25 lines of code. Based on the approach in [my previous blog](http://codeforces.me/blog/entry/14385), today, I found an amazing way to calculate large fibonacci numbers (in some modulo). According to part IV of my previous blog, let $f(n)$ be the $(n+1)^th$ fibonacci number, we have two case: $n$ is even and $n$ is odd. - $f(2*k) = f(k)*f(k) + f(k-1) * f(k-1)$ - $f(2*k+1) = f(k)*f(k+1) + f(k-1)*f(k)$ There are only at most $O(4*\log n)$ states. I don't like to prove this, but I can ensure it is true by doing some following experiment. Let's divide n into groups by depth, you will realize a special property: Each depths only contains at most 4 values of n. call f(1000): ~~~~~ Depth[0] : 1000 Depth[1] : 499 500 Depth[2] : 248 249 250 Depth[3] : 123 124 125 Depth[4] : 60 61 62 63 Depth[5] : 29 30 31 32 Depth[6] : 13 14 15 16 Depth[7] : 5 6 7 8 Depth[8] : 1 2 3 4 Depth[9] : 0 1 2 Depth[10] : 0 1 ~~~~~ call f(123123123122): ~~~~~ Depth[0] : 123123123122 Dep...
An amazing way to calculate 10^18-th fibonacci number using 25 lines of code., an amazing way to calculate large fibonacci numbers (in some modulo). According to part IV of my

Полный текст и комментарии »

  • Проголосовать: нравится
  • +118
  • Проголосовать: не нравится

138.
Автор paulzrm, история, 4 месяца назад, По-английски
Codeforces Round 1116 (Div. 1, Div. 2) Editorial [2256A-Three Numbers on the Blackboard](https://codeforces.me/contest/2256/problem/A) Idea: [user:paulzrm,2026-08-10] <spoiler summary="Hint 1"> Sort the numbers as $a\le b\le c$. </spoiler> <spoiler summary="Hint 2"> After at least one operation, consider the median. </spoiler> <spoiler summary="Hint 3"> Doing nothing gives $c-a$; replacing $c$ with $a+b$ gives $b$. </spoiler> <spoiler summary="Tutorial"> Suppose the current numbers are $x\le y\le z$. An operation keeps two numbers and replaces the third with their sum. Since all values are nonnegative, the new sum is no smaller than either retained number. Thus the new median is the larger retained number, which is at least the old median $y$. The median never decreases. After an operation that retains $u\le v$, the numbers are $u,v,u+v$. Their range is exactly $v$, also their median. Hence every nonempty sequence of operations ends with a range of at least the initial median $b$. With no opera...
number. Thus the new median is the larger retained number, which is at least the old median $y$. The

Полный текст и комментарии »

Разбор задач Codeforces Round 1116 (Div. 1)
Разбор задач Codeforces Round 1116 (Div. 2)
  • Проголосовать: нравится
  • +166
  • Проголосовать: не нравится

139.
Автор tibinyte2006, 4 года назад, По-английски
[Tutorial] Cartesian tree and some related problems The Cartesian Tree is a useful concept for solving some problems which revolve mainly about thinking of the range of maximality of elements. It also provides a sort of "persistance" to the algorithm of monotonic stack, if you will. In this blog, we will learn what a Cartesian Tree is, how to construct one and solve some related problems to strengthen our understanding. Let's begin! <hr> #### What is a Cartesian Tree? Let's consider an array $a$ where all values are distinct. The Cartesian Tree for the array $a$ is a binary labeled tree build recursively from the function $get(l,r)$ which constructs our desired tree from the subarray $l...r$. Now let's define $get(l,r)$ - First root the tree at index $i$ such that $a_i = min(a_l,a_{l+1},...,a_r)$. Note that because all values are distinct, $i$ will always be unique. - The aforementioned index will become the root of the Cartesian Tree. It's left and right subtrees will be recursively generated by $get(l,i-1)$ and $get(...
$a_i$ is maximum. The depth of the Cartesian Tree of some index is now just the number of intervals

Полный текст и комментарии »

  • Проголосовать: нравится
  • +223
  • Проголосовать: не нравится

140.
Автор cry, 16 месяцев назад, По-английски
CSES Additional Problems I (new problems only) Tutorial Hello Codeforces. I was stuck on a 3 hour flight with nothing to do, so what better way to spend my time than catching up on the new CSES problems. But it turns out I finished those too quick so I guess I'm writing the solutions for some of them here. No one probably asked. This will only cover the new problems from the 2025 update and in the **Additional Problems I** section. For old problem solutions you can probably find them somewhere on the internet. For new problems not in this section, some of their solutions are in [this blog](https://codeforces.me/blog/entry/142894). ### [Distinct Values Sum](https://cses.fi/problemset/task/3150/) <spoiler summary="Smash Me"> Consider each distinct value separately. Say we are focused on $x$ and denote the indices where $x$ occurs in $a$ as $b_1, b_2, \ldots, b_k$. We want to count the number of subarrays that covers at least one element in $b$. Let's break $[1, n]$ into intervals separated by each $b_i$, so we have intervals $[...
number, it is swapped. Then, the bubble sort moves past the larger number. You can see that in each

Полный текст и комментарии »

  • Проголосовать: нравится
  • +82
  • Проголосовать: не нравится

141.
Автор Bahamin, история, 16 месяцев назад, По-английски
Atto Round 1 (Codeforces Round 1041, Div. 1 + Div. 2) Editorial ### ✨ **Hope you enjoyed the problems!** ✨ <span style="font-size: 20px;">[problem:2127A]</span><br> **Idea:** [user:Bahamin,2025-08-04]<br> **Preparation:** [user:Hamed_Ghaffari,2025-08-04] <spoiler summary="Hints"> <spoiler summary="Hint 1"> What happens if $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) = 0$? </spoiler> <spoiler summary="Hint 2"> Now what happens if $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) \neq 0$? </spoiler> </spoiler> <spoiler summary="Solution"> Let's see when does $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}])$ equal $\max([a_i, a_{i+1}, a_{i+2}]) - \min([a_i, a_{i+1}, a_{i+2}])$. **Case 1:** $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) = 0$ This implies that all numbers are equal and non-zero, since otherwise $\min$ would be less than $\max$ and the difference wouldn't be $0$. **Case 2:** $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) \neq 0$ In this case $\min([a_i, a_{i+1}, a_{i+2}])$ should be $0$ because $0$ is in the seque...
Because Mani wants the number of days to be as large as possible, the final answer is: $\max(\min

Полный текст и комментарии »

  • Проголосовать: нравится
  • +243
  • Проголосовать: не нравится

142.
Автор Errichto, 11 лет назад, По-английски
Good Bye 2015 Editorial [problem:611A] There are two ways to solve this problem. The first is to hard-code numbers of days in months, check the first day of the year and then iterate over days/months &mdash; [http://ideone.com/4TYPCc](http://ideone.com/4TYPCc) The second way is to check all possible cases by hand. The 2016 consists of 52 weeks and two extra days. The answer for "x of week" will be either 52 or 53. You must also count the number of months with all 31 days and care about February. [http://ideone.com/Bf9QLz](http://ideone.com/Bf9QLz) [problem:611B] Each number with exactly one zero can be obtained by taking the number without any zeros (e.g. $63_{10} = 111111_{2}$) and subtracting some power of two, e.g. $63_{10} - 16_{10} = 111111_{2} - 10000_{2} = 101111_{2}$. Subtracting a power of two changes one digit from '1' to '0' and this is what we want. But how can we iterate over numbers without any zeros? It turns out that each of them is of form $2^x-1$ for some $x$ (you can c...
number into binary system and count zeros to be sure. Watch out for overflows! Use '1LL << x

Полный текст и комментарии »

Разбор задач Good Bye 2015
  • Проголосовать: нравится
  • +184
  • Проголосовать: не нравится

143.
Автор TheScrasse, 14 месяцев назад, По-английски
Editorial of Codeforces Round 1053 (Div. 1, Div. 2) [problem:2151A] Author: [user:TheScrasse,2025-09-21]<br> Preparation: [user:TheScrasse,2025-09-21] <spoiler summary="Hint 1"> There are two types of subarrays. </spoiler> <spoiler summary="Hint 2"> If there exists $a_i \geq a_{i+1}$, how many times can the subarray appear? </spoiler> <spoiler summary="Solution"> - If there exists an $i$ such that $a_i \geq a_{i+1}$, we have $a_i = k$ for some $k$, $a_{i+1} = 1$. The subarray $[k, 1]$ appears only once on the blackboard (when James writes $1, \ldots, k$ and then $1, \ldots, k+1$). Since $a_1, a_2, \ldots, a_m$ contains $[k, 1]$, it must appear at most once as well, but the statement guarantees that it appears at least once, so the answer is $1$. - Otherwise, the array $a_1, a_2, \ldots, a_m$ can be rewritten as $l, l+1, \ldots, r$, and it appears when James writes $1, \ldots, r$, then when James writes $1, \ldots, r+1$, ..., then when James writes $1, \ldots, n$ (so $n-r+1$ times in total). Complexity: $O(n)$ </...
property of diameter, $k = \frac{D}{2} + 1$]. Then we can waste the sufficient number of steps on the path

Полный текст и комментарии »

Разбор задач Codeforces Round 1053 (Div. 1)
Разбор задач Codeforces Round 1053 (Div. 2)
  • Проголосовать: нравится
  • +155
  • Проголосовать: не нравится

144.
Автор Gellyfish, 3 года назад, По-английски
Codeforces Round 901 (Div. 1, Div. 2) Editorial ## [problem: 1875A] <spoiler summary="Tutorial"> We can use one tool each time the timer reaches to $1$, then the answer will be $\sum_{i=1}^n \min(a - 1, x_i) + b$. This can prove to be optimal. Because for each tool, if we use it when the timer is $c$, its contribution to the answer is $\min(x_i, a - c)$. We can't use the tool when the timer is less than or equal to $0$ because the bomb will explode before that, so $c=1$ is the optimal. Time complexity: $O(n)$ per test case. Memory complexity: $O(1)$ per test case. </spoiler> <spoiler summary="Code"> ```c++ #include<bits/stdc++.h> using namespace std; int n = 0, a = 0, b = 0; long long ans = 0; inline void solve(){ scanf("%d %d %d", &a, &b, &n); ans = b; for(int i = 0, x = 0 ; i < n ; i ++){ scanf("%d", &x); ans += min(a - 1, x); } printf("%lld\n", ans); } int T = 0; int main(){ scanf("%d", &T); for(int i = 0 ; i < T ; i ++) solve(); return 0; } ``` </spoiler> ## [probl...
$, The time complexity will become $O(n^4 \log n)$. This is not enough because $n$ islarge and $10^9+7

Полный текст и комментарии »

Разбор задач Codeforces Round 901 (Div. 1)
Разбор задач Codeforces Round 901 (Div. 2)
  • Проголосовать: нравится
  • +220
  • Проголосовать: не нравится

145.
Автор cry, 3 года назад, По-английски
CodeTON Round 8 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-03-10] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:oursaco,2024-03-30] | 800 | 1200 | 1500 | 1800 | 2200 | 2400 | 2800 | 2700 | 3400 | | [user:priyanshu.p,2024-03-30] | 800 | 1200 | 1300 | 1600 | 2200 | | | | | | [user:thescrasse,2024-03-30] | 800 | 1200 | 1400 | 1700 | 2100 | 2300 | 2900 | 2900 | 3500 | | [user:cry,2024-03-30] | 800 | 1000 | 1300 | 1700 | 2100 | 2200 | 2800 | 2900 | 3500 | | [user:buffering,2024-03-30] | 800 | 1000 | 1500 | 1900 | 2100 | 2200 | 2700 | 2800 | 3500 | | [user:jaggubandar,2024...
. Earlier numbers can still influence $\lfloor f(n) \rfloor$ when $n$ is large. Suppose that all $f

Полный текст и комментарии »

  • Проголосовать: нравится
  • +143
  • Проголосовать: не нравится

146.
Автор TheScrasse, 3 года назад, По-английски
Editorial of Codeforces Round 889 (Div. 1 + Div. 2) The official implementations of all the problems are [here](https://drive.google.com/file/d/1stkidhN_ftTOzK4qcMYxkUAlwWWb3AqF/view?usp=sharing). [problem:1855A] Author: [user:Kaey,2023-07-23]<br> Preparation: [user:akifpatel,2023-07-23] <spoiler summary="Hint 1"> What's the most efficient way to make the sad students happy? </spoiler> <spoiler summary="Hint 2"> In most cases, you can make $2$ sad students happy in $1$ move. </spoiler> <spoiler summary="Solution"> Let $s$ be the number of sad students at the beginning. The answer is $\lceil \frac{s}{2} \rceil$. In one move, you can make at most $2$ sad students happy (because you can change the position of at most two students), so you need at least $\lceil \frac{s}{2} \rceil$ moves. In fact, you can make everyone happy in exactly $\lceil \frac{s}{2} \rceil$ moves: - while there are at least $2$ sad students, you can swap them and both of them will be happy; - if there is exactly $1$ sad student left, you ...
possible (if we added a large number it would not affect many $f(s)$ and thus it would not be very

Полный текст и комментарии »

Разбор задач Codeforces Round 889 (Div. 1)
Разбор задач Codeforces Round 889 (Div. 2)
  • Проголосовать: нравится
  • +196
  • Проголосовать: не нравится

147.
Автор orz, история, 5 лет назад, По-русски
Fast modular multiplication Consider the following problem: given three integers $x$, $y$ и $m$, $0 \leqslant x,y < m < 2^{32}$, calculate $xy\bmod m$. The easy way is just to multiply these numbers and apply the modulo operation: ~~~~~ uint32_t prod(const uint32_t x, const uint32_t y, const uint32_t m) { return x * y % m; } ~~~~~ As you might have guessed, this solution is wrong. The thing is that an overflow is possible in such a procedure: the operation `x * y` is performed in the type` uint32_t`, and in fact the intermediate result of this operation will not be $xy$, but $xy\bmod2^{32}$. If after that we take the result modulo $m$, it may differ from the correct one: $$ \left(xy\bmod2^{32}\right)\bmod m\ne xy\bmod m. $$ The way out is simple — you need to multiply in a larger type: ~~~~~ uint64_t prod_uint64(const uint64_t x, const uint64_t y, const uint64_t m) { return x * y % m; } ~~~~~ If you do this, then, since $xy<2^{64}$, this product will definitely not overflow, and after tak...
behind other compilers in the availability of technical means for multiplying large numbers modulo, find a large number $N$, by which you can quickly multiply, then you can multiply any two numbers

Полный текст и комментарии »

  • Проголосовать: нравится
  • +269
  • Проголосовать: не нравится

148.
Автор Endagorion, история, 11 лет назад, По-английски
Codeforces Round #339 Editorial I'm terribly sorry for the delay. Please report any mistakes. [problem:614A] Author: [user:Tigutor,2016-01-16] Developers: [user:Tigutor,2016-01-16], [user:ch_egor,2016-01-16] You had to print all numbers of form $k^x$ for non-negative integers $x$ that lie with the range $[l; r]$. A simple cycle works: start with $1 = k^0$, go over all powers that do not exceed $r$ and print those which are at least $l$. One should be careful with 64-bit integer overflows: consider the test $l = 1$, $r = 10^{18}$, $k = 10^9$, the powers will be 1, $10^9$, $10^{18}$, and the next power is $10^{27}$, which does not fit in a standard integer type. [problem:614B] Author, developer: [user:ch_egor,2016-01-16] You were asked to print the product of $n$ large numbers, but it was guaranteed that at least $n-1$ are beautiful. It's not hard to see that beautiful numbers are 0 and all powers of 10 (that is, 1 followed by arbitrary number of zeros). If there is at least one zero among the g...
You were asked to print the product of $n$ large numbers, but it was guaranteed that at least $n-1

Полный текст и комментарии »

Разбор задач Codeforces Round 339 (Div. 1)
Разбор задач Codeforces Round 339 (Div. 2)
  • Проголосовать: нравится
  • +74
  • Проголосовать: не нравится

149.
Автор -is-this-fft-, история, 3 года назад, По-английски
[Tutorial] Hungarian algorithm in Õ(mn) or O(n^3) I once read a paper that claimed and used the fact that the Hungarian algorithm can be implemented in such a way that it runs in $O(m n \log n)$ time. Using the soft-O notation which ignores log factors, the complexity can be written as $\tilde{O} (m n)$. If the graph is dense, i.e. $m = \Theta(n^2)$, the log factor can be removed There are many tutorials on how to get $O(n^3)$, but I couldn't find any references that directly show how to do $\tilde{O}(mn)$ from end to end (but I found just enough to conclude that it is probably possible). So I decided to write one up myself and well, this is as good a place as any. In my [last blog](https://codeforces.me/blog/entry/128552), I showed how thinking in terms of linear programming and duality can be useful when working with maximum flows and minimum cuts. The usefulness of this is best demonstrated with examples, and this is a good example. In fact, this is pretty much **the** primal-dual algorithm: it was one of the prototypes th...
number of reachable vertices from $r$ (using the rules above) becomes bigger, since we are now

Полный текст и комментарии »

  • Проголосовать: нравится
  • +87
  • Проголосовать: не нравится

150.
Автор Arpa, история, 3 года назад, По-английски
Ten Years of Competitive Programming 4 Hey, Codeforces! I’m AmirReza PourAkhavan, the former Codeforces Contest Coordinator. I let the story become complete and I’m sharing it now. The story is about a 16-year competitive programmer, who left his family and migrated to another city alone to follow competitive programming. After seven years, he advanced to the International Collegiate Programming Contest World Finals, twice. Read the previous parts: [1](https://codeforces.me/blog/entry/107465), [2](https://codeforces.me/blog/entry/108838), [3](https://codeforces.me/blog/entry/114356). **Read the Persian version** [**here**](https://docs.google.com/document/d/e/2PACX-1vSUoFC9tLgDCji6rSCYy-RYoUG1_6uOQnHz_LlLKe6KksWBYWO4r6clDly5YxIgzu1g3Tj31weDxgWz/pub). What happened previously === I was a lone programmer, in a small city, trying to learn CP and prepare for the Iran National Olympiad. It was not as successful as I expected. I tried to change my school and I immigrated to Tehran, alone. I entered AE high s...
During the preparation, a large number of problems were discarded, and others were selected as

Полный текст и комментарии »

  • Проголосовать: нравится
  • +99
  • Проголосовать: не нравится

151.
Автор Geothermal, история, 7 лет назад, По-английски
Codeforces Round #644 (Div. 3) — Unofficial Solutions Hi all! I'm here to share my solutions to today's Div. 3 round, since I managed to finish the round relatively quickly and thought that my approaches might be of some use to others. Feel free to leave questions in the comments! --- #A &mdash; Minimal Square Without loss of generality, let's say $A \leq B$, that is, $B$ is the larger side-length. We claim that the minimum side length is $\max(2A, B)$, hence, the answer is $\max(2A, B)^2$. This is relatively easy to observe just by looking at the sample cases and trying different configurations, but I'll prove this claim below in case you're curious. To prove this, we first show that $\min(2A, B)$ is a valid side-length. To achieve this, just stack the two rectangles on top of each other, with the two short sides stacking vertically and the long sides overlapping. (This looks much like the solution given in the problem statement for the second test case.) The vertical side-length of the block formed will be $2A$, and...
a certain number of packages, the number of shovels per package must be a factor of $N$. We can

Полный текст и комментарии »

  • Проголосовать: нравится
  • +109
  • Проголосовать: не нравится

152.
Автор Maksim1744, 5 лет назад, По-английски
Unofficial editorial for Codeforces Round #171 (Div. 2) [Continuing](https://codeforces.me/blog/entry/83942) with the theme of absent editorials for old rounds, here is an editorial for [contest:279]. Even though there is an official editorial, it is only in russian and doesn't have solution for the last problem. A <spoiler summary="Editorial"> ### [problem:279A] Since constraints are small, you can just simulate the whole process, but I'll explain an $O(1)$ solution. Let's look at the path <img src="/predownloaded/29/e8/29e8a60536c8c2797c2e180f9fc640ee2eebc428.png" width="400px"/> Now it's easy to see that the plane can be divided into four parts <img src="/predownloaded/7a/21/7a21eb1014e8b41ee5a7d0bdf5563015c2123a56.png" width="400px"/> And then we can calculate answer for each part separately, just be careful with borders. For example, for the right part the answer is $4x - 3$. </spoiler> <spoiler summary="Code"> ~~~~~ #include "bits/stdc++.h" using namespace std; int main() { int x, y; ci...
Let's look at the highest bit in the current number, suppose it's $2^k$. Since the sum of all

Полный текст и комментарии »

Разбор задач Codeforces Round 171 (Div. 2)
  • Проголосовать: нравится
  • +111
  • Проголосовать: не нравится

153.
Автор Mindeveloped, история, 9 месяцев назад, По-английски
Codeforces Round 1086 (Div. 2) Editorial We hope that you have enjoyed our problems! [problem: 2208A] Idea by [user:Mindeveloped,2026-03-15], prepared by [user:Mindeveloped,2026-03-15] <spoiler summary="Hint 1"> It is always possible to rearrange the candies, unless candies of one specific color appears too often. </spoiler> <spoiler summary="Solution"> Let $x$ be the color with the highest number of candies. In case of ties, $x$ could be any of the candidates. Denote the number of candies with color $x$ as $a$. Conclusion: The answer to the problem is `YES` if and only if there are no more than $n^2 - n$ candies of color $x$; &mdash; in other words, $a\le n^2 - n$ holds. Proof of necessity: If there are more than $n^2 - n$ candies of color $x$, then there are less than $n$ candies not of color $x$. Since there are $n$ rows, at least one row will have no candies not of color $x$; therefore, such a row will be filled with candies of color $x$, violating the restrictions. Proof of sufficiency: If there a...
Let $ s_u $ denote the number of nodes reachable from $ u $. Among all nodes in $ R_u $, let $ v

Полный текст и комментарии »

Разбор задач Codeforces Round 1086 (Div. 2)
  • Проголосовать: нравится
  • +100
  • Проголосовать: не нравится

154.
Автор aryanc403, 6 месяцев назад, По-английски
Very detailed (text+video) editorial for Codeforces Round 1103 The full editorial video for [contest:2236] is [now available here](https://youtu.be/Y91ChDX4apQ) &mdash; over 3 hours of problem discussions and solutions. Enjoy! I'll update this blog later with submission links and video timestamps. For now, I'm exhausted after finishing this video editorial. Problems are discussed in the following order: A → B → C → D → E → F1 → F2 → G. --- [problem:2236A] <spoiler summary="Hint 1"> What is the smallest possible final height that all towers can reach? </spoiler> <spoiler summary="Hint 2"> Remember that every tower must receive a strictly positive increment. </spoiler> <spoiler summary="Hint 3"> If the tallest tower has height mx, can the final height be mx? </spoiler> <spoiler summary="Hint 4"> Try making every tower equal to mx+1. </spoiler> <spoiler summary="Hint 5"> For a tower of height h[i], how much do we need to add? </spoiler> <spoiler summary="Hint 6"> The answer is determined by the tower requiri...
- divide the larger number once more

Полный текст и комментарии »

  • Проголосовать: нравится
  • +35
  • Проголосовать: не нравится

155.
Автор djm03178, 2 года назад, По-английски
Div. 2 C's are NOT getting easier Recently, after like every Div. 2 contest I see some blogs/comments saying that ~2C problems are getting easier. What's the evidence? They say these problems have _many_ solves. No, I think it's the opposite. Definite number of solves is not a good measure for evaluating the difficulty. A not too precise, but statistically more reliable way to evaluate the difficulty of a 2C problem would be calculating `(# of official solves on C) / (# of official solves on A)`, assuming that most people have always been able to solve 2A. Let's calculate them for recent 10 Div. 2-only contests' (not counting Educational rounds) C problems: - [contest:1993] : 6755/19951 (33.86%) - [contest:1995] : 2384/13980 (17.05%) - [contest:1990] : 3490/11867 (29.41%) - [contest:1988] : 7239/12234 (59.17%) - [contest:1983] : 5504/16414 (33.53%) - [contest:1982] : 7654/14965 (51.15%) - [contest:1978] : 5115/12031 (42.52%) - [contest:1979] : 9051/17663 (51.24%) - [contest:1981] : 1128/10942 (10.31...
getting too large absolute number of solves. Having 40 solves on 2F nowadays isn't same as having

Полный текст и комментарии »

  • Проголосовать: нравится
  • +226
  • Проголосовать: не нравится

156.
Автор Olympia, история, 5 лет назад, По-английски
[Tutorial] Tree Isomorphism CSES ### Introduction I have no school right now, and there's no tutorials on Tree Isomorphism on Codeforces, so I decided to write one :). _What is a tree isomorphism?_ Maybe you recognize the word isomorphic: in the context of abstract algebra when two objects are effectively the same, but are labelled differently. We can extend this to trees as well: two trees are isomorphic if they are the same, but may have different node labels. For example, ![ ](https://i.ibb.co/0ZTB5xt/Screen-Shot-2022-03-18-at-9-29-35-AM.png) are isomorphic because we can relabel the nodes. If you want a more rigorous definition, then two trees $T_1 = (V_1, E_1)$ and $T_2 = (V_2, E_2)$ are isomorphic iff there exists a $\phi$ for which $\phi(E_1) = E_2$ and a $\phi^{-1}$ for which $\phi^{-1} (E_2) = E_1$. _What is the problem?_ We want to determine if two unrooted trees are isomorphic in $\mathcal{O}(N \log N)$ time. _If we can solve the problem for rooted trees, can we solve it for unrooted...
it's binary representation. In the case that the number is too large, we can take it modulo some

Полный текст и комментарии »

  • Проголосовать: нравится
  • +125
  • Проголосовать: не нравится

157.
Автор Sanae, история, 15 месяцев назад, По-английски
Set algorithm(rev.2) # Set algorithm Part I Sometimes we may meet with some functions $S\rightarrow V$(S is a set,V is a value),and we need to handle some transformations on it. The article is for beginners whick is much easy, and I may continously update the article. There are some features. First the problem always give small $n$,such as $n\leq 15,n\leq20$. Second,the time complexity is always $O(n2^n),O(3^n),O(n^22^n)$. Let's do some assumption: The values form a ring and they contain ring operations like addition,substraction,multification or division in constant time. ## FWT/FMT The most classical one is FWT/FMT. ### Problem Define $a(S),b(S)(S\subseteq U)$ on a set. Get all $c(S)=\sum\limits_{i \oplus j=S}a_ib_j\qquad \oplus \text{is} \ \textrm{and,or,xor}$ The general idea: Let $a, b, c$ be maps (functions) from a set $S$ to a value domain $V=(N/Q/C\cdots)$. We define a transformation $\text{FWT}$ (Fast Walsh Transform) as a map from the space of such functi...
Consider PIE, calculate the number of DAG of scc which size is larger than $2$.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +105
  • Проголосовать: не нравится

158.
Автор dragonslayerintraining, 7 лет назад, По-английски
Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2) Editorial [1209A &mdash; Paint the Numbers](https://codeforces.me/contest/1209/problem/A) ================== Author: [user:MikeMirzayanov,2019-09-14] Consider the smallest element $x$ in the array. We need to paint it in some color, right? Observe, that we can paint all elements divisible by $x$ in that color as well. So we can perform the following while the array is not empty: * find the minimum element $x$, * assign new color and remove all elements divisible by $x$ Complexity: $\mathcal{O}(n^2)$. [1209B &mdash; Koala and Lights](https://codeforces.me/contest/1209/problem/B) ================== Author: [user:FieryPhoenix,2019-11-28] Because each individual light flashes periodically, all the lights together are periodic as well. Therefore, we can simulate the lights up to the period to get the answer. The actual period can be calculated as follows: <spoiler summary="Spoiler"> * If a light toggles every $t$ seconds, its period is $2t$. * The overall per...
(minimum, number of minimums) on the segment. In a similar way we can build a structure which returns, However, computing the actual period is not necessary and a very large number will work (like $1000$).

Полный текст и комментарии »

  • Проголосовать: нравится
  • +124
  • Проголосовать: не нравится

159.
Автор MikeMirzayanov, 13 лет назад, По-русски
Codeforces: Results of 2013 Hello! Do you feel the breath of New Year? <img src="http://assets.codeforces.com/images/tree.png" style="float:right;margin: 0 1em 1em 1em;"/> The clock shows a day before New Year, so it is time to sum up the past. I do not have speech-writers for words in the style of "what recently seemed almost impossible, it becomes a fact of life" so I'll be short. Thank you all! Your unfading interest and constant help inspire Codeforces team for new achievements! Brilliant writers, invisible soldiers: testers, tireless and greedy for knowledge participants &mdash; all of you help Codeforces do better! I've dug into the records and made a partial list of the most notable major improvements of 2013. Some large improvements of our infrastructure are not in the list, as the community can not see them directly. * A simple way to add contest from [Polygon](https://polygon.codeforces.com/) to Codeforces::Gym. * Drafts embedded in text form fields in Codeforces and Polygon. * Multipl...
the most valuable — a large number of Andrew Stankevich Сontests. * Implemented [checker and

Полный текст и комментарии »

  • Проголосовать: нравится
  • +601
  • Проголосовать: не нравится

160.
Автор Zlobober, история, 11 лет назад, По-русски
Editorial for VK Cup 2015 — Finals Thanks everybody for participating. Tasks follow in the order of the original contest (the mirror order is given in the brackets). [problem:562A] -------------- (in mirror: [problem:566C]) Let's think about formal statement of the problem. We are given a tricky definition of a distance on the tre: $\rho(a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_i$. We need to choose a place $x$ for a competition such that the sum of distances from all vertices of the tree with their weights is minimum possible: $f(x) = w_1 \rho(1, x) + w_2 \rho(x, 2) + \ldots + w_n \rho(x, n)$. Let's understand how function $f(x)$ works. Allow yourself to put point $x$ not only in vertices of the tree, but also in any point inside each edge by naturally expanding the distance definition (for example, the middle of the edge of length $4$ km is located $2$ km from both ends of this edge). **Fact 1**. For any path $x \in [a, b]$ in the tree the function $\rho(i, x)$ is convex. Actually, the ...
, by running one gradient calculation we reduced the number of vertices in a considered part of a tree, We got a solution in $O(n)$ operation (though, the constant hidden by $O$-notation is prettylarge

Полный текст и комментарии »

Разбор задач VK Cup 2015 - Finals
  • Проголосовать: нравится
  • +100
  • Проголосовать: не нравится

161.
Автор Zlobober, 12 лет назад, По-русски
VK Cup Round 1 (+ online mirror) editorial Problemsets slightly differ in main round and in an online mirror, in editorial problems follow in an order of the main round. [problem:524A] ============== This problem didn't appear in an online mirror. Its editorial will be left as an exercise in Russian language for those who are curious what it is about =) [problem:524B] ============== In an original version there was no constraint that no more than n / 2 friends should lie. This version can be solved pretty easy. Iterate over all possible values of $H$. For a fixed $H$ we have to minimize total width of all rectangles on the photo. So, for each rectangle we need to choose in which orientation it fits into photo having the minimum possible width. [problem:529B] ============== In an online mirror version the problem was slightly harder. Let's call people with $w \leq h$ \textit{high}, and remaining people \textit{wide}. Let's fix photo height $H$. Let's consider several following cases: * If a high person fi...
-wise larger then other ones, so it is better than other states (since the largestnumber in some

Полный текст и комментарии »

Разбор задач VK Cup 2015 - Раунд 1
  • Проголосовать: нравится
  • +90
  • Проголосовать: не нравится

162.
Автор FieryPhoenix, 7 лет назад, По-английски
Codeforces Round #621 (Div. 1 + Div. 2) Editorial [problem:1307A] Idea: [user:FieryPhoenix,2020-02-16] <spoiler summary="Tutorial"> [tutorial:1307A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <iostream> using namespace std; int N,D,a[105]; int main(){ int T; cin>>T; while (T--){ cin>>N>>D; for (int i=1;i<=N;i++) cin>>a[i]; while (D--){ //loop over D days for (int i=2;i<=N;i++) if (a[i]>0){ //move closest haybale over a[i]--; a[i-1]++; break; } } cout<<a[1]<<endl; } } ~~~~~ </spoiler> <spoiler summary="Alternative O(n) Solution:"> ~~~~~ #include <iostream> using namespace std; int N,D,a[105],ans; int main(){ int T; cin>>T; while (T--){ cin>>N>>D; for (int i=1;i<=N;i++) cin>>a[i]; for (int i=2;i<=N;i++){ int move=min(a[i],D/(i-1)); //number of haybales we can move from pile i to pile 1 a[1]+=move; //update pile 1 D-=move*(i-1); //update remaining days } cout<<...
; //largest favorite number for (int i=0;i>A; a.insert(A

Полный текст и комментарии »

Разбор задач Codeforces Round 621 (Div. 1 + Div. 2)
  • Проголосовать: нравится
  • +159
  • Проголосовать: не нравится

163.
Автор omsincoconut, 11 месяцев назад, По-английски
Codeforces Round 1071 (Div. 3) Editorial [problem:2179A] =============== Author: [user:IceBorworntat,2025-12-22] <spoiler summary="Hint 1"> Think about the indices that have the same remainder after division by $x$. </spoiler> <spoiler summary="Solution"> Consider the subsequence formed from the indices that have the same remainder after division by $x$. There are $x$ such subsequences. Each subsequence contains distinct characters, so the maximum length of such subsequences is $k$. As such, the minimum string length that cannot be constructed is $n = kx+1$. Time complexity: $\mathcal{O}(1)$ </spoiler> <spoiler summary="Implementation (Python)"> ~~~~~ t = int(input()) for _ in range(t): k, x = [int(i) for i in input().split()] print(k*x+1) ~~~~~ </spoiler> [problem:2179B] =============== Author: [user:spycoderyt,2025-12-22] <spoiler summary="Hint 1"> First observe that it is always helpful to remove a floor. Now the question becomes which floor to remove. </spoi...
For a larger value of $k$, we cannot modify the value of $a_1$, so every number must be made into

Полный текст и комментарии »

Разбор задач Codeforces Round 1071 (Div. 3)
  • Проголосовать: нравится
  • +164
  • Проголосовать: не нравится

164.
Автор TheScrasse, история, 5 лет назад, По-английски
[Tutorial] Number theory — Storing information about multiples/divisors Hello everyone,<br> here is a very simple idea that can be useful for (cp) number theory problems, especially those concerning multiples, divisors, $\text{GCD}$ and $\text{LCM}$. Prerequisites: basic knowledge of number theory (divisibility, $\text{GCD}$ and $\text{LCM}$ properties, prime sieve). Idea ------------------ Let's start from a simple problem. _You are given $n$ pairs of positive integers $(a_i, b_i)$. Let $m$ be the maximum $a_i$. For each $k$, let $f(k)$ be the sum of the $b_i$ such that $k | a_i$. Output all pairs $(k, f(k))$ such that $f(k) > 0$._ An obvious preprocessing is to calculate, for each $k$, the sum of the $b_i$ such that $a_i = k$ (let's denote it as $g(k)$). Then, there are at least $3$ solutions to the problem. #### Solution 1: $O(m\log m)$ For each $k$, $f(k) = \sum_{i=1}^{\lfloor m/k \rfloor} g(ik)$. The complexity is $O\left(m\left(\frac{1}{1} + \frac{1}{2} + \dots + \frac{1}{m}\right)\right) = O(m\log m)$. #### Solution 2: $O(n\sq...
[Tutorial] Number theory — Storing information about multiples/divisors, > If $m$ is large, you may need to use a map to store the values of $f(k)$ but, as there are $O(n, Hello everyone, here is a very simple idea that can be useful for (cp) number theory problems

Полный текст и комментарии »

  • Проголосовать: нравится
  • +105
  • Проголосовать: не нравится

165.
Автор Everule, история, 4 года назад, По-английски
Editorial for Round 850 #### [A. Monsters (easy version)](https://codeforces.me/contest/1785/problem/A) Notice that this is equivalent to maximizing the damage done by the operation of type $2$. Let us consider the case when there are 2 monsters with health $h$, and $h+k$, and no monsters with health in $(h, h+k)$. Then reducing the monster with health $h + k$ to $h + 1$ cannot make the final outcome worse. You can prove it by noticing that the operation of type $2$ can only happen $h$ times if the health of the monster is above $h + 1$. Now we get monsters with health in such a way, that there exists $H$, where there is monster with health from $1$ to $H$. Then one move of operation $2$ can kill the remaining monsters. So you only need to simulate the above process, and find out how many moves of type $1$ were required to do it. #### [B. Letter Exchange](https://codeforces.me/contest/1785/problem/B) Let us consider a graph with $3$ nodes $w, i, n$. For a word of type $wii$ add an edge from $i$ to...
Let's go for the next claim. Let $b$ be the number of elements in $[1, n]$ deleted with median, Now its quite natural to fix $t$, the number of minimum operations we did. Then all median

Полный текст и комментарии »

  • Проголосовать: нравится
  • +121
  • Проголосовать: не нравится

166.
Автор Ecrade_, 20 месяцев назад, По-английски
Codeforces Round 1010 (Div. 1, Div. 2, based on Zhili Cup 2025) Editorial Sorry for the late editorial. Our problem setters were so exhausted with the offline competition yesterday that they really need some good rest. Despite the unexpected and unpleasant incidents that occurred, we are truly surprised and grateful that so many of you still participated in this competition! We sincerely hope you enjoyed it! (Gratitude for all you guys from [user:Ecrade_,2025-03-16]: I felt so heartbroken when I heard about the unexpected issues, but seeing so many people in the comments comforting us, sharing thoughtful and positive messages that showed genuine empathy, and continuing to fully support our competition even after the wasted time, I was deeply moved. Thank you all! Codeforces truly embodies such a positive and uplifting community spirit!) [problem:2082A] <br> Idea: [user:Ecrade_,2025-03-16] <spoiler summary="Hint"> Do we really have to consider the problem on the whole matrix? </spoiler> <spoiler summary="Solution"> Let $r$ be the num...
large, until $f_k$ and calculate the contributions of these $d$.

Полный текст и комментарии »

Разбор задач Codeforces Round 1010 (Div. 1, Unrated)
Разбор задач Codeforces Round 1010 (Div. 2, Unrated)
  • Проголосовать: нравится
  • +167
  • Проголосовать: не нравится

167.
Автор jiry_2, история, 9 лет назад, По-английски
A simple introduction to "Segment tree beats" Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this comment](http://codeforces.me/blog/entry/54750?#comment-387957). Sorry for the long delay, as a sophomore in Peking University, I've just finished a tired semester and a painful final exam. And now I finally have enough time to do a simple introduction to this interesting algorithm. It may be a huge project for me since my English is not good. I think I will finish this blog in several steps and I will try to finish it as soon as possible :) In China, all of the 15 candidates for the Chinese National Team are asked to write a simple research report about algorithms in informatics Olympiad, and the score will be counted in the final selection. There are many interesting ideas and algorithms in these reports. And I find that some of them are quite new for competitors in CF although they are well known in China from the final standings of some recent contests. For example, In the last co...
)$ 3. For all $i \in [l,r]$, change $A_i$ to $A_i + x$, $x$ can be a negative number 4. Query for

Полный текст и комментарии »

  • Проголосовать: нравится
  • +771
  • Проголосовать: не нравится

168.
Автор arvindf232, история, 12 месяцев назад, По-английски
Quadratic binary energy function minimisations by Flow ## Motivations I tried to read [https://codeforces.me/blog/entry/148438](https://codeforces.me/blog/entry/148438) and failed. It contains a lot of extra explanations and intuition that I either already knew or could reconstruct immediately. That is not inherently bad, but for me personally it made the key ideas harder to see. (I think most contestants would not struggle with visualising binary logical relations...) As I asked around (and with help from LLMs), it became clear that the underlying structure is the Kolmogorov–Zabih characterization of which quadratic binary energies are solvable via a single max-flow. This blog is essentially a reweighting of that material: shorter, more “algebraic”, and aimed at people who are already comfortable with max-flow / min-cut and with abstracting away implementation details. This blog is also just essentially an extremely long comment that is too long to fit in comment section. ## Declarations While writing this, I did **not**...
/michaelmas2002/23520065.pdf). * Solve a large number of max-flow problems to add my own problem

Полный текст и комментарии »

  • Проголосовать: нравится
  • +95
  • Проголосовать: не нравится

169.
Автор shadow9236, история, 5 лет назад, По-английски
[Tutorial] Subtree sets using small-to-large merging <h1>Introduction</h1> Hello Codeforces,<br> I came across this problem a while back — https://cses.fi/problemset/task/1139/. Here the task is — "Given a colored, rooted tree, determine the number of distinct colors in each subtree of the tree". It is possible to solve this problem by flattening the tree and then using a binary indexed tree(now that subtrees have converted into subarrays). I will discuss an alternate technique to solve this, which can help in cases where it is useful to have the entire subtree as a set in a DFS call. <h1>$O(n^2)$ solution</h1> If $n$ were small, we could have stored for each node, the set of elements in its subtree. A DFS can be used to evaluate this, which will take $O(n^2log n)$ time and $O(n^2)$ space. ```cpp vector<int> color(n); vector<set<int>> subtree(n); void dfs(int i,int parent){ subtree[i].insert(color[i]); for(int node : graph[i]){ if(node != parent){ dfs(node,i); subtree[i].insert(subtree[node].begin(),subtree...
[Tutorial] Subtree sets using small-to-large merging, ()); } } } ``` The number of distinct colors in the subtree of the $i^{\text{th}}$ node is just the, ://cses.fi/problemset/task/1139/. Here the task is — "Given a colored, rooted tree, determine thenumber

Полный текст и комментарии »

  • Проголосовать: нравится
  • +78
  • Проголосовать: не нравится

170.
Автор ATSTNG, история, 7 лет назад, перевод, По-русски
[Tutorial] Matroid intersection in simple words **[This article is also available in [Russian](https://codeforces.me/blog/entry/69287?locale=ru)]** Hello, CodeForces. I think that matroids are beautiful and powerful concept, however, not really well known in competitive programming. I’ve discovered matroids at 2019 Petrozavodsk Winter Training Camp. There was a problem that clearly cannot be solved using usual techniques I knew, editorial for this problem was just these three words “just matroid intersection”. Back then it took me more than 2 days of upsolving to find all the information and details I need and implement solution that gets Accepted on this. And it took way longer to actually understand why does it work and exactly how does it work. (I still hesitate in some details.) Of course, it is not hard to google up all the definitions and some related articles, but in my opinion they all are focused more on mathematical part of theory, strict proofs in some not really obvious but short ways, and observing only ke...
independence. And we can measure running time of some algorithms as the number of _oracle calls_. (However, in

Полный текст и комментарии »

  • Проголосовать: нравится
  • +904
  • Проголосовать: не нравится

171.
Автор jerrywang0916, история, 8 месяцев назад, По-английски
List of Suspected Cheaters in Nebius Round 2 This message was originally intended to be posted via the account [user:send_cheater_to_basement,2026-03-31]. However, since that account is not a trusted account, it cannot publish blogs. Therefore, I am using this account instead, **which belongs to one of my classmates**. I would like to thank him for lending it to me. I manually collected all suspicious users, which were then organized by AI. There may be errors. Here is a list of users who are heavily suspected of cheating during the Nebius Round 2. I only managed to check the top 250 participants whose original rating was no higher than Specialist. Unfortunately, I had to stop after checking these because my IP was flagged as a web crawler/bot. **⚠️ DISCLAIMER: Appearing on this list does not definitively prove that a user has cheated.** It simply indicates highly suspicious behavior during the contest. ### Detection Methodology During the contest, anti-AI traps were placed in the problem statements: - ...
- [user:ALPHAwule,2026-03-31] - Evidence: A large number of compilation errors, with only a 1

Полный текст и комментарии »

  • Проголосовать: нравится
  • +264
  • Проголосовать: не нравится

172.
Автор neal, 8 лет назад, По-английски
Quick unofficial editorial for Educational Round 59 (Div. 2) Continuing with the theme from last time, here's a quick writeup of my approaches: #### [problem:1107A] Since we just want to make two numbers such that the first number is smaller than the second, our best bet is to use only the first digit for the first number and the rest of the digits for the second number. Note that since the numbers can have up to 300 digits we shouldn't actually evaluate the second number. Instead, since the digits only include 1 through 9, we can handle that case by checking the number of digits. Code: [submission:49002957] #### [problem:1107B] The key observation is that the digital root of an integer $k$ is the single-digit number $1 \leq d \leq 9$ such that $k \equiv d \bmod 9$. You can prove this by noticing that $10^p \equiv 1 \bmod 9$ for all $p$. Once we observe this, finding the $k$-th number is very simple; see the code: [submission:48993705] #### [problem:1107C] Since we are only allowed to push the same button $k$ times in a row, let's do...
:1107A] Since we just want to make two numbers such that the first number is smaller than the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +262
  • Проголосовать: не нравится

173.
Автор NetSpeed1, 23 месяца назад, По-английски
Codeforces Global Round 28 Editorial [problem:2048A] Author: [user:Little09,2024-12-19] <spoiler summary="Hint 1"> How much does the number decrease when we remove two consecutive $3$ s? </spoiler> <spoiler summary="Tutorial"> ### [problem:2048A] When we transform $\overline{x33y}$ into $\overline{xy}$ (where $x$ and $y$ are decimal numbers), the actual value changes from $10^{p+2} \cdot x + 33 \cdot 10^p + y$ to $10^p \cdot x + y$. The decrease is $99 \cdot 10^p \cdot x + 33 \cdot 10^p$. It is easy to see that $33 \mid (99 \cdot 10^p \cdot x + 33 \cdot 10^p)$. Therefore, we can replace the operation of removing two consecutive $3$ s with a series of $-33$ operations. Hence, we only need to determine whether $x$ can be reduced to $0$ using a series of $-33$ operations, which is equivalent to checking whether $x \bmod 33$ equals zero. </spoiler> [problem:2048B] Author: [user:wsyear,2024-12-19] <spoiler summary="Hint 1"> If the permutation is sufficiently long, what is the maximum number of leng...
**Lemma:** Suppose the largest value filled is $mx$, and the number of distinct values is $c$. Let

Полный текст и комментарии »

Разбор задач Codeforces Global Round 28
  • Проголосовать: нравится
  • +128
  • Проголосовать: не нравится

174.
Автор Geothermal, история, 7 лет назад, По-английски
Codeforces Round 629 -- Unofficial Solutions Hi all! As it might be a little while before the editorial for today's round is released (due to the open hacking phase), I thought I'd publish my solutions in case anyone wants to review the problems right away. --- #A &mdash; Divisibility Problem There are a few ways to approach this. One is to find the next multiple of $B$ after $A$ and subtract $A$. Recall that we can compute $\frac{A}{B}$, rounded up, as $\frac{A+B-1}{B}$, rounded down. We can compute this value and then multiply it by $B$ to get the next multiple of $B$, subtracting $A$ to get our answer. An alternative solution (and the one I implemented) is to realize that, as long as $A$ isn't already a multiple of $B$, the number of moves required is $B - (A \% B)$, since the distance to the next lower multiple of $B$ plus the distance to the next higher multiple of $B$ will be $B$. We can use this to compute the answer. In the case where $A$ is a multiple of $B$, this prints $B$ instead of $0$, so we can ...
point. As soon as we make the two numbers different, though, whichever number is bigger at this stage, $ to each number. When we process a $2$, we should add a $1$ to each number: this is better than

Полный текст и комментарии »

  • Проголосовать: нравится
  • +97
  • Проголосовать: не нравится

175.
Автор hyforces, история, 3 года назад, По-английски
Teamscode Summer 2023 Editorial This is the editorial for the recent Teamscode Summer 2023 contest, and the problems are open for upsolving on this [gym](https://codeforces.me/gym/104520). Problems were prepared by [user:oursaco,2023-08-22], [user:dutin,2023-08-22], [user:thehunterjames,2023-08-22], [user:Bossologist,2023-08-22], [user:Esomer,2023-08-22], [user:danx,2023-08-22], [user:codicon,2023-08-22], [user:willy108,2023-08-22], and [user:hyforces,2023-08-22]. The problems were tested by [user:omeganot,2023-08-22], [user:codicon,2023-08-22], [user:cry,2023-08-22], [user:skye_,2023-08-22], [user:Litusiano_,2023-08-22], and [user:apple_method,2023-08-22]. ### [A. Who is cooking?](https://codeforces.me/gym/104520/problem/A) <spoiler summary="Solution"> danx </spoiler> <spoiler summary="Code"> ~~~~~ print("Esomer") ~~~~~ </spoiler> ### [B. Restaurant Sorting](https://codeforces.me/gym/104520/problem/B) <spoiler summary="Solution"> The answer is $n - $ the longest prefix of the array where a...
character in the string, repeated the number of times it appears in the string.

Полный текст и комментарии »

Разбор задач Teamscode Summer 2023 Contest
  • Проголосовать: нравится
  • +84
  • Проголосовать: не нравится

176.
Автор Little_Sheep_Yawn, 14 месяцев назад, По-английски
Codeforces Round 1057 (Div. 2) Editorial ### [problem:2153a] <spoiler summary="Hint 1"> You can't eat two apples of the same beauty value. </spoiler> <spoiler summary="Hint 2"> Is there a way to eat apples of all kinds of beauty values that appearred? </spoiler> <spoiler summary="Solution"> First of all, since the beauty values of the apples you eat are in strictly increasing order, any two of them have different beauty values. So, for each beauty value, you can eat at most one apple. In fact, it can be shown that it is always possible to eat exactly one apple of each beauty value. Let's say all the distinct beauty values are $v_1,v_2,\ldots,v_k\ (v_1\lt v_2\lt\ldots\lt v_k)$. You can eat one apple of beauty value $v_i$ during the $i$-th time you move along the full circle. Therefore, the answer is the number of distinct numbers in beauty values. The time complexity is $\mathcal{O}(n)$. </spoiler> <spoiler summary="Code (C++, maomao90)"> ~~~~~ #include <bits/stdc++.h> using namespace std; i...
Let $\mathrm{PrimeGap}(M)$ be the maximum difference between a number $x\ (2\leq x\leq M)$ and the

Полный текст и комментарии »

Разбор задач Codeforces Round 1057 (Div. 2)
  • Проголосовать: нравится
  • +117
  • Проголосовать: не нравится

177.
Автор gojira, 13 лет назад, По-русски
Rockethon 2014 Editorial In this post you will find the authors' solutions for the problems and subproblems featured in the competition, as well as some bonus questions related to these tasks. [problem:391A] -------------- Note that we can consider each maximal sequence of identical characters independently, since there is no way to insert a character and affect more than one such sequence. Also, note that there are multiple ways to correct a single maximal sequence by inserting one character into it: we can either insert a different character somewhere in this sequence and divide it into two sequences of odd length (this is always possible for a sequence of even length), or even just add the same character in any point of this sequence, thus increasing its length by 1 and changing its parity. Therefore, the answer to the problem is the number of maximal sequences of even length. One can find all such sequences in linear time. A pseudocode of the solution follows: ~~~~~ i = 1 ans = 0 while i ...
will be involved in a streak of large values, so we can remove a constant fraction of the totalnumber

Полный текст и комментарии »

Разбор задач Rockethon 2014
  • Проголосовать: нравится
  • +101
  • Проголосовать: не нравится

178.
Автор -is-this-fft-, 3 года назад, По-английски
Counting forests with limited degrees and component sizes Someone posted a modified variant of [ABC 180 F](https://atcoder.jp/contests/abc180/tasks/abc180_f) here before and asked for help solving it. The task went as follows: given $n$ and $\ell$, count the number of labeled graphs on $n$ vertices such that no vertex has a degree exceeding 3, there is no cycle in any connected component (i.e. the graph is a forest) and the largest connected component has exactly $\ell$ vertices. I wrote a rather long comment explaining how to solve it. I hit "post" and... ![ ](/predownloaded/33/93/3393dfc4e72c3da020caac8d105c9de676e2df3d.png) the blog was gone. **To whoever was the author: please don't do this. It's very frustrating to put effort into writing an explanation only to discover that it had been completely in vain.** Even if you already got an answer from elsewhere, other users might enjoy reading the solution. It was not the case here, but especially don't delete/hide your blog if there already are answers in the comments. This way ...
the number of labeled graphs on $n$ vertices such that no vertex has a degree exceeding 3, there is no

Полный текст и комментарии »

  • Проголосовать: нравится
  • +126
  • Проголосовать: не нравится

179.
Автор BigBag, 6 лет назад, По-английски
Weak test cases for problem G from Grakn Forces, or how did I hack tourist Today I was upsolving a problem [problem:1408G] from the recent Grakn Forces 2020 contest. I've solved it, however I didn't really like my solution. So I decided to view how other participants solved this problem. Of course, I first opened the [user:tourist,2020-10-02]'s submission ([submission:94320762]), because his codes are always written in a good style and are easy to understand. But when I carefully looked through his solution, I was a little bit confused, because he used the idea, which I supposed to be wrong. The idea is the following: computers with indices $x_1$, $x_2$, $\ldots$, $x_k$ form a valid set, iff for each $i \in$ {$x_1, x_2, \ldots, x_k$}, values $a[i][x_1]$, $a[i][x_2]$, $\ldots$, $a[i][x_k]$ are smaller then all $a[i][j]$, where $j \notin$ {$x_1, x_2, \ldots, x_k$}. It's obvious that it's a necessary condition for being a valid set, and while solving this problem I first thought, that it can be also a sufficient condition. But after thinking a little bit...
problem. A similar [situation](https://codeforces.me/blog/entry/83259) (a smallnumber of system

Полный текст и комментарии »

  • Проголосовать: нравится
  • +269
  • Проголосовать: не нравится

180.
Автор plagues, 3 месяца назад, По-английски
The most outrageous cheating in the history of Huawei Challenge ![ ](/predownloaded/e4/f0/e4f0838fd7d6c43c6a92c2655748800519c78bd3.jpg) I am writing this because I believe that prohibited collaboration occurred during this Challenge and affected the prize positions. To state my personal conclusion plainly: I believe this is cheating, not merely a collection of innocent coincidences. The final positions relevant to the accounts discussed in this post were: | Rank | Handle | Final score | Result of my public-data review | |---:|---|---:|---| | 2 | [user:IceKylin,2026-08-28] | 16808.628 | Historical team with [user:candy0014,2026-08-28] named “IceKylin 0339 team”; all-time runtime/score leads with [user:candy0014,2026-08-28] and [user:Retired_Zhisheng,2026-08-28] | | 3 | [user:mahiro_zcy,2026-08-28] | 16757.390 | Repeated all-time runtime/score correlation with [user:mojo__hugo,2026-08-28]; repeated timing correlation with [user:Zinc-acetate,2026-08-28]; weak close event with [user:Mango2011,2026-08-28] | | 4 | [user:Zinc-acetate,2026-08-...
/distinct” prevents a large number of resubmissions at one score from looking like many independent

Полный текст и комментарии »

  • Проголосовать: нравится
  • +205
  • Проголосовать: не нравится

181.
Автор thanhchauns2, история, 5 лет назад, По-английски
Unofficial editorial for Codeforces Round #760 (Div.3) <spoiler summary="A small confession"> Hi, this is the first time I write such a blog like this. All is because of my excitement that for the first time I can solve all problems, not because I am worshiping myself or something. I know this is just a Div-3 contest, so there are many people who can solve it. But if you are stuck with some problems, feel free to read my solutions. This is not an official editorial, so the solutions might not be the best of all solutions out there, so if you have something to discuss, feel free to leave something below. Thanks for all. </spoiler> [A. Polycarp and Sums of Subsequences](https://codeforces.cc/contest/1618/problem/A) ------------------------------------------------------------------------------------- The first two numbers cannot be produced by a sum operation, so we have $2$ of $3$ numbers we must find. How to find the last one? Subtract these two from the largest one. <spoiler summary="Implentation"> ~~~~~ vector<ll> a(...
We need to optimize two things: the numbers we use in $k$ operations must be as large as possible

Полный текст и комментарии »

  • Проголосовать: нравится
  • +58
  • Проголосовать: не нравится

182.
Автор Black_Fate, 4 года назад, По-английски
[Educational] Combinatorics Study Notes (1) Hello Codeforces! Today I'll be writing about what I have learnt about combinatorics, which played, and, in my opinion, will still be playing a important role in both Codeforces and CP (short for competitive programming). However, combinatorics is such a great subject that made that impossible for me to write it all in one blog. So, this is just the very first blog, which is for beginners. If you are interested, please, pay attention to this account and I'll give posts as series for a long term. If you have found some mistakes in the text, or if you have some questions about the topic, please, leave a comment, and I'll check it weekly and reply. Also, if you find some grammar mistakes, a kind comment will be also welcomed. ### Thanks - [user:happyivan,2022-12-21], [user:Ptilon,2022-12-22], [user:ck1ne,2022-12-22] for pointing out some problems in the text. - [user:kill_all_placeholder,2022-12-21], [user:hydracody,2022-12-22] for providing possible topics. ### Content...
By the way, $\binom{n}{m}$ is a large number, so we usually get it modulus a number (usually a

Полный текст и комментарии »

  • Проголосовать: нравится
  • +139
  • Проголосовать: не нравится

183.
Автор Juve45, история, 6 лет назад, По-английски
Let's discuss solutions for catching cheaters The problem of cheating has been addressed many times in blog entries, many cheaters being reported. However, it seemed to me that few solutions were actually given. Therefore, I want to share my thoughts about how codeforces could prevent such behavior in the future: I think that, besides automated check (which also probably could be improved), there should be some sort of report mechanism, through which anyone could report a user for cheating &mdash; this could be implemented as a simple report button beside a standings line. Adding a short text or an image/link to an image to the report could also be an option. These reports could be handled by some **trustworthy** members of the community (high rated/contributing users). Even some sort of two-step verification could be implemented: after the first filtering of the trustworthy users, there could be a final check by someone from the codeforces staff (The first filtering phase will most probably reduce the quantity of reports)....
process could also be implemented: If some user receives a large number of reports, then he will be

Полный текст и комментарии »

  • Проголосовать: нравится
  • +358
  • Проголосовать: не нравится

184.
Автор Noam527, история, 4 года назад, По-английски
Attempting to Extend Segment Trees to Arbitrary Subsets Throughout the last several weeks I have tried to invent and solve, a generalization of segment trees (although now it doesn't fit to name it "segment trees"... see for yourself). The results are very few (and not good, if you ask me), but the problem was very appealing and fun to think about. The purpose of this blogpost is to share my experience with this problem, in order to provide curiousity to at least a few people, and also to let bright-minded users tackle this problem together, and hopefully achieve better results. Since I want to share my experience, I will also put some possibly challenging parts under spoilers, if you want to attempt it yourself. So, there is no tl;dr. Sorry :) The Motivation and The Problem ------------------------------ As the title suggests, the motivation was from inspection of segment trees. Define the following problem, which we will try to solve throughout this post: Given $n$ elements $a_0, \ldots, a_{n-1}$, initially $0$, and $m$ subs...
constructions work with $N$ bounded by some polynomial $p(n)$. Hence for large enough $n$, we have

Полный текст и комментарии »

  • Проголосовать: нравится
  • +200
  • Проголосовать: не нравится

185.
Автор feecIe6418, история, 20 месяцев назад, По-английски
InfOJ April Fools Day Contest 2025 (On April 5th) Hello Codeforces! I am glad to invite you to [InfOJ April Fools Day Contest 2025](http://119.27.163.117/contest/28) (IAFDC for short) which will start on [April 5th 2025, 19:00 UTC+8](https://www.timeanddate.com/worldclock/fixedtime.html?day=5&month=4&year=2025&hour=19&min=00&sec=0&p1=33). The problem setters are me and [user:gyh20,2025-03-22]. This is not a joke: the contest will really be held! The contest will last for 2.5 hours with 10 tasks for you to solve. All problems are worth 100 points, and the contest will be in IOI mode with standings. You can see the past problems [here](http://119.27.163.117/contests). ## Why is April Fool's Contest not on April Fools Day? From the year 2023, the contest has always been held on April 5th, to match the Tomb Sweeping Day's break in Chinese schools. ## Language of Problem Statements We will provide English statements for all problems. However, in the past several years, only Chinese statements are available. If you wan...
You need to print a number that is "distant enough" from the numbers

Полный текст и комментарии »

  • Проголосовать: нравится
  • +53
  • Проголосовать: не нравится

186.
Автор MateoCV, история, 5 лет назад, По-английски
Codeforces Round #774 (Div. 2) Editorial Thanks for participating in the round! I hope you enjoyed the problems! [problem:1646A] <spoiler summary="Solution"> [tutorial:1646A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; for(int i = 0; i < t; i++){ long long n, s; cin >> n >> s; cout << s / (n * n) << "\n"; } return 0; } ~~~~~ </spoiler> [problem:1646B] <spoiler summary="Solution"> [tutorial:1646B] </spoiler> <spoiler summary="Additional comment"> It can be proven that (try to prove it!) if some $k$ works, then $k=\displaystyle \left \lfloor \frac{n-1}{2} \right \rfloor$ has to work. This means that there is always an answer using $n$ or $n-1$ elements, depending on parity. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t; cin >> t; for(int test_number = 0; test_number < t; test_numb...
answer modulo some big prime number). Try to solve the problem with this new constraint!

Полный текст и комментарии »

Разбор задач Codeforces Round 774 (Div. 2)
  • Проголосовать: нравится
  • +136
  • Проголосовать: не нравится

187.
Автор Osama_Alkhodairy, история, 7 лет назад, По-английски
[Insight] Number of Topological Orderings of a Directed Tree I was checking [this](https://csacademy.com/contest/round-11/task/connected-tree-subgraphs/statement/) problem on csacademy, and I came up with the dp combinatorics solution to calculate the number of topological orderings of a directed tree with a fixed root. First, let me explain this solution. Let's root the tree at node $1$ and calculate $sz_v$ = size of the subtree rooted at $v$. Let $dp_v$ be the number of possible topological orderings of the subtree rooted at $v$. To calculate $dp_v$, let's imagine $v$ has only two children: $x$ and $y$. We can see quite easily that $dp_v = dp_x * dp_y * {sz_x+sz_y \choose sz_x}$. That's because any valid topological ordering of the subtree of $v$ will begin with $v$ itself and then $sz_x+sz_y$ nodes, and because the nodes of $x$'s and $y$'s subtrees are independent, all possible combinations between them are possible. So, we will choose $sz_x$ spots of the $sz_x+sz_y$ spots and put in them all the nodes form $x$'s subtree and put on the res...
[Insight] Number of Topological Orderings of a Directed Tree, /statement/) problem on csacademy, and I came up with the dp combinatorics solution to calculate thenumber, The number of valid orderings for the whole tree is $dp_1 = \frac{n!}{\prod_{v=1}^{n} sz_v}$. Here

Полный текст и комментарии »

  • Проголосовать: нравится
  • +88
  • Проголосовать: не нравится

188.
Автор artew, 3 года назад, По-русски
Codeforces Round #932 (Div. 2) Editorial [problem:1935A] Idea: [user:i_love_penguins,2024-02-24] <br> Preparation: [user:i_love_penguins,2024-02-24] <br> Editorial: [user:i_love_penguins,2024-02-24] <spoiler summary="Hints"> <spoiler summary="Hint 1"> The answer will always have either the prefix $s$, or the reversed string $s$. </spoiler> <spoiler summary="Hint 2"> Adding the string to the end is required no more than once. </spoiler> </spoiler> <spoiler summary="Solution"> Let $t$ be the reversed string $s$. Notice that it is advantageous for us to use operation 1 (adding the reversed string at the end) no more than once. Indeed, having obtained some string, we will simply spend the remaining operations on flipping the string. Thus, we will get the original string or the reversed one, depending on the parity of the number of remaining operations. It is easy to see that the answer will always have either the prefix $s$, or $t$. Then, we find two lexicographically minimal strings with the prefix $s...
, y_i)$ and find the bitwise largest common prefix — let it be number $w$. Then it is clear that

Полный текст и комментарии »

Разбор задач Codeforces Round 932 (Div. 2)
  • Проголосовать: нравится
  • +213
  • Проголосовать: не нравится

189.
Автор ditoly, история, 8 лет назад, По-английски
Codeforces Round #511 Editorial Hi, here is the editorial. Sorry for a long waiting. Have you enjoyed this round? I hope so. I know there are many things not so good and making some people unhappy :( I'm very sorry about that. Since this is my first round, I have many things not taken into consideration or done badly. I will try to improve them if I have my next round (I hope). Let's talk about the problems. The problems are mainly prepared by me, [user:ditoly,2018-09-22], which can be seen in D1D as "Little D". Also, my friends [user:ACMLCZH,2018-09-22] ("Little C") and [user:FallDream,2018-09-22] ("Mr. F", I don't know whether this name can explain Chinese word "F大爷" well, maybe "Master F" is better?) provided great helps. The statements are mainly written by me (with the help of [user:300iq,2018-09-22] and [user:cyand1317,2018-09-22] and some others, thanks!). My English is not so good, so it's frequent that I just understand the problem but other people get AC :( So I try to explain the problems in short st...
A remainder problem is it can not be modulo $p$ when calculating in this algorithm, so thenumber

Полный текст и комментарии »

Разбор задач Codeforces Round 511 (Div. 1)
Разбор задач Codeforces Round 511 (Div. 2)
  • Проголосовать: нравится
  • +191
  • Проголосовать: не нравится

190.
Автор tokitsukaze, 5 лет назад, По-английски
Codeforces Round #789 Editorial [problem:1678A] Idea: [user:tokitsukaze,2022-05-08] <br /> Prepare: [user:tokitsukaze,2022-05-08] <spoiler summary="Tutorial"> We observe that when there is $0$ in the sequence, it is optimal to choose $0$ and any number other than $0$ for each operation. Therefore, when there is $0$ in the sequence, let $cnt$ be the number of $0$s, the answer is $n - cnt$. Otherwise, when $0$ does not exist in the sequence, there are two situations: 1. When there exist two equal numbers in the sequence, we can perform the operation $1$ time to convert it into the situation of having $0$ in the sequence. So the answer must be $n$. 2. When all numbers in the sequence are distinct, we can perform the operation $2$ times to convert it into the situation of having $0$ in the sequence. So the answer must be $n + 1$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(){ int t; scanf("%i",&t); while(t--){ int n; scan...
$ is preceded by a number larger than the current position, then it will definitely be exchanged and, In order to maximize the score, we make the larger number in the permutation "peak" and the smaller, Let $S=\{1,2,\ldots,n\}$, and find that the last number can be determined through $c_n$, because

Полный текст и комментарии »

Разбор задач Codeforces Round 789 (Div. 1)
Разбор задач Codeforces Round 789 (Div. 2)
  • Проголосовать: нравится
  • +115
  • Проголосовать: не нравится

191.
Автор ivan100sic, история, 5 лет назад, По-английски
Let's solve some hard problems! Tonight, I will pick twelve 3000 rated problems I haven't solved yet, try solving them, and track my progress. As usual, I will not look at editorials. Hopefully I will be able to solve them all before the year ends. I will not make this my highest priority and I won't try too hard. I will keep solving other problems in the meantime. The problems are: 1. [problem:341E] (solved Jan 14, 12 days) 2. [problem:843E] 3. [problem:1250D] (solved Jan 5, 3 days) 4. [problem:573D] (solved Jan 6, 4 days) 5. [problem:1290D] (solved Jan 8, 6 days) 6. [problem:568E] 7. [problem:788D] (solved Jan 14, 12 days) 8. [problem:698F] (solved Jan 3, 1 day) 9. [problem:1342F] (solved Jan 4, 2 days) 10. [problem:1236F] (solved Jan 3, 1 day) 11. [problem:533A] (solved Jan 16, 14 days) 12. [problem:1411F] (solved Jan 22, 20 days) My thoughts on the problems I have solved: <spoiler summary="Problem 1"> I had a lot of fun solving this! <spoiler summary="My solution"> I use only a few tho...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +197
  • Проголосовать: не нравится

192.
Автор LorentzianExpanders, история, 21 месяц назад, По-английски
Modulo Inversion in Constant Time, with Subpolynomial Precomputation Hi everyone, In this post, I'll share a method to compute modular inverses in $O(1)$ time under some $p^{\varepsilon}$-time precomputation. Rather than simply computing the modular inverse, we aim to solve for a pair of integers $x, y$ such that $ax + by = \gcd(a, b)$. I.e., find the solution of the Bezout equation. #### Observations > **Observation.** For two non-zero positive integers $a, b$ less than some bound $X$, there exists an invertible integer matrix $M \in \mathrm{GL}_2(\mathbb{Z})$ such that one component of the vector $M \begin{pmatrix}a\\\\b \end{pmatrix}$ is bounded by $X^{1/2}$, and the absolute values of the elements in $M$ are also bounded by $X^{1/2}$. _Proof._ The pigeonhole principle is sufficient to prove this observation. However, there could be a more algorithmic proof by analyzing the execution of Euclid's algorithm. We omit the details of this proof here. $\square$ > **Corollary.** Given two non-zero positive integers $a, b$ less than $X$, an...
via a table lookup. Afterward, apply one step of the Euclidean algorithm to reduce the othernumber.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +116
  • Проголосовать: не нравится

193.
Автор MikeMirzayanov, 15 лет назад, По-русски
Codeforces::Gym <p> We've made it! Or in any case, we are at least very close to it. </p> <p> On January 19, 2012 at 12:00 we open a sub-project called &quot;Gym&quot;. In short, its goal is to enable the Codeforces coders not only to participate in competitions and discuss them, but also to train and coach easily. </p> <p> In fact, despite the wide diversity of online judges in the world, a well thought-out training service system does not exist. So, the expectations from this system are: </p> <ol> <li>Collection of online contests, composed mainly of the past official contests. </li><li> Opportunity to integrate the final standings of past contests in the online contests to be able to train &quot;against&quot; the official participants. </li><li> Opportunity to participate in the training at any time whatsoever, without fear that something breaks down and the server will fall. In short, reliability. </li><li> Opportunity to write virtual contests and to solve the problems in a practice mode. </li...
RoundUp is the function of rounding up to an integer number of seconds. We believe that this is a, they see that you have violated these simple rules. If we find that we have a large number of such

Полный текст и комментарии »

  • Проголосовать: нравится
  • +419
  • Проголосовать: не нравится

194.
Автор Bashca, 6 лет назад, По-английски
Fenwick Tree generalization using Centroids Hello, Codeforces community! (Again) After asking many times, I realized that the central idea of this blog was not being understood, and I’ve finally decided to rewrite it. This time I want to be clearer and provide more details. This is not about the classic centroid decomposition, but I’ll try to keep it self-contained so the concept is understandable within this blog. --- ## What is a Centroid? In a tree, a centroid is a node that, when removed along with its incident edges, minimizes the size of the largest remaining connected component, see figure 1. <center> <img src="/predownloaded/03/3f/033f954d1d44920150b706caa12c0045f41bced4.png" alt="centroid of a tree and remaining components"> <br> <I>figure 1. Centroid of a tree and remaining components</i> </center> **Claim**: Let $W(v)$ be the size of the largest component after removing node $v$, and $n$ be the total number of nodes. If $v$ is a centroid, then: $$W(v) \le \frac{n}{2}$$ **Proof**: Supp...
total number of nodes. If $v$ is a centroid, then:

Полный текст и комментарии »

  • Проголосовать: нравится
  • +188
  • Проголосовать: не нравится

195.
Автор piaoyun, история, 5 месяцев назад, По-английски
Anti-cheating in the LLM Era I think many people now hold such an idea: LLMs have already historically defeated CP, and catching those cheaters is only useless effort. The fairness of CF and the value of rating will finally disappear. But, is CP the first game where humans were defeated? Long time ago, Deep Blue defeated chess, AlphaZero defeated Go, scripts and mouse macros defeated FPS games, and GTO defeated Poker. The fact is, chess developed faster time controls that are harder to cheat in. Thousands of millions of real money still flows on poker websites. FPS game companies rely on automatic detection and community anti-cheat to continuously reduce the percentage of cheaters in the game, until it reaches a level that can basically be tolerated. In this article, I list some anti-cheating methods that I know. Maybe not all of them are feasible. But what I want to express is that we still have many methods to defend the purity of the CP community. ## 1. KYC (Know Your Contestant) & VP (Verified Play...
A large number of honest CF users have already mobilized to find cheaters, and summarized many

Полный текст и комментарии »

  • Проголосовать: нравится
  • +117
  • Проголосовать: не нравится

196.
Автор adamant, 13 лет назад, По-русски
C++ STL: Policy based data structures Hi everyone! After a relatively long lull, I decided that <s>my contribution growing too slowly</s> the hour has come to please you with another article in the blog _:)_ 2 months ago user [user:Perlik,2014-03-19] wrote an [article] (/blog/entry/10355), in which he described a very interesting STL implemented data structure that allows you to quickly perform various operations with substrings. Some time after I tested it on various tasks and, unfortunately, tend to get a negative result &mdash; rope was too slow, especially when it came to working with individual elements. For some time, I forgot about that article. Increasingly, however, I was faced with problems in which it was necessary to implement set with the ability to know ordinal number of item and also to get item by its ordinal number (ie, order statistic in the set). And then I remembered that in the comments to that article, someone mentioned about the mysterious data structure order statistics tree, which supports th...
; the number of items in a set that are strictly smaller than our item. Example of use:

Полный текст и комментарии »

  • Проголосовать: нравится
  • +120
  • Проголосовать: не нравится

197.
Автор _LeMur_, 3 года назад, По-английски
Editorial of Codeforces Round 917 (Div. 2) [problem:1917A] Author: [user:zidder,2023-12-24] <br> Preparation: [user:_LeMur_,2023-12-24] <br> Editorial: [user:zidder,2023-12-24] <br> Official solution: [submission:238752794] <br> <spoiler summary="Hint 1"> What is the minimum product that we can get, when one of the given numbers is equal to $0$. </spoiler> <spoiler summary="Hint 2"> How is the absolute value of the integer changed, when we apply the given operation on that integer? </spoiler> <spoiler summary="Hint 3"> We can always make the product as small as possible with at most $1$ operation. </spoiler> <spoiler summary="Solution"> First, let's find the minimum product we can get. If one of the numbers is or becomes $0$, then the product will be $0$. Otherwise, all the numbers don't change their sign during the operation. So the initial product won't change its sign as well. Also, we can note that the absolute value will not increase after an operation. That means if the initial product is negative...
, which are followed by several red elements. The number of blue elements in the beginning is equal to

Полный текст и комментарии »

Разбор задач Codeforces Round 917 (Div. 2)
  • Проголосовать: нравится
  • +192
  • Проголосовать: не нравится

198.
Автор Endagorion, 15 лет назад, По-русски
Codeforces Beta Round #99: editorial <h3>[[problem:139A]]</h3>If the total number of pages doesn't exceed the number of pages for Monday, the answer is Monday. Otherwise we can substract the Monday number from total and go on to Tuesday. If Tuesday isn't enough, we subtract and continue to Wednesday, and so on. We are sure that no more than N weeks will pass, as at least one page is read every week. Complexity - O(N).<br /><br /><h3>[[problem:139B]]</h3>Unluckily, the translated statement was <strike>quite tough</strike> even tougher to understand than the original statement.<br /><br />Say we fixed the roll type and the room. The only possible way to cut the roll is to cut it into vertical stripes with length equal to room's height (though it was said we can cut it any way we want, there were some conditions to fulfill, namely there could be no joints other than vertical). So we find the total width of stripes we can cut our roll into as the (length of the roll / height of the room) (rounded down) * (width of the roll). ...
This solution is good in theory, but in practice it has a flaw: if the number of segments islarge

Полный текст и комментарии »

Разбор задач Codeforces Beta Round 99 (Div. 1)
Разбор задач Codeforces Beta Round 99 (Div. 2)
  • Проголосовать: нравится
  • +68
  • Проголосовать: не нравится

199.
Автор -is-this-fft-, 5 лет назад, По-английски
[Tutorial] Proving the inverse Ackermann complexity of Union-Find #### Introduction Most of us are familiar with the union-find data structure and the two optimizations one can do on it: _union by rank_ and _path compression_. Most tutorials will introduce these methods and state that if both optimizations are used, the complexity will be $\mathcal{O}((n + m) \alpha(n))$. Here, $n$ and $m$ are the number of vertices and queries respectively. What is $\alpha$? Generally, we are told that $\alpha$ is some mysterious function that grows very slowly: $\alpha(N) < 5$ where $N$ is the number of subsets of particles in the observable universe and whatnot. What it is is usually not clarified very much. And there is typically no proof (or intuition and other such justifications) as to why the complexity is like that: usually we're told that the complexity analysis is quite long and complicated. At the time of writing, both [cp-algorithms](https://cp-algorithms.com/data_structures/disjoint_set_union.html) and [Wikipedia](https://bit.ly/3EvnzrI) are like th...
) \alpha(n))$. Here, $n$ and $m$ are the number of vertices and queries respectively. What is $\alpha

Полный текст и комментарии »

  • Проголосовать: нравится
  • +448
  • Проголосовать: не нравится

200.
Автор Zlobober, 11 лет назад, По-английски
An editorial of Topcoder SRM 672 Hi everybody! It was my first experience of writing problems for TopCoder SRM, hope you liked it. I was a writer of Easy and Medium task in both divisions, [user:subscriber,2015-10-21] was an author of both Hard tasks. In div1 they were harder than usual, but I hope you still liked them. #### Div2 easy This task was just about implementing exactly what is described in the statement. Looks like Python has a built-in support of set comparison. Usually coders using Python have a disadvantage, but in this task it looks more like an advantage :) There are built-in functions for sets in C++ and Java too, I recommend to learn about them even if you successfully submitted this problem. #### Div2 medium Knowing strings a and b, we can build a reverse mapping $q[d] = c$, that maps the encoded letter $d$ to it's original corresponding letter $c$. For letters that do not appear in $b$, we remember that we don't know their pre-image. After that, we just apply our mapping $q$ to a string...
simulate the process. Suppose we are now standing in number $n$, the last hour was $h$, it means that, The key observation is that when we change our number, we don't need to find divisors of a new

Полный текст и комментарии »

  • Проголосовать: нравится
  • +103
  • Проголосовать: не нравится

201.
Автор Geothermal, история, 7 лет назад, По-английски
AtCoder Beginner Contest 140 English Solutions #A &mdash; Password We have $N$ choices for each of the three characters in our password. This gives us a total of $N \cdot N \cdot N = N^3$ possible passwords. We can thus print $N \cdot N \cdot N$ as our answer. Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc140/submissions/7380201) --- #B &mdash; Buffet We can solve this with a brute-force simulation, simply implementing the procedure given in the problem. Iterate over the dishes in the order specified by array $A$, and when we eat dish $i$, add $B[i]$ to our answer, plus $C[i-1]$ if we just ate dish $i-1$. Note that since we'll eat every dish once, we could also just add the sum of array $B$ to our answer as we read it in, iterating over $A$ only to add values from $C$ where necessary. My solution implements this approach. Runtime: $O(N)$. [Click here for my submission.](https://atcoder.jp/contests/abc140/submissions/7383059) --- #C &mdash; Maximal Value We're giv...
-last positions of greater numbers in the set before the current number. Similarly, let $x$ and $y

Полный текст и комментарии »

  • Проголосовать: нравится
  • +117
  • Проголосовать: не нравится

202.
Автор Geothermal, история, 7 лет назад, По-английски
Codeforces Round #570 Solutions Since it will be a little while longer before the editorials for the recent Division 3 Round come out, I thought I'd post some solutions I wrote up. Please feel free to post below if you have any questions or notice any errors. If any of my solutions end up getting hacked, I'll replace the submission and solution text as soon as possible. Links to my submissions are at the bottom of this post. --- **A:** We can easily prove that the answer will not be much bigger than A, so simply iterating through all the possible values until we find one that works will do fine. (As a trivial proof, note that 1003 is interesting, so we will have to test at most 1003 numbers.) Then, the only challenging part from here is finding the sum of the digits of a number, which can be implemented easily with modular arithmetic. --- **B:** Start by sorting the prices. It turns out that only the greatest and least prices matter. We have two key facts to prove: 1. The answer is -1 if the ...
candidates in decreasing order of size. While it doesn't divide the number on top of the stack, pop this, of type-1 candies in sets of candies large enough to use. Then, iterate through the numbers of types, number of subsequences with the current length (all of them, unless this gives us more than K total

Полный текст и комментарии »

  • Проголосовать: нравится
  • +110
  • Проголосовать: не нравится

203.
Автор djm03178, 2 года назад, По-английски
Different behavior between gcd and __gcd I experienced something weird while solving [problem:2050F]. Basically, I tried solving it by decomposing the array into $\mathcal{O}(\sqrt{n})$ blocks. I submitted several of them each using difference size of blocks, and they passed in 2s during the contest. Surprisingly, in system tests, all of my submissions got TLE on my hack test that was used to hack other similar solutions that worked much slower in the original tests. It felt really weird, because the most basic `gcd` implementation we learn is something like this: ~~~~~ int G(int a, int b) { return b ? G(b, a % b) : a; } ~~~~~ Although a single call for this function takes $\mathcal{O(\log{x}})$ time where $x$ is the value of the input, when we repeatedly apply this fuction $k$ times where either $a$ or $b$ is the result of a previous call on this function, it should only take $\mathcal{O}(k+\log{x})$ because the depth of the recursion gets deeper only when the result gets smaller. Thus, my solution should o...
time proportional to the number of significant bits of the input, even if the result remainslarge. For

Полный текст и комментарии »

  • Проголосовать: нравится
  • +204
  • Проголосовать: не нравится

204.
Автор Lewin, история, 11 лет назад, По-английски
Wunder Fund Round 2016 Editorials I hope you enjoyed the contest! Let me know if you find any errors below. Thanks for participating. Short solutions: - Slime Combining: You can just do what's described in the statement. Or, maybe you can do something with the binary representation of the number. - Guess the permutation: Find out where 1 should go. Then, find out where 2 should go, and so on. - Constellation: Start with a triangle and break it up. Or, choose a point and look at angles. Or, sort by x coordinate. - Hamiltonian Spanning Tree: Two cases: X > Y and X <= Y. For X > Y we can almost always avoid the spanning tree edges. For X <= Y we can do something greedy. - Robot Arm: Make a segment tree on segments. A segment is basically just a linear transformation, which can be described with three numbers. - Double Knapsack: Make the problem harder. Let's say I want a consecutive sublist of both lists that have equal sums. Then use pigeonhole principle to get an answer. - Combining Slimes: Use conditional e...
Another approach that would also work is that after a large number of squares, the probabiltiy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +128
  • Проголосовать: не нравится

205.
Автор Secret_Eagle, история, 5 лет назад, По-русски
Yes, again about cheaters Hello, Codeforces! You may have noticed that a lot of blogs are created about cheaters, and these blogs usually look at two or three users and compare their submissions. **In my opinion, this approach is fundamentally wrong. After all, such blogs are fighting not the cause but the effect of the problem.** Let me tell you a little bit about what interested me in these blogs. When I looked at the profiles of cheaters, I noticed that they are often not from one city, and sometimes live really far away from each other. It seemed to me that cheaters were sometimes in different countries as well! From that I have made a fairly simple and obvious conclusion for many &mdash; the existence of Telegram/Youtube channels, where they publish solutions to problems. Frankly speaking, I have found such channels several times already, but I wondered if I could find "help" in Codeforces solutions if I directly entered key words like: _"codeforces contest ongoing solutions telegram"_ into the se...
) Solutions for rounds very easy to find, and a large number of groups with cheaters, they are also not

Полный текст и комментарии »

  • Проголосовать: нравится
  • +271
  • Проголосовать: не нравится

206.
Автор Error_Yuan, история, 2 года назад, По-английски
Refact.ai Match 1 (Codeforces Round 985) Editorial Thank you all for participating in the round! We apologize for the wrong checker in problem E at the beginning of the contest, as well as the weak tests in problem B. To be honest, all the hacked submissions have similar logic and codes in B, which made me suspicious. Anyway, we are sorry for the inconvenience! >_< <spoiler summary="Rating Predictions"> | |A|B|C|D|E|F|G|H|I| |:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:| |[user:Error_Yuan,2024-11-7]|800|1200|**1600**|**2100**|**2300**|2600|**3000**|3400|**3500**| |[user:sszcdjr,2024-11-7]|800|1100|1600|2000|2300|**2600**|2900|**3300**|3500| |[user:wyrqwq,2024-11-7]|800|**1000**|1400|2200|**2300**|2600|**3000**|3500|3500| |[user:Otomachi_Una,2024-11-7]|**800**|1000|1600|2200|2400|2600|3200|3500|3500| |[user:dxqwq,2024-11-7]|900|1100|1700|2200|2400|2600|3200|3500|3500| |[user:Kubic,2024-11-7]|800|1000|1600|2400|2200|2800|3000|3500|3300| |[user:wsc2008qwq,2024-11-7]|800|1100|1600|1900|2200|2700|3100| | | |[user:chroma...
We can delete the numbers from small to large. Thus, previously

Полный текст и комментарии »

  • Проголосовать: нравится
  • +136
  • Проголосовать: не нравится

207.
Автор salyg1n, 3 года назад, По-русски
Codeforces Round #897 (Div. 2) Editorial Hello everyone! We're very sorry for the delay >_< We hope you enjoyed the tasks! Sorry for too tight limits in C so that Java solutions don't pass (actually one of our authors nickname used to be "java." :D), we'll hopefully do a better job next time! Feel free to leave your feedback in the comments. [1867A &mdash; green_gold_dog, array and permutation](https://codeforces.me/contest/1867/problem/A) Author: [user:green_gold_dog,2023-09-12] <spoiler summary="Tutorial"> Let's subtract $n$ from the minimum number, subtract $n - 1$ from the second minimum, $n - 2$ from the third $\ldots$, and subtract $1$ from the maximum. Then the number of distinct elements will be $n$. Obviously, it is impossible to achieve a better result. Let's prove that the number of distinct elements will be equal to $n$. Suppose $c_i = c_j$, then without loss of generality, let's say that $b_i > b_j$, then $a_i \leq a_j$, which means $c_i = a_i - b_i$ < $a_j - b_j = c_j$. Contradiction. ...
Notice that the $\operatorname{MEX}$ of a set is the largest number k such that all numbers from $0

Полный текст и комментарии »

Разбор задач Codeforces Round 897 (Div. 2)
  • Проголосовать: нравится
  • +107
  • Проголосовать: не нравится

208.
Автор dario2994, 4 года назад, По-английски
pol2dom: Convert problems from Polygon to DOMjudge TL;DR: I am advertising [pol2dom](https://github.com/dario2994/pol2dom): a tool to convert a set of problems prepared in Polygon into a DOMjudge contest. The whole process is automated: downloading the Polygon package, converting it into a DOMjudge package, and uploading the DOMjudge package to a DOMjudge server. If you are organizing a contest that uses DOMjudge, I invite you to give `pol2dom` a try. #### Long story [Polygon](https://polygon.codeforces.com/) is the platform used to prepare problems for Codeforces rounds (and, at least one year ago, for Codechef rounds). It has [many issues](https://codeforces.me/blog/entry/90914) but, as far as I know, it is the best platform for preparing competitive programming problems. It has a large number of checks that catch common mistakes, it is hosted online, it allows a coordinator to quickly review the preparation, and so on. As everyone, I would like to see Polygon improve (for example, with a decent UI), but there's nothing ...
programming problems. It has a large number of checks that catch common mistakes, it is hosted online, it

Полный текст и комментарии »

  • Проголосовать: нравится
  • +160
  • Проголосовать: не нравится

209.
Автор caustique, 13 лет назад, По-русски
Editorial for Codeforces Round #202 ### [problem:349A] In the problem you need to decide whether cashier can give a change to all customers if the price of the ticket is 25 rubles and there's 3 kinds of bills: 25, 50 and 100 rubles. There's no money in the ticket office in the beginning. Let's consider 3 cases. - Customer has 25 rubles hence he doesn't need a change. - Customer has 50 rubles hence we have to give him 25 rubles back. - Customer has 100 rubles hence we need to give him 75 rubles back. It can be done in 2 ways. 75=25+50 и 75=25+25+25. Notice that it's always worth to try 25+50 first and then 25+25+25. It's true because bills of 25 rubles can be used both to give change for 50 and 100 rubles and bills of 50 rubles can be used only to give change for 100 rubles so we need to save as much 25 ruble bills as possible. The solution is to keep track of the number of 25 and 50 ruble bills and act greedily when giving change to 100 rubles &mdash; try 25+50 first and then 25+25+25. ### [problem:349B] ...
### [problem:349B] In the problem you're asked to write the largest possible number given number, Longer number means larger number so it's worth to write the longest possible number. Because of

Полный текст и комментарии »

Разбор задач Codeforces Round 202 (Div. 1)
Разбор задач Codeforces Round 202 (Div. 2)
  • Проголосовать: нравится
  • +50
  • Проголосовать: не нравится

210.
Автор Geothermal, история, 6 лет назад, По-английски
AtCoder Beginner Contest 172 English Solutions #A &mdash; Calc Just directly print the given sum. Time Complexity: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc172/submissions/14750143) --- #B &mdash; Minor Change The answer is simply the number of positions $i$ for which $S[i] \neq T[i]$. This is because we must make a move fixing each of those position, and each move can only make $S[i] = T[i]$ for one new position. Thus, we can iterate through the positions and count those where $S$ and $T$ differ, printing the total as our answer. Time Complexity: $O(|S|)$. [Click here for my submission.](https://atcoder.jp/contests/abc172/submissions/14750027) --- #C &mdash; Tsundoku We apply two pointers. Iterate over the number of books to be read from desk A in decreasing order, starting with the greatest number of those books we could read without exceeding $K$ minutes. Maintain the sum of all books to be read from desk A. Then, while we can do so without exceeding $K$ minutes, add ...
Change The answer is simply the number of positions $i$ for which $S[i] \neq T[i]$. This is, throughout our process may not equal $A_1 + A_2$, since the number of bits we assign is largely determined

Полный текст и комментарии »

  • Проголосовать: нравится
  • +259
  • Проголосовать: не нравится

211.
Автор rabaiBomkarBittalBang, 5 лет назад, По-английски
Codeforces Round #724 — Editorial We hope you liked the problems! If you’re curious about the two different problem formats, initially [user:Tlatoani,2021-06-06], [user:golions,2021-06-06], [user:qlf9,2021-06-06] and I were working on Omkar 3 with [user:antontrygubO_o,2021-06-06] while [user:hu_tao,2021-06-06] was working on a separate round with [user:isaf27,2021-06-06]. We eventually decided to join forces and combine the rounds, resulting in the current Omkar 3. <h1>[problem:1536A]</h1> Idea: [user:rabaiBomkarBittalBang,2021-06-06] Preparation: [user:rabaiBomkarBittalBang,2021-06-06], [user:Tlatoani,2021-06-06], [user:qlf9,2021-06-06] [Video editorial](https://www.youtube.com/watch?v=GZeihS2xTSc) <spoiler summary="Hint"> Consider what happens when $a$ contains a negative number. </spoiler> <spoiler summary="Solution"> We first claim that if any negative number exists in $a$, then no solution exists. Denote $p$ as the smallest number in $a$ and $q$ as another arbitrary number in the array (as $n...
. This is the only valid assignment because if we make any number larger, there will exist a pair of

Полный текст и комментарии »

Разбор задач Codeforces Round 724 (Div. 2)
  • Проголосовать: нравится
  • +257
  • Проголосовать: не нравится

212.
Автор AndreyPavlov, история, 4 года назад, По-русски
Codeforces Round #846 (Div. 2) — Tutorial [problem:1780A] Idea: [user:AndreyPavlov,2023-01-24] <br> Preparation: [user:AndreyPavlov,2023-01-24] <br> Editorialist: [user:AndreyPavlov,2023-01-24] <spoiler summary="Tutorial"> Note that there are two variants of which numbers to take to make their amount odd: $3$ odd number; $2$ even and $1$ odd. Let’s save all indices of even and odd numbers into two arrays, and check both cases. </spoiler> <spoiler summary="Implementation (Python)"> ~~~~~ def solve(): n = int(input()) a = list(map(int, input().split())) odd, even = [], [] for i in range(n): if a[i] % 2 == 0: even.append(i + 1) else: odd.append(i + 1) if len(odd) >= 1 and len(even) >= 2: print("YES") print(odd[0], even[0], even[1]) elif len(odd) >= 3: print("YES") print(odd[0], odd[1], odd[2]) else: print("NO") t = int(input()) for test in range(t): solve() ~~~~~ </spoiler...
equal. Consider any block of units length $len$, then for $len + 1$ substrings length $k$number of

Полный текст и комментарии »

Разбор задач Codeforces Round 846 (Div. 2)
  • Проголосовать: нравится
  • +348
  • Проголосовать: не нравится

213.
Автор ATSTNG, история, 5 лет назад, По-английски
What is efficient number system conversion for big integers? Number system conversion algorithm is well-known and taught in almost every basic programming course. To get $y_b = x_{10}$ (number $y$ written in base $b$ equal to number $x$ base $10$) we have to iteratively chop the lowest digit in base $b$ from number $x$ using division and remainder operators: ~~~~~ def naive_conversion(x, base): y = "" while x > 0: y = str(x % base) + y x //= base return y ~~~~~ This works in $\mathcal{O}(\log x)$ for all $x$ that fit into machine word $(\log x < w)$. However this becomes inacceptably slow when we consider numbers of length $n$ that is large enough and we cannot use $\mathcal{O}(1)$ division. Let's define $n$ as length of converted number $x$ in some number system $(w \ll \log x = n)$. Still, base of number systems $b$ and all digits in it can be stored in usual integer. So we can implement conversion above in $\mathcal{O}(n^2)$ with some efficient implementation of big-number-by-small-number division. ...
What is efficient number system conversion for big integers?, this becomes inacceptably slow when we consider numbers of length $n$ that is large enough and we

Полный текст и комментарии »

  • Проголосовать: нравится
  • +39
  • Проголосовать: не нравится

214.
Автор lrvideckis, история, 21 месяц назад, По-английски
on minimizing the expected number of recursive calls for segment tree For the longest time, this comment https://codeforces.me/blog/entry/112755#comment-1004966 was bugging me (the part about how the 'complete' segment tree is 20% slower (complete, because it’s a complete binary tree)). Instead of benchmarking, this blog calculates the expected number of recursive calls visited between segment tree implementations. Thanks to [user:camc,2025-03-03] for giving valuable feedback. This blog will study 2 implementations of segment trees. <spoiler summary="'standard' segment tree"> ~~~~~ void dfs(int v, int l, int r) { // [l, r) if (r - l == 1) { return; } int m = (l + r + 1) / 2; dfs(2 * v, l, m); dfs(2 * v + 1, m, r); } // dfs(1, 0, n); ~~~~~ </spoiler> And <spoiler summary="'complete' segment tree"> ~~~~~ int split(int l, int r) { int pw2 = 1 << __lg(r - l); return min(l + pw2, r - pw2 / 2); } void dfs(int v, int l, int r) { // [l, r) if (r - l == 1) { return; } int m = split(l, r); dfs(2 ...
on minimizing the expected number of recursive calls for segment tree

Полный текст и комментарии »

  • Проголосовать: нравится
  • +52
  • Проголосовать: не нравится

215.
Автор swapnil07, 6 лет назад, По-английски
Expectation in Random Walk <p>I have always been fascinated by the idea of random walk. Recently, [user:jiraya_,2021-03-11] and I observed some new ideas in this domain. Thus, I wanted to share the same with you and get your insights regarding the same. </p> <h4>Assumptions</h4> <ol> <li>The initial position of the person is assumed to be $X$ (positive integer) on the number line <li>The walk is not absolutely random, i.e., the probability of person moving from position $Y$ to position $Y+1$ is $p$, and the probability of person moving from position $Y$ to position $Y-1$ is $q$. Obviously, $p + q = 1$. <li>There is a pit at position 0, therefore a person who reaches the position 0 does not move further. </ol> <h4>Pre-requisites</h4> <p> The proof regarding the pre-requisites used in this blog can be found [here](http://www2.math.uu.se/~sea/kurser/stokprocmn1/slumpvandring_eng.pdf). <p>I have used the following results for this blog: <ol> <li> The probability of person to reach position $Y=0$ from pos...
In this blog, we only consider the scenario for various cases after very large (or maybe

Полный текст и комментарии »

  • Проголосовать: нравится
  • +141
  • Проголосовать: не нравится

216.
Автор brunomont, 2 месяца назад, По-английски
tgen::miniblog(5): random graphs with large diameter <center> <img src="/predownloaded/72/82/7282f22a0748c711b1964af0315893578b0d32d5.png" style="width: 350.0px;max-width: 100.0%;max-height: 100.0%;"> </center> <i>This is a blog 5 of a series of blogs about algorithmic challenges I came across when creating [tgen](https://codeforces.me/blog/entry/154468).</i> In this blog we will tackle: 1. Generate a skewed connected graph on vertices $[0, n)$ with $m$ edges, in $\mathcal O(n + m \log n)$ time if $\mathrm{spread}$ is $\mathcal O(1)$, and in $\mathcal O(n \log n + m \log^2 n)$ expected time otherwise. In the [previous miniblog](https://codeforces.me/blog/entry/156658) we generated a skewed tree with `wnext`: the parent of $i$ is `wnext(i, e)`. If $e$ is small, this is biased toward $0$ and the tree is star-like; if $e$ is large, it is biased toward $i-1$ and the tree is path-like, with endpoints $0$ and $n-1$. To get a connected graph with $m \ge n-1$ edges, the obvious next step is to add $m-(n-1)$ extra edges uniformly ...
tgen::miniblog(5): random graphs with large diameter, **Proof:** Let $W = \sum_u w[u]$ be the number of candidate chords, and write $k_{\max}(u) = \min, large, it is biased toward $i-1$ and the tree is path-like, with endpoints $0$ and $n-1$. To get a

Полный текст и комментарии »

  • Проголосовать: нравится
  • +92
  • Проголосовать: не нравится

217.
Автор Zlobober, 10 лет назад, По-русски
Codeforces Round #376 (Div. 2) editorial I'm sorry for a delay with publishing the editorial. [problem:731A] -------------- Problem author: [user:egor-belikov,2016-10-17], developer: [user:timgaripov,2016-10-17] In this problem you have to implement exactly what is written in the statement, i. e. you should find minimum number of rotations from letter `a` to the first letter in the input, then to the second one and so on. The only useful knowledge that may simplify the solution is that the distance between points $x$ and $y$ on the circle of length $l$ (26 in our case) is $\min(|x - y|, l - |x - y|)$. This solution works in $O(|s|)$, and, of course, fits in time limit. [problem:731B] -------------- Problem author: olympiad jury, developer: [user:platypus179,2016-10-17] In a correct answer we may guarantee that for any two consecutive days we use no more than one coupon for bying pizzas in these days. Indeed, if we have two coupons for buying pizzas in days $i$ and $i + 1$, replace these coupons for two ...
summation there is a number that is divisible by $x$ and that is no larger than $200\,000$ at the

Полный текст и комментарии »

Разбор задач Codeforces Round 376 (Div. 2)
  • Проголосовать: нравится
  • +63
  • Проголосовать: не нравится

218.
Автор eduardische, 12 лет назад, По-английски
Solving Code Jam Qualification Round. In Excel. So, the qualification round was upon us, and it's a nice way to have some fun. In the past two years I've been writing solutions in multiple languages. In both of them I used Excel for one problem. Without any use of VBA of course, as it would've been too boring. This year I decided to go nuclear and use Excel for everything. I managed to get 100 points. Here are the notes on this glorious experience. [cut] . So, how does this works overall? In Excel you can import data, particularly from text. You can also specify separator, which is usually space, which means the numbers will spread out over the columns. Then you can write formulas to calculate the output row for every test, and if they're presented sequentially in one column, you can easily select them and copy-paste into any text editor. Let's deal with the easiest problem first in terms of implementation in Excel &mdash; D. X is in column A, R is in column B, C is in column C. Use simple formula: ~~~~~ =IF(A2="", "", "...
`$` before column name or row number. For example, `$A$1` will always remain A1, `$A1` will keep the, of M and then we need to divide all the data by that number, meaning that we need 1M numbers for

Полный текст и комментарии »

  • Проголосовать: нравится
  • +421
  • Проголосовать: не нравится

219.
Автор Geothermal, история, 7 лет назад, По-английски
Proposal Regarding Standings for Div. 2 and Div. 3 Rounds As many of you are aware, some users abuse Codeforces' virtual participation feature in order to submit prewritten solutions immediately when the contest starts so as to appear at the top of the contest leaderboards. A few examples are [here](https://codeforces.me/contest/1158/standings), [here](https://codeforces.me/contest/1196/standings), and [here](https://codeforces.me/contest/1141/standings). Of course, preventing cheating by virtual participants is rather difficult, especially because while these three are relatively obvious cases, other forms of dishonest behavior are just as plausible but are harder to detect. For example, someone who looked at the comments on a round's announcement before participating virtually and thus learned that a particularly valuable problem was relatively easy to solve would have an unfair advantage (as they would be able to earn more points by knowing to attempt this problem early into the contest), but one that would be rather difficult to d...
impact a large number of users: for example, 1557 competitors above the 1600 rating cap registered

Полный текст и комментарии »

  • Проголосовать: нравится
  • +141
  • Проголосовать: не нравится

220.
Автор dmkozyrev, история, 8 лет назад, По-русски
[Tutorial] Rolling hash and 8 interesting problems [Editorial] **UPD**: while I was translating this post from Russian to English, [user:dacin21,2018-07-06] wrote his post, more advanced, [link](http://codeforces.me/blog/entry/60442). I hope that my post will help beginners, but in my post more rough estimates. And in Russia we call **rolling hashes** as a **polynomial hashes**. Hello, codeforces! This blogpost is written for all those who want to understand and use polynomial hashes and learn how to apply them in solving various problems. I will briefly write the theoretical material, consider the features of the implementation and consider some problems, among them: 1. Searching all occurrences of one string of length $n$ in another string length $m$ in $O(n + m)$ time 2. Searching for the largest common substring of two strings of lengths $ n $ and $ m $ $(n \ge m) $ in $O((n+m \cdot log(n)) \cdot log(m))$ and $O(n \cdot log(m))$ time 3. Finding the lexicographically minimal cyclic shift of a string of length $ n $ in $ O(n \cdo...
the integer division, sometimes on the border with TLE for large problems, and b) on the codeforces

Полный текст и комментарии »

  • Проголосовать: нравится
  • +239
  • Проголосовать: не нравится

221.
Автор kpw29, 11 лет назад, По-английски
1st Hunger Games Large Editorial — Community solutions This is the second part of Hunger Games Editorial, hope you'll enjoy it :) And again, thanks for stuff for awesome contest, congratz for survivors too! **UPD**: Problems B, D, E, Q, T, W are now available, more soon :) **Editorial Hall of Fame:** [user:Stonefeang,2015-08-26] [user:Andres_Unt,2015-08-26] [user:cuber2460,2015-08-26] [user:Anonym_KALEP,2015-08-26] [user:adamant,2015-08-26] [user:ngoisao_93,2015-08-27] [user:gendelpiekel,2015-08-27] [user:fcdkbear,2015-08-27] [user:izrak,2015-08-27] **Problem A: Good Numbers.** Tutorial by: [user:ngoisao_93,2015-08-28] Call `LCM(i, j)` the lowest common multiple of i and j. First, we should analyse that if x is divisible by `LCM(p^i, q^j)`, then x is divisible by `p^i` and `q^j` at the same time. Call set `s(i, j)` the set of number x in range [l, r] that x is divisible by `LCM(p^i, q^j)`. Call `|s(i, j)|` the size of s(i, j). We can find out that: `|s(i, j)| = |s(1, j)| - |s(1, i-1)| = r/LCM(p^i, q^j...
1st Hunger Games Large Editorial — Community solutions, . answer of this query is needed information for this Guni!($g_i$) so we add thisnumber to second, $, where $L$ is number of values, which X contain. (L can be computed the same time we write DP, Call set `d(i, j)` the set of number x in range [l, r] that x is divisible by `LCM(p^i, q^j)` and, Call set `s(i, j)` the set of number x in range [l, r] that x is divisible by `LCM(p^i, q^j)`. Call, Now we can solve the problem with $DP$ Where $DP[E][S]$=number of ways we can weight tree with sum, The overall complexity is O($n * log(n) * M$), where $M$ is a number of prime powers that are less, We consider a number to be the sum of some powers of two. ($X = 2^i + 2^j + 2^k + ... $)., Where g[i][j][k] = the number of subsequences with bits i, j and k set. We can use the Mobius DP, number. After that we'll have an information in the following form: if the left border of the segment is

Полный текст и комментарии »

  • Проголосовать: нравится
  • +60
  • Проголосовать: не нравится

222.
Автор Edvard, история, 11 лет назад, По-русски
Editorial of Educational Codeforces Round 2 [problem:600A] This is a technical problem. You should do exactly what is written in problem statement. [problem:600B] Let's sort all numbers in a. Now let's iterate over elements of $b$ and for element $b_j$ find the index of lowest number that is greater than $b_j$. We can do that using binary search. That index will be the answer for value $b_j$. Complexity: $O(n logn)$. [problem:600C] Let's denote $cnt_c$ &mdash; the number of occurences of symbol $c$. Let's consider odd values $cnt_c$. Palindrome can not contain more than one symbol $c$ with odd $cnt_c$. Let's denote symbols with odd $cnt_c$ as $a_1, a_2 ... a_k$ (in alphabetical order). Let's replace any one of symbols $a_k$ with symbol $a_1$, $a_{k-1}$ with $a_2$ and so on until the middle of $a$. Now we have no more than one odd symbol. If we have some let's place it in the middle of the answer. First half of answer will contain $\frac{cnt_c}{2}$ occurences of symbol $c$ in alphabetical order. The second half ...
The name of this problem is anagram for ''Small to large''. There is a reason for that :-) The

Полный текст и комментарии »

Разбор задач Educational Codeforces Round 2
  • Проголосовать: нравится
  • +58
  • Проголосовать: не нравится

223.
Автор kpw29, 6 лет назад, По-английски
Meet IT Codeforces Round Editorial Thank you very much for taking part in the contest! <spoiler summary="Contest timeline"> - -0:05. Starting the chat with the Questions Answering team: [user:tnowak,2020-11-15] and our beloved coordinator [user:antontrygubO_o,2020-11-15]. We hope that there won't be that many questions :) - -0:01. One minute to go! I hope that everything goes smoothly. I'm so afraid of posting the editorial accidentally that I moved this timeline into another blog... - 0:01. First blood in Div2! Congratulations to [user:majorro,2020-11-15]!. - 0:03. First blood in Div1 as well! Congratulations to [user:Errichto,2020-11-15], your knapsack is ready for a journey to win! - 0:04. [user:Sho10,2020-11-15] first to solve Div2B. Well done! - 0:05. We also have the first question. So far so good... - 0:06. [user:Um_nik,2020-11-15] gets the first pretests pass in Div1B. The cheaters are caught! - 0:09. [user:bandiaoz,2020-11-15] packs the first Knapsack in Div2! A difficulty spike is coming... - 0:12....
"> We want to minimize the number of negative numbers as much as we can by applying the operations

Полный текст и комментарии »

  • Проголосовать: нравится
  • +515
  • Проголосовать: не нравится

224.
Автор Xellos, история, 11 лет назад, По-английски
Codeforces Round #333 — editorial ### Hints: [div2A](#div2A): Try conversions between bases. [div2B](#div2B): Solve a simpler version of the problem where $A_{i+1} \neq A_i$ for all $i$. [div1A](#div1A): What are the shortest paths of the vehicles? what's the shorter of those paths? [div1B](#div1B): Forget about the ceiling function. Draw points $(i,A[i])$ and lines between them &mdash; what's the Lipschitz constant geometrically? [div1C](#div1C): Some dynamic programming. Definitely not for the exp. score of one person &mdash; look at fixed scores instead. [div1D](#div1D): Compute $dif(v)$ in $O(N)$ (without hashing) and then solve the problem in $O(N^2)$. You need some smart merges. [div1E](#div1E): Can you solve the problem without events of type 1 or 2? Also, how about solving it offline &mdash; as queries on subsets. ![ ](https://i.imgur.com/bnWmD60.png) ### <a name="div2A"></a>Div. 2 A: Two Bases ------------------------------------ It's easy to compare two numbers if the same bas...
currently processed number. One option would be remembering the last position of each integer

Полный текст и комментарии »

Разбор задач Codeforces Round 333 (Div. 1)
Разбор задач Codeforces Round 333 (Div. 2)
  • Проголосовать: нравится
  • +490
  • Проголосовать: не нравится

225.
Автор lucifer1004, история, 6 лет назад, По-английски
Unofficial Editorial for Educational Codeforces Round 97 [中文题解](https://cp-wiki.vercel.app/tutorial/codeforces/1437/) ### [problem:1437A] <spoiler summary="Hint"> What will happen if $r\geq2l$? </spoiler> <spoiler summary="Solution"> Suppose that $r\geq2l$, then at least we need to cover $[l,2l]$. Obviously, we must have $a>l$, since the length of the segment is already longer than $l$. Now if $l<a\leq2l$, there are at most $l$ modules of $a$ which are no less than $\frac{a}{2}$, which cannot cover the segment whose length is $l+1$. But if $a>2l$, then $l$ cannot be a good value. On the contrary, if $r<2l$, we can always choose $a=2l$ which will be a valid answer. So this problem can be simplified to judging whether $r<2l$ holds. Time complexity is $O(1)$. </spoiler> <spoiler summary="Code (Python 3)"> ~~~~~ def read_int(): return int(input()) def read_ints(): return map(int, input().split(' ')) t = read_int() for case_num in range(t): l, r = read_ints() print('YES' if l * 2 > r els...
index that can be included in the set when the largest number is $a[i]$ (after sorting)., of the second-largest number? , $, then the current second-largest number $second$ must follow $2second, After that, we will do dynamic programming, where $dp[i]$ means the number of valid permutations

Полный текст и комментарии »

  • Проголосовать: нравится
  • +147
  • Проголосовать: не нравится

226.
Автор thanhchauns2, история, 4 года назад, По-английски
Some short snippets that will shorten your time. Hi there! ================== In this blog I would like to share some of the code snippets that can shorten your time in future contests. Of course, I'll ignore the "international snippets" <spoiler summary="like:"> ~~~~~ #define SZ(a) (ll)a.size() #define FOR(i,a,b) for (ll i=(ll)a; i<=(ll)b; i++) #define f first #define mp make_pair #define s second #define p pair #define all(C) C.begin(), C.end() ~~~~~ </spoiler> Sometimes you may find typing the identical thing again and again is boring, this blog is about some method that a few people use to get rid of them (or just only me). So, let's get started. #### Scanning/printing the whole vector in a single `std::cin/std::cout` <spoiler summary="Snippet"> ~~~~~ template<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;}; template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {for(auto &x : a) out << x << ' '; return out;}; ~~~~~ </spoiler> ...
#### Prime test for large numbers, // Prime test for large numbers

Полный текст и комментарии »

  • Проголосовать: нравится
  • +37
  • Проголосовать: не нравится

227.
Автор WorldWarV, история, 2 месяца назад, По-английски
Codeforces Round 1122 (Div. 3) Editorial Thanks for participating in [contest:2266]! <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2266A] <spoiler summary="Hint"> How many participants can possibly have solved all three problems? </spoiler> <spoiler summary="Solution"> At most $\min(a_1,a_2,a_3)$ participants could have solved all three problems. This is achievable by making the same $\min(a_1,a_2,a_3)$ participants solve every problem, then distributing the remaining solves arbitrarily. Thus, the answer is $n-\min(a_1,a_2,a_3)$. ...
Process the values from large to small, and let $q$ be the number of copies of the current value, number of elements to avoid overflow.

Полный текст и комментарии »

Разбор задач Codeforces Round 1122 (Div. 3)
  • Проголосовать: нравится
  • +98
  • Проголосовать: не нравится

228.
Автор T1duS, история, 5 лет назад, По-английски
IOI Training for Indian Aspirants (UFDS Mentoring 2022) Hey all! We hope you're doing well. Like last year, we're again looking to give back a little to the competitive programming community, in the form of mentorship. This mentorship is **completely free**. We're hoping to help aspiring competitive programmers do well at the [ZCO, INOI and IOITC](https://www.iarcs.org.in/inoi/), and hopefully even [represent India at the IOI](https://stats.ioinformatics.org/results/IND)! We're setting up another Discord server, to mentor people trying out for the ZCO, INOI and IOITC. Last year, we had 16 people from our server qualify for IOITC. This time, there's a larger limit on the total number of people we can take, as we have many more mentors. However, we're trying to focus more on olympiad preparation this year. You're still welcome to apply if you think you'd benefit from Olympiad training but are ineligible for INOI. We're also in the process of developing a resource similar to the USACO Guide, in order to help us organise our teaching ...
the total number of people we can take, as we have many more mentors. However, we're trying to focus

Полный текст и комментарии »

  • Проголосовать: нравится
  • +215
  • Проголосовать: не нравится

229.
Автор Gheal, 4 года назад, По-английски
Codeforces Round #875 (Div.1 + Div. 2) Editorial [1831A &mdash; Twin Permutations](https://codeforces.me/contest/1831/problem/A) ------------------ Author: [user:Gheal,2023-05-25] <spoiler summary="Hints"> <spoiler summary="Hint 1"> If $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. </spoiler> <spoiler summary="Hint 2"> Building on the idea from the first hint, can we build a permutation $b$ such that $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$? </spoiler> </spoiler> <spoiler summary="Solution"> Since $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Therefore, any permutation $b$ which satisfies $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$ is a valid answer. If $b_i=n+1-a_i$, then: 1. $b$ is a permutation; 2. $a_1+b_1=a_2+b_2=\ldots=a_n+b_n=n+1$ Consequently, $b=[n+1-a_1,n+1-a_2,\ldots,n+1-a_i,\ldots,n+1-a_n]$ is a valid answer. Time complexity per test case : $O(N)$ </spoiler> <spoiler summary="Code (Gheal, C++)"> ~~~~~ #include<bits/stdc++.h>...
number of ranges where point $i$ is the largest coordinate within it are the ranges $[l,r]$ which

Полный текст и комментарии »

Разбор задач Codeforces Round 875 (Div. 1)
Разбор задач Codeforces Round 875 (Div. 2)
  • Проголосовать: нравится
  • +153
  • Проголосовать: не нравится

230.
Автор wangmarui, история, 11 месяцев назад, По-английски
Hello 2026 Editorial We'd like to thank you all for participating in the contest, and hope you enjoyed it. Any feedback would be appreciated! <spoiler summary="Rate The Contest!"> - Great contest - Good contest - Average contest - Bad contest </spoiler> ## [2183A &mdash; Binary Array Game](https://codeforces.me/contest/2183/problem/A) Idea & Preparation: [user:wangmarui,2025-12-23] <spoiler summary="Rate The Problem!"> - Good Problem - Okay Problem - Bad Problem - Didn't Solve </spoiler> <spoiler summary="Hint 1"> If the sequence $a$ consists entirely of $1$ s, what will Alice do? </spoiler> <spoiler summary="Hint 2"> Consider discussing the values of $a_1$ and $a_n$. </spoiler> <spoiler summary="Solution"> First, if the entire sequence consists of $1$ s, Alice wins immediately by operating on the whole sequen...
the minimum of $\text{cost}-\mu\cdot(\text{number of blocks})$ over partitions with cuts in

Полный текст и комментарии »

Разбор задач Hello 2026
  • Проголосовать: нравится
  • +146
  • Проголосовать: не нравится

231.
Автор Xellos, 13 лет назад, По-английски
Samara SAU ACM ICPC 2013-2014 Quarterfinal Qualification Contest: Editorial ### A. The Power of the Dark Side (difficulty: easy) Let's sort the parameters of every Jedi: $a \ge b \ge c$. The "coverted" Jedi obviously wants to use his strongest 2 parameters ($a_k,b_k$) against the opponent's weakest 2 ($b_i,c_i$) to get 2 victories as assuredly as possible; besides, the optimal order is $a_k$ against $b_i$ and $b_k$ against $c_i$, because if he can win when using them in the opposite order, then he'll win after swapping them, too. So we want to find all Jedis that have $a_k > b_i$ and $b_k > c_i$ for all $i$. That's simple, because those are the same conditions as $a_k > B=\max(b_i)$ and $b_k > C=\max(c_i)$. When processing the input, we can count $B$, $C$ and then we just check for every Jedi if he satisfies these 2 conditions, in linear time. I decided during the contest to code a solution which is a bit slower, but more powerful &mdash; it allows us to answer stronger versions of this problem like "which Jedis can we choose, if we're satisfied with...
The ideal approach to this problem is binary search, because if some number of hits is sufficient

Полный текст и комментарии »

  • Проголосовать: нравится
  • +37
  • Проголосовать: не нравится

232.
Автор HellKitsune, история, 10 лет назад, По-русски
Educational Codeforces Round 17 Editorial <spoiler summary="Task A"> If you find all the small divisors of n that are less than sqrt(n), you can find the rest of them dividing n by the small ones. By the way, this problem is widely known and googlable :) You can, for example, check out this link: http://stackoverflow.com/questions/26753839/efficiently-getting-all-divisors-of-a-given-number </spoiler> <spoiler summary="Task B"> Try coming up either with greedy algorithm or with two pointers algorithm. <spoiler summary=""> Try to prove the following greedy: in each step we can choose the cheapest remaining mouse. If there is a computer left that has only one type of port suitable for this mouse, plug it there. Else if there is a computer with both types, plug it there. Else discard this mouse. Try to also come up with the two pointers solution. If you cannot, it is described under the next spoiler. <spoiler summary=""> Sort all of the USB mouses and all of the PS/2 mouses so that the price is non-descending. ...
the number of stations that match the currently processed station from the $left$ vector?

Полный текст и комментарии »

Разбор задач Educational Codeforces Round 17
  • Проголосовать: нравится
  • +196
  • Проголосовать: не нравится

233.
Автор Geothermal, история, 7 лет назад, По-английски
AtCoder Beginner Contest 151 English Solutions #A &mdash; Next Alphabet The easiest way to deal with this problem is probably to convert the given character to an integer, add one, and convert it back. If you absolutely can't do that, a somewhat more annoying implementation would involve iterating through the alphabet, waiting until you find the given letter, using a boolean variable to store that the letter has been found, and printing the letter on the next iteration of the loop. (However, iterating over the alphabet is itself nasty unless you have conversion from letters to integers, so this approach is rather pointless unless your language just doesn't support the first method, though in that case you should probably switch languages anyway.) Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc151/submissions/9440245) --- #B &mdash; Achieve the Goal In total, we need to earn $NM$ points. We subtract the points earned so far and determine whether this is a valid score for the final ...
). Note that the number of sets in which $A_i$ is the largest value is the number of ways to choose $K-1, We will separately count the number of times each element appears as the minimum and the maximum in

Полный текст и комментарии »

  • Проголосовать: нравится
  • +40
  • Проголосовать: не нравится

234.
Автор cry, 15 месяцев назад, По-английски
Codeforces Round 1050 (Div. 4) Editorial #### [problem:2148A] <spoiler summary="Solution (written by cry)"> Notice that if we pair each odd-indexed element with an even-indexed element, it sums to $0$. Therefore, our strategy is to pair the $2i$'th element with the $(2i+1)$th element until there are no more elements to pair. Note that if $n$ is odd, then there exists an unpaired odd element at the end. In this case, the answer will just be that ending element, which will be $x$. Otherwise, when $n$ is even, we paired every element perfectly and the sum will be $0$. Time complexity: $\mathcal{O}(1)$ per test case. </spoiler> <spoiler summary="Code (C++) (MikeMirzayanov)"> ```cpp #include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int x, n; cin >> x >> n; if (n % 2 == 0) cout << 0; else cout << x; cout << endl; } } ``` </...
To handle this, let’s think in terms of divisors. For each number $a_i$, compute all of its

Полный текст и комментарии »

Разбор задач Codeforces Round 1050 (Div. 4)
  • Проголосовать: нравится
  • +74
  • Проголосовать: не нравится

235.
Автор kpw29, 5 лет назад, По-английски
[ICPC blog series #0] My last ACM experience Disclaimer ================== This isn't really a first tutorial in the series. If you are interested in reading what participating in ICPC World Finals feels like, you can enjoy my <s>pathetic</s> behind-the-scenes story of the Cambridge silver-medal performance in WF2020. I tried to write a spoiler--free blog so that it contains minimum information about the problems. Motivation ================== In 2016 I have written a blogpost [My first ACM experience](https://codeforces.me/blog/entry/48082). It made sense to me to also close some chapter of the book by writing up about how my last serious contest went. I advise not to take the blog too seriously, it is just an honest stream of consciousness (some facts may not even be 100% accurate, though I will fix things people point me). Feel free to comment, praise, <s>or hate</s>. For a different perspective, check out [user:IBaloff,2021-10-07]'s [blog](https://codeforces.cc/blog/entry/95526). The hero and heroine of the story o...
not remove the RTE verdict. Bomb number two! Was she playing a game of bomberman today? In the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +348
  • Проголосовать: не нравится

236.
Автор YouKn0wWho, 5 лет назад, По-английски
Editorial of Codeforces Round #735 (Div. 2) The problem names are based on my favorite characters out there. Yes, [problem:1554E] are my most favorite character UwU. I have tried to make the editorials as interactive as possible. Enjoy. [tutorial:1554A] <spoiler summary="Code(C++)"> ~~~~~ #include<bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto &x: a) { cin >> x; } long long ans = 0; for (int i = 1; i < n; i++) { ans = max(ans, 1LL * a[i] * a[i - 1]); } cout << ans << '\n'; } return 0; } ~~~~~ </spoiler> <spoiler summary="Code(Python)"> ~~~~~ import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): ans = max(ans, a[i] * a[i + 1]) print(ans) ~~~~~ </spoiler> [tutorial:1554B] <sp...
) { // number of times i-th node occurs in the string if (dp[i] != -1) return dp[i]; int ret

Полный текст и комментарии »

Разбор задач Codeforces Round 735 (Div. 2)
  • Проголосовать: нравится
  • +328
  • Проголосовать: не нравится

237.
Автор MathModel, история, 13 месяцев назад, По-английски
Codeforces Round 1061 (Div. 2) Editorial ### Thank you for participating ! Special Thanks to [user:hxu10,2025-10-24] for giving me the chance to write the editorial and for [user:maomao90,2025-10-24] for enhancing the editorial !. Editorial of Problems E and F are written by hxu10, and the rest are written by me. I hope they're insightful and concise, please let me hear your opinion about it or any feedback in general &#128153;. #### [problem:2156A] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Since $m_1 \le m_2$, the total number of slices Alice ate is always at least as much as the total number of slices Bob ate. What's optimal construction ? </spoiler> <spoiler summary="Hint 2"> We want to try to minimize the difference between the total number of slices Alice ate and the total number of slices Bob ate. </spoiler> <spoiler summary="Hint 3"> The optimal construction is to let both $m_1$ and $m_2$ to be equals to one. The sequence of operations, denoted by $(m_1, m...
feasible** position ensures the smallest possible number at that index. Any alternative that puts

Полный текст и комментарии »

Разбор задач Codeforces Round 1061 (Div. 2)
  • Проголосовать: нравится
  • +159
  • Проголосовать: не нравится

238.
Автор flamestorm, 5 лет назад, По-английски
EZ Programming Contest #1 Editorial Thank you for competing! I hope you had fun in the contest. **UPD:** Implementations have been added. [problem:103150A] <spoiler summary="Short Solution"> The value of $k$ is irrelevant, just output the answer when zero operations are performed. </spoiler> <spoiler summary="Editorial"> If we perform $0$ operations on the array, then the answer is just $\max{(a_i)} - \min{(a_i)}$ (maximum element of $a$ minus minimum element of $a$). Call this value $r$. Now we claim that, no matter how many operations are performed on the array, the answer will always be $r$. Let's prove it. Let $s$ be the sum of the elements of the array. Then the operation is equivalent to turning $a_i$ into $s - a_i$ for all $i$. In particular, let $a_p$ be the maximum element and $a_q$ be the minimum element of $a$. Then after the operation, $a_p$ becomes $s - a_p$ and $a_q$ becomes $s - a_q$. It's easy to see that $s - a_p$ will be the smallest number of the resulting array, and $s - a_q$ will be...
Here is a rough idea: for large $n$, the smallest number we can make, To do this, we can greedily choose the largest triangular number less than $n$. It can be checked

Полный текст и комментарии »

Разбор задач EZ Programming Contest #1
  • Проголосовать: нравится
  • +100
  • Проголосовать: не нравится

239.
Автор djm03178, 23 месяца назад, По-английски
Explanation on the set/map hack for 2044F Problem: [problem:2044F] I initially wrote this [here](https://codeforces.me/blog/entry/137306?#comment-1228128), but it has gotten too long and it's hard to find within so many comments, and I see many people are wondering what exactly happened there. So, I'm re-writing all things in a single blog again. If you got time limit exceeded on test 25 or later, then you're caught by one of these hacks. ### What did the hack aim for? The editorial says a `map` (or a `set`, as they're basically the same) solution was intended to pass and no further optimization is needed. Unfortunately, it turns out that the tests weren't strong enough to actually evaluate its performance on the worst case. Let $SumA$ be the sum of elements of array $a$, and $SumB$ be the sum of elements of array $b$ (as stated in the editorial). Let's also say $SA$ is the set of $SumA-a_i$s and $SB$ is the set of $SumB-b_i$s. The most basic way to implement this solution is for each $i \cdot j = x$ ($1 \le i \l...
Therefore, my idea was to query the number with most number of divisors, while letting $i$, $j

Полный текст и комментарии »

  • Проголосовать: нравится
  • +74
  • Проголосовать: не нравится

240.
Автор BledDest, история, 6 лет назад, По-английски
Kotlin Heroes: Episode 6 — Editorial First of all, I would like to thank all testers of the round: [user:Um_nik,2021-03-09], [user:IlyaLos,2021-03-09], [user:Roms,2021-03-09], [user:nuipojaluista,2021-03-09], [user:Supermagzzz,2021-03-09], [user:Stepavly,2021-03-09], [user:hg333,2021-03-09]. Also huge thanks to co-authors of the contest: [user:Ne0n25,2020-11-12], [user:adedalic,2020-11-12], [user:vovuh,2020-11-12] and [user:pikmike,2020-11-12]. I hope you enjoyed participating in the round! Okay, now for the editorial itself: [problem:1488A] Idea: [user:BledDest,2021-03-09], preparation: [user:Neon,2021-03-09] <spoiler summary="Tutorial"> [tutorial:1488A] </spoiler> [problem:1488B] Idea: [user:BledDest,2021-03-09], preparation: [user:BledDest,2021-03-09] <spoiler summary="Tutorial"> [tutorial:1488B] </spoiler> [problem:1488C] Idea: [user:vovuh,2021-03-09], preparation: [user:vovuh,2021-03-09] <spoiler summary="Tutorial"> [tutorial:1488C] </spoiler> [problem:1488D] Idea: [us...
the smallest total number of problems such that there exists a distribution. Since that value is, Now it would be great if the function that tells if some $x$ can be the number of problems during

Полный текст и комментарии »

Разбор задач Kotlin Heroes: Episode 6
  • Проголосовать: нравится
  • +63
  • Проголосовать: не нравится

241.
Автор physics0523, история, 3 года назад, По-английски
TheForces Round #27 Editorial [problem:104855A] <spoiler summary="Editorial"> First,it's not hard to come up with query `? 1`.Assume we have got $t$,the answer is either $2t$ or $2t-1$. Then we can query `? 2t`.It can be proven the answer of `? 2t` is always different from `? 2t-1`. Another approach:query `? 2` or `? 2m-1`.Although it doesn't work in some small cases,you can do another query to avoid conflict. </spoiler> <spoiler summary="Rate the problem"> Good problem! : Average problem : Bad problem... : </spoiler> [problem:104855B] <spoiler summary="Editorial"> Every time choosing adjacent cell to blue cell is optimal because it can stop the growth of blue cell in that particular direction, so obviously if $k>=4$ we can surround the blue cell so answer will be $nm-1$. For $k=1$ we will take the portion (up side, down side, left side, right side) of cells to initial blue cell containing maximum white cells, similarly for $k=...
Let's solve this problem starting from the box which has the smallest number of salmons, until the

Полный текст и комментарии »

Разбор задач TheForces Round #27(3^3-Forces)
  • Проголосовать: нравится
  • +16
  • Проголосовать: не нравится

242.
Автор _Seele_Vollerei_, история, 4 месяца назад, По-английски
Report: Contest-Time Solution Hints Linked to NotOnlySuccess I am writing this blog to report a competitive-integrity issue involving the Codeforces user [user:NotOnlySuccess,2026-08-09] and a website associated with their content. The main issue is simple: **problem-specific solution material and hints for an ongoing Codeforces contest were made available before the contest ended.** # 1. Solution material published before the contest ended During [Codeforces Round 1116 (Div. 1, Div. 2)](https://codeforces.me/blog/entry/155668), an article titled [CF Round 1116 (Div. 1+2)](https://mp.weixin.qq.com/s/P3QJqmQFRsLlW9GX_y_8YQ) was published on a WeChat public account at August 10, 2026, 00:37 (UTC +8). The Codeforces contest ended at August 10, 2026, 01:05 (UTC +8). Therefore, the article was publicly available **28 minutes before the contest ended**. ![ ](/predownloaded/e5/8e/e58ea523bd7a61b7bdd20d83d2d16a0672f1cca0.png) The article already contained problem-specific solution material. For readers who do not understand Chinese...
> **Greedy** > > - In one operation, one number is replaced by the sum of the other two numbers

Полный текст и комментарии »

  • Проголосовать: нравится
  • +282
  • Проголосовать: не нравится

243.
Автор flaviu2001, история, 6 лет назад, По-английски
Codeforces Round #676 (Div. 2) Editorial **[1421A &mdash; XORwice](https://codeforces.me/contest/1421/problem/A)** Idea and solution: [user:flaviu2001,2020-10-17] <spoiler summary="Hint"> Think about addition in base two. Say $a$ = $10101$ and $b$ = $1001$. What your operation does is it modifies the bits in your numbers, so if the first bit in $a$ is $1$ and the first bit in $b$ is $1$ (as is the case above) you can make both $0$ by making that bit $1$ in $x$. This is actually the only way you can decrease the resulting sum, so $x$ = $1$ is an answer above. </spoiler> <spoiler summary="Solution"> Noticing the hint above we now deduce $x$ = $a$ & $b$ where & is bitwise $AND$. So just printing ($a$ $\oplus$ ($a$ & $b$)) + ($b$ $\oplus$ ($a$ & $b$)) works, but there's an even nicer formula. We'll leave it up to you to prove that ($a$ $\oplus$ ($a$ & $b$)) + ($b$ $\oplus$ ($a$ & $b$)) = $a$ $\oplus$ $b$, where $\oplus$ is the bitwise $XOR$ :) </spoiler> **[1421B &mdash; Putting Bricks in the Wall](https://code...

Полный текст и комментарии »

Разбор задач Codeforces Round 676 (Div. 2)
  • Проголосовать: нравится
  • +158
  • Проголосовать: не нравится

244.
Автор izban, 13 лет назад, По-русски
Codeforces Round #239 Editorial Sorry for my poor English. If you find a mistake, write me a private message, I'll fix it. Some problems have not been translated yet, now you can try to read the Russian version of editorial with Google Translate. [problem:408A] In this problem you were to find waiting the time for every queue by summing up the purchases of all the people, and return the minimum. [problem:408B] In this problem it is necessary to find the garland with the maximal length, which can be composed of elements that we have. <br/> First, if you need some color, but you don't have it, then the answer is -1 <br/> Otherwise, answer is always exists. <br/> Let's sum the answers for all the colors separately. <br/> Suppose we have $a$ pieces of a garland of some color, and we need $b$ pieces. Then we have to add $min(a, b)$ to the answer: if $a >= b$ we will use $b$ 1 meter pieces, in the other case if $a < b$ we will use all $a$ pieces. [problem:407A] In this problem you have to locate the r...

Полный текст и комментарии »

Разбор задач Codeforces Round 239 (Div. 1)
Разбор задач Codeforces Round 239 (Div. 2)
  • Проголосовать: нравится
  • +56
  • Проголосовать: не нравится

245.
Автор Sereja, 13 лет назад, По-русски
Codeforces Round #223 — Tutorial ### [problem:381A] Simply do the process described in the statment. ### [problem:381B] Calculate the amount of each number. For all the different numbers &mdash; maximum possible times of use isn't more than 2 times. For the maximum is is only &mdash; 1. ### [problem:380A] Generate the first number 100000. Will in turn handle the requests, if the request gets to the point of adding one number, just print it. Otherwise see what element will meet our and just print it from precalculated array. ### [problem:380B] Lets generate a tree as described in the statment. For each request to add items we just add a segment for a certain level. At the request of the number of items we just go through all the lower levels, considering the leftmost and the rightmost vertex in the subtree. To each level will take all intervals that it owns and for each check &mdash; whether it intersects with the interval that we have generated in the current stage. If so, simply add items ...
What to know such information is sufficient to find 60 numbers large jobs left and right. This can

Полный текст и комментарии »

Разбор задач Codeforces Round 223 (Div. 1)
Разбор задач Codeforces Round 223 (Div. 2)
  • Проголосовать: нравится
  • +30
  • Проголосовать: не нравится

246.
Автор physics0523, история, 4 года назад, По-английски
Strange Comparison: vector&lt;vector&lt;int&gt;&gt; vs vector&lt;pair&lt;int,int&gt;&gt; ? If we want to use a 2D dynamic array, some C++ user writes following 2D vector: ``` vector<vector<int>> a(n); // add y to a[x] a[x].push_back(y); // walkthrough a[x] for(auto &nx : a[x]){ cout << nx << "\n"; } ``` But we can do the equivalent thing with handwritten linked list (when we know the total size) by using 1D vector<pair<int,int>>: ``` pair<int,int> empty={-1,-1}; vector<pair<int,int>> b(n+total_size,empty); int add_point=n; // add y to b[x] if(b[x]!=empty){ b[add_point]=b[x]; b[x].second=add_point; add_point++; } b[x].first=y; // walkthrough b[x] int current=x; while(current!=empty.second && b[currnt]!=empty){ cout << b[current].first << "\n"; current=b[current].second; } ``` So, what's the benefit for the later implementation? The merit is the generation time of later one is very fast. vector size = $10^5$, Total elements = $10^6$ (this means we need `vector<vector<int>>(1e5)` and the sum of the size of $10^5$ vect...
So, when the vector size is large and need small number of walkthrough, the `vector

Полный текст и комментарии »

  • Проголосовать: нравится
  • +67
  • Проголосовать: не нравится

247.
Автор nifeshe, 22 месяца назад, По-английски
Codeforces Round #997 (Div. 2) Editorial <spoiler summary = "Rating predictions"> | | A | B | C | D | E | F1 | F2 | |----------------------|------|-----------|---------|------|------|------|---------------| | [user:nifeshe,2025-01-17] | 800 | 1200 | 1400 | 2000 | 2200 | 2700 | 2800 | | [user:Intellegent,2025-01-17] | 800 | 1200 | 1600 | 2000 | 2300 | | | | [user:mwen,2025-01-17] | 800 | 1200 | 1300 | 1800 | 2300 | | | | [user:Markadiusz,2025-01-17] | 800 | 1100 | 1300 | 1800 | 2300 | 2500 | 2800 | | [user:_istil,2025-01-17] | 800 | | [1600, 2000] | 2000 | | 2400 | 2700 | | [user:hazzlek,2025-01-17] | 1000 | 1200 | 1500 | 2000 | 2100 | | | | [user:iLoveIOI,2025-01-17] | 800 | 1100 | 1600 | 2000 | 2400 | | | | [user:A_G,2025-01-17] | 800 | 1100 ...
So let's fix $p$ as the number of non-zero elements in $\text{cnt}$ and $x$ as the median. Denote

Полный текст и комментарии »

Разбор задач Codeforces Round 997 (Div. 2)
  • Проголосовать: нравится
  • +96
  • Проголосовать: не нравится

248.
Автор NemanjaSo2005, 3 года назад, По-английски
Codeforces Round 911 (Div. 2) Editorial [problem:1900A] Author: [user:NemanjaSo2005,2023-11-26] <spoiler summary="Hint 1"> Assume that cells $i-1$, $i$, and $i+1$ are covered in water. What happens if you remove water from cell $i$? </spoiler> <spoiler summary="Hint 2"> The water at position $i$ is replaced as both cells $i-1$ and $i+1$ have water in them. </spoiler> <spoiler summary="Solution"> Read the hints. If there are 3 consecutive empty cells $i-1$, $i$, $i+1$, we can place water in cells $i-1$ and $i+1$ and then move water from cell $i$ to all other cells. If there are no such cells, we have to place water on every empty cell. So if we find substring ''...'' in the array, the answer is $2$, otherwise the answer is the number of empty cells. Time and memory complexities are $O(N)$. </spoiler> <spoiler summary="Bonus"> Solve the problem if it is required that each cell is filled with water, or next to at least $1$ cell that is filled with water. </spoiler> [problem:1900B] ...
To find the number of triples that have a gcd value that is an integer multiple of $d$, we can do

Полный текст и комментарии »

Разбор задач Codeforces Round 911 (Div. 2)
  • Проголосовать: нравится
  • +103
  • Проголосовать: не нравится

249.
Автор KADR, 15 лет назад, По-русски
Codeforces Beta Round #97: editorial <p>Here is the editorial of Codeforces Beta Round #97. If you have any questions or suggestions --- feel free to post them in the comments.</p><h3>[[problem:136A]] (A Div 2)</h3><div><br /></div><div>In this problem one had to read a permutation and output the inverse permutation to it. It can be found with the following algorithm. When reading the <i>i</i>-th number, which is equal to <i>a</i> one can store <i>i</i> into the <i>a</i>-th element of the resulting array. The only thing left is to output this array.</div><div><br /></div><div>The complexity is $O(N)$.</div><div>[cut]</div><div><h3>[[problem:136B]] (B Div 2)</h3></div><div><br /></div><div>It is easy to see that the answer is always unique. Let's consider an operation which is opposite to <i>tor</i>. From each ternary digit of <i>c</i> we will subtract a corresponding digit of <i>a</i> and take a result modulo 3. We'll obtain a number <i>b </i>which has the following property: <i>a tor b = c</i>.</div><div><br /></div><div...
If the largest number in our array is equal to 1 then let's replace it with 2, otherwise let's

Полный текст и комментарии »

Разбор задач Codeforces Beta Round 97 (Div. 1)
Разбор задач Codeforces Beta Round 97 (Div. 2)
  • Проголосовать: нравится
  • +87
  • Проголосовать: не нравится

250.
Автор PersistentLife, история, 3 месяца назад, По-английски
Competitive Programming Training: Curated Problem Set #1 [1200–2600, with Editorials] **UPD: Curated problem set 1 (both normal and advanced) for subscribers is ready! Feel free to join our Discord server and subscribe!** A few days ago, I published a blog post on Codeforces about how to train for competitive programming: [Link](https://codeforces.me/blog/entry/156161) In that post, I mentioned that I planned to regularly publish recommended training problems. Now, here they are! Please join our Discord server to receive the latest updates: https://discord.gg/DsHSfmVgG ### Problem Set Overview Each release will include $5$ problems and their editorials. After converting the difficulty of every problem into a Codeforces rating, the problems will be distributed approximately uniformly across the range $[1200,2600]$. The problems will be selected from relatively obscure problem series that are not suitable for being worked through indiscriminately from beginning to end. For this reason, some problem statements may not be available in English; you can use...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +132
  • Проголосовать: не нравится

251.
Автор macaquedev, 8 месяцев назад, По-английски
Codeforces Round 1090 (Div. 4) Editorial I hope you all enjoyed the contest! Special thanks to: - [user:damamila,2026-04-05], for creating problem G - [user:chromate00,2026-04-05], [user:AG-88301,2026-04-05], [user:simplelife,2026-04-05], [user:SpyrosAliv,2026-04-05], [user:reirugan,2026-04-05] and [user:damamila,2026-04-05] for editorials for B-G respectively. - [user:cry,2026-04-05], for helping answer clarifications. <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> #### [A &mdash; The 67th Integer Problem](https://codeforces.me/contest/2218/problem/A) ...
Therefore, if the number of vertices with an even subtree size is larger than thenumber of

Полный текст и комментарии »

Разбор задач Codeforces Round 1090 (Div. 4)
  • Проголосовать: нравится
  • +55
  • Проголосовать: не нравится

252.
Автор flash_7, история, 9 лет назад, По-английски
Digit DP Wrote this article a long ago but during solving a problem recently thought of sharing this article publicly. Hope it will help some contestants to understand the idea clearly. Digit dp is a very easy technique and also useful to solve many dynamic programming problems. Seeing the name “Digit DP” it’s easy to guess that we are going to do something using the digits. Yes we are actually going to play with digits. Let’s explain the concept using a classical problem. #### Problem How many numbers **x** are there in the range **a** to **b**, where the digit **d** occurs exactly **k** times in **x**? There may have several solutions including number theory or combinatorics, but let’s see how we can solve this problem using digit dp. #### Solve for range (zero to a) Using digit dp we always focus on building a number satisfying all the conditions. If we finally manage to build that number then we say, yes we have got one ;-) But how we’ll build that number? For the time being let...
digit greater than b[pos]. Because then the number will become larger than **b**.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +123
  • Проголосовать: не нравится

253.
Автор ecnerwala, история, 6 лет назад, По-английски
Alternative approach to CF #718 H - Hack me please! I had a different approach to H that results in very short, but incorrect code ([submission:114044595], [submission:114044982]). I also have a few versions which I don't know how to hack ([submission:114142853], [submission:114141339], [submission:114141392]). Can anyone hack these or prove they're correct? The main idea is to use strong LP duality: the problem is unsatisfiable if and only if there is some linear combination of the input constraints such that all variables cancel and the constants give a contradiction (e.g. $0 \le -1$). We can try to simplify this by only checking all "extremal" feasible linear combinations, i.e. linear combinations on the convex hull of all linear combinations whose variables completely cancel. Here, I came up with the (false) hypothesis that any such extremal linear combination must include 2 "neighboring" constraints which we can treat as a relaxation, e.g. we use both $y_{i-1}^+$ and $z_{i}^+$; these can be "merged" into a (possibly tighter)...
extremal negative cycle, multiply it by a large number, and add any positive cycle including the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +114
  • Проголосовать: не нравится

254.
Автор ItsNotMeItsYou, 3 месяца назад, По-английски
Codeforces Round 1118 (Div. 2) Editorial Sorry for underestimating the difficulties of the problems, especially B2 and D. We tried to serve as many cool problems as we could. And apparently, this led to some difficult ones. Thank you for participating in the round. We all hope you enjoyed all of our problems. [problem:2258A] Idea: [user:ItsNotMeItsYou,2026-08-29], [user:mychecksdead,2026-08-29] <spoiler summary="Hint1"> Think of the case $n=3$. Can you remove the first or the last number in any way? </spoiler> <spoiler summary="Solution"> We cannot obtain a number larger than $\gcd(a_1,a_n)$ because the first and last numbers in the array can't be removed. We can remove all other elements by choosing $[1, i, n]$, so the answer is $\gcd(a_1, a_n)$. </spoiler> <spoiler summary="Code"> [submission:388911115] </spoiler> <spoiler summary="Rate the problem"> Amazing Good Ok Bad Terrible </spoiler> [probl...
We cannot obtain a number larger than $\gcd(a_1,a_n)$ because the

Полный текст и комментарии »

Разбор задач Codeforces Round 1118 (Div. 2)
  • Проголосовать: нравится
  • +44
  • Проголосовать: не нравится

255.
Автор Endagorion, 15 лет назад, По-русски
Codeforces Round #109: editorial [problem:155A] You should do what is written: go through the sequence and count the elements which are greater or less than all of its predecessors. We don't even have to store the whole sequence, just the current minimum and maximum. Complexity --- O(N), but squared still works fine. [problem:155B] Clearly, we can play the cards with $b_i$ > 0 first as each of them gives at least one extra move. After that, the number of extra moves left doesn't depend on the order of playing. The left cards all have $b_i$ = 0, so we play those of them which have larger $a_i$. Simpler version of this solution: sort all the cards by decrease of $b_i$, if equal --- by decrease of $a_i$, and then go through the sorted array from beginning to end, simulate the counter and sum up the points. Remember not to fall over the edge of array if the sum of $b_i$'s is larger than the number of cards. Complexity --- O(n log n) (or O(n^2), if using bubblesort, which is still accepted). [problem:155C] ...
on every iteration we perform the constant number of operations with the queue of size at most n., . After that, the number of extra moves left doesn't depend on the order of playing. The left cards

Полный текст и комментарии »

Разбор задач Codeforces Round 109 (Div. 1)
Разбор задач Codeforces Round 109 (Div. 2)
  • Проголосовать: нравится
  • +43
  • Проголосовать: не нравится

256.
Автор n0sk1ll, 4 года назад, По-английски
Editorial for Hello 2023 ## [problem:1779A] Author: [user:n0sk1ll,2022-12-27] <spoiler summary="Hint"> What happens when $\texttt{L}$ appears after some $\texttt{R}$ in the string? </spoiler> <spoiler summary="Solution"> Suppose that there exists an index $i$ such that $s_i = \texttt{R}$ and $s_{i+1} = \texttt{L}$. Lamp $i$ illuminates trophies $i+1,i+2,\ldots n$ and lamp $i+1$ illuminates $1,2,\ldots i$. We can conclude that all trophies are illuminated if $\texttt{L}$ appears right after some $\texttt{R}$. So, strings $\texttt{LLRRLL}, \texttt{LRLRLR}, \texttt{RRRLLL}, \ldots$ do not require any operations to be performed on them, since they represent configurations of lamps in which all trophies are already illuminated. Now, we consider the case when such $i$ does not exist and think about how we can use the operation **once**. Notice that if $\texttt{R}$ appears right after some $\texttt{L}$, an operation can be used to transform $\texttt{LR}$ into $\texttt{RL}$, and we have concluded before...
large sum and then we excluded all subsets which are less than some other included set. So, the max

Полный текст и комментарии »

Разбор задач Hello 2023
  • Проголосовать: нравится
  • +356
  • Проголосовать: не нравится

257.
Автор zscoder, история, 10 лет назад, По-английски
Codeforces Round #372 Editorial We hope everyone enjoyed the problems. Here is the editorial for the problems. I tried to make it more detailed but there might be some parts that might not be explained clearly. [Div. 2 A &mdash; Crazy Computer](http://codeforces.me/contest/716/problem/A) ------------------ Prerequisites : None This is a straightforward implementation problem. Iterate through the times in order, keeping track of when is the last time a word is typed, keeping a counter for the number of words appearing on the screen. Increment the counter by $1$ whenever you process a new time. Whenever the difference between the time for two consecutive words is greater than $c$, reset the counter to $0$. After that, increment it by $1$. Time Complexity : $O(n)$, since the times are already sorted. <spoiler summary="Code (O(n))"> ~~~~~ #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #def...
right square of the grid was $(n, n)$ and increased to $(n + 1, n + 1)$. So, thenumber $x$ is written

Полный текст и комментарии »

Разбор задач Codeforces Round 372 (Div. 1)
Разбор задач Codeforces Round 372 (Div. 2)
  • Проголосовать: нравится
  • +173
  • Проголосовать: не нравится

258.
Автор galen_colin, 6 лет назад, По-английски
Hybrid Tutorial #-1: Heavy-Light Decomposition **[Here](https://www.youtube.com/watch?v=_G_LMuLWMaI&list=PLDjGkpToBsYDx4GWu2u87sTqt6ICELz-T) is a playlist of all hybrid tutorials I've done.** # "Intro" _Timestamp: [00:00](https://youtu.be/_G_LMuLWMaI)_ Hi! Definitely not inspired by [this comment](https://codeforces.me/blog/entry/81086?#comment-675431), I've decided to try something that seems relatively novel &mdash; combining a blog and video tutorial into one, in a "hybrid" fashion. Both should be usable independently, but they will have the same "flow" and structure so you can reference both for concepts that are harder to grasp, and the two will supplement each other. The goal of these is to be **complete** &mdash; beneficial for both video and blog lovers, as well as full of enough information that anyone without much of an idea of what the concept is should be able to fully understand. There will be code as well, however, I very highly recommend not looking at it, but rather working out the implementation for yours...
"). For example, for a max segment tree, this would be a very large (by magnitude) negativenumber

Полный текст и комментарии »

  • Проголосовать: нравится
  • +404
  • Проголосовать: не нравится

259.
Автор -1e11, 20 месяцев назад, По-английски
April Fools Day Contest 2025 Editorial ### [2095A &mdash; Piecing It Together](https://codeforces.me/contest/2095/problem/A) Credits: [user:flamestorm,2025-04-01] <spoiler summary="Solution"> If you complete the puzzle, you will get a line of Python code reading $\texttt{print("puzzling")}$. To solve the problem, you just need to print $\texttt{puzzling}$. </spoiler> <spoiler summary="Code (C++)"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve() { cout << "puzzling\n"; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); solve(); } ~~~~~ </spoiler> <spoiler summary="Code (Python)"> ~~~~~ print("puzzling") ~~~~~ </spoiler> ### [2095B &mdash; Plinko](https://codeforces.me/contest/2095/problem/B) Credits: [user:AlperenT,2025-04-01] <spoiler summary="Solution"> In this problem you need to drop a ball from a column of your choosing and get it to the green area. With simple analysis (similar to Pascal's triangle), one can notice that best chanc...
submission got accepted, then it will show up if you query any number, as long as thatnumber doesn't

Полный текст и комментарии »

Разбор задач April Fools Day Contest 2025
  • Проголосовать: нравится
  • +169
  • Проголосовать: не нравится

260.
Автор peti1234, 5 лет назад, По-английски
Codeforces Round #783 Editorial Hope you enjoyed the problems. <spoiler summary="Direction Change"> [problem:1668A] <spoiler summary="Solution"> The moves are symmetrical, so we can assume that $n≥m$. There is no solution if $m=1$ and $n≥3$, because one can only move up and down, but two consecutive down moves is required to reach $(n, 1)$. Otherwise, there is a solution. One should move downwards at least $n-1$ times, and it is forbidden to do that twice in a row, so another $n-2$ move is necessary ($1$ between each pair). So at least $n-1+n-2=2 \cdot n-3$ moves required. If $n+m$ is even, then one more, because the parity of $a+b$ changes after every move, and the parity is even before the first and after the last move, so the total number of moves should be even. There is a construction for that lower bound: Move alternately down and right. After reaching the $m$-th column, repeat the following sequence of moves: down, left, down, right. With this $4$ move long sequence, one can move down t...
bound for the number of free chairs: $a_2+a_3+...+a_{n-1}+2 \cdot a_n$.

Полный текст и комментарии »

Разбор задач Codeforces Round 783 (Div. 1)
Разбор задач Codeforces Round 783 (Div. 2)
  • Проголосовать: нравится
  • +146
  • Проголосовать: не нравится

261.
Автор MohammadParsaElahimanesh, 4 года назад, По-английски
Codeforces Global Round 23 Editorial Hi Codeforces, I've tried my best to make a different editorial, I wish you enjoy it ... [problem:1746A] problem author: [user:MohammadParsaElahimanesh,2022-10-15], [user:AmirrzwM,2022-10-15] <spoiler summary="step by step solution"> step 1: It's obvious that the answer is "NO" if $a_{i} = 0$ for all $1 \le i \le n$. step 2: Lets prove that the answer is "YES" if $a_{i} = 1$ for at least one $1 \le i \le n$. step 3: If size of $a$ is equal to $k$, just use second type operation once and we are done. step 4: Otherwise (if $|a| > k$), there will be three cases: (assume that $a_{j} = 1$) - if $j > 2$, you can use first type operation on first and second element and decrease size of $a$ by 1. - else if $j < |a|-1$, you can use first type operation on last and second to last element and decrease size of $a$ by 1. - else, it can be shown easily that $|a| = 3$ and $k = 2$ so you can use second type operation twice and turn $a$ into a single $1$. In ...
large values) it's best to update $dp[A][B]$ from something around $dp[A-A/2][A/2+B/2]$ (in other words

Полный текст и комментарии »

Разбор задач Codeforces Global Round 23
  • Проголосовать: нравится
  • +240
  • Проголосовать: не нравится

262.
Автор MinakoKojima, 12 лет назад, По-английски
Codeforces Round #259 Editorial Overview ======== There are 3 normal tasks accompanied with 2 challenge tasks in div 1 as we usually do. You can check the [Statistics](http://codeforces.me/blog/entry/13271) by By [user:DmitriyH,2014-08-06] for detail. Problem B, C is by [user:sevenkplus,2014-08-06], problem D is by [user:xlk,2014-08-06] and problem A, E is by me. Problem E is rather complicated then hard, it means if you carefully broke down the problem into smaller ones, it became quite straightforward. During the contest, only [user:kcm1700,2014-08-06] managed to solve it successfully. Problem D, which decided the round boiled down to the following nice Dynamic Programming subproblem: you are given $2^20$ numbers. For each position i between 0 and $2^{20}-1$, and for each distance $j$ between 0 and 20, what is the sum of the numbers with such indexes $k$ that $k$ and $i$ differ in exactly $j$ bits? The fun part is not how to do it $T$ times, it is how to do it even once on $10^6$ numbers. [user:...
Enumerate the maximum number, the distribution will be a $n$-dimensional super-cube with $m$-length

Полный текст и комментарии »

Разбор задач Codeforces Round 259 (Div. 1)
Разбор задач Codeforces Round 259 (Div. 2)
  • Проголосовать: нравится
  • +54
  • Проголосовать: не нравится

263.
Автор Intellegent, история, 22 месяца назад, По-английски
Codeforces Round 1005 (Div. 2) Editorial Thank you everyone for participating! [problem:2064A]: <spoiler summary="Solution"> Notice that if $s$ starts with a $1$ we must move the entire string $s$ to $t$ at some point. Also Notice that if we perform the operation, the total number of occurrences of $01$ and $10$ across both strings can only decrease by one. This gives us an upper bound on the answer being the number of occurrences of $01$ and $10$ in $s$ adding one to this if it starts with the character $1$. Now the following construction uses the same number of moves as the upper bound (thus showing it is the minimum number of moves): If $s$ begins with $1$ then select the entire string $s$ and move it to $t$. Then repeatedly find the first character in $s$ or $t$ which is not equal to the character before it (note under this construction such an index can only exist in one string at a time) and selected the suffix starting from this character and move it to the other string. During this construction some prefi...
$ after the last element bigger than $y$. Once we can use prefix sums to find thenumber of possible

Полный текст и комментарии »

Разбор задач Codeforces Round 1005 (Div. 2)
  • Проголосовать: нравится
  • +119
  • Проголосовать: не нравится

264.
Автор laoriu, 12 лет назад, По-английски
Codeforces Round #277(Div. 2) Editorial [problem:486A] If $n$ is even, then the answer is $n/2$, otherwise the answer is $(n - 1) / 2 - n$ = $-(n + 1) / 2$. [problem:486B] Hint of this problem is presented in its statement. "$a_1 \operatorname{OR} a_2 \operatorname{OR} \dots \operatorname{OR} a_k$ where $a_i \in \{0, 1\}$ is equal to $1$ if some $a_i = 1$, otherwise it is equal to $0$." To solve this problem, do 3 following steps: 1. Assign all $a_{ij}$ ($1 \le i \le m, 1 \le j \le n$) equals to 1. 2. If some $b_{ij}$ = 0, then do assignments: $a_{ik}$ = $a_{tj}$ = 0 ($1 \le k \le n, 1 \le t \le m$) (that means, assign all elements in row $i$ and column $j$ of matrix $a$ to 0). 3. Then we have matrix $a$ which need to find. Just check whether from matrix $a$, can we produce matrix $b$. If not, the answer is obviously "NO". Complexity: We can implement this algorithm in $O(m * n)$, but it's not neccesary since $1 \le m, n \le 100$. [problem:486C] Assuming that cursor's position is in the first half o...
We have an additional issue. The number of LIS of $\{a_1, a_2, \dots, a_n\}$ maybe verylarge

Полный текст и комментарии »

Разбор задач Codeforces Round 277 (Div. 2)
  • Проголосовать: нравится
  • +94
  • Проголосовать: не нравится

265.
Автор brunomont, 6 месяцев назад, По-английски
Chinese Postman Problem: How I Ran a 180 km Ultramarathon Through Every Street in My City Hello, Codeforces! A couple of years ago, a friend of mine told me that two cyclists had passed through every single street in the center region of the city I live in (Belo Horizonte, southeastern Brazil), on the [third try](https://www.strava.com/activities/1030665876/overview). <spoiler summary="First try"> After ~160 km, they had not completed 1/3 of the goal. [Strava link](https://www.strava.com/activities/976021527). <img src="/predownloaded/8a/53/8a53829f7d78e88808a3ff751b64406ec2fc0efd.png" style="width: 600.0px;max-width: 100.0%;max-height: 100.0%;"> </spoiler> <spoiler summary="Second try"> They were better prepared, but one of the guys was run over by a car (no big injuries). [Strava link](https://www.strava.com/activities/999450285). <img src="/predownloaded/85/8f/858fdcdcfda93cd1d9c7c59db7dbfad9e63d6ea2.png" style="width: 600.0px;max-width: 100.0%;max-height: 100.0%;"> </spoiler> <center> <img src="/predownloaded/8d/5c/8d5cfb677a361654105e49f36f214c35...
streets that are too close to each other (such as sidewalks on different sides of alarge street), then

Полный текст и комментарии »

  • Проголосовать: нравится
  • +802
  • Проголосовать: не нравится

266.
Автор yak_ex, 16 лет назад, По-английски
A way to use C++ iostream for large input (gcc only) <P><STRONG>Updated:</STRONG> Add note for Cygwin environment.<BR><STRONG>Updated</STRONG>: Add result on FreeBSD<STRONG> </STRONG><BR></P><P>In programming competition such as Codeforces, reading a large number of inputs is somtimes required, for example, 1500*1500 integers in <A href="http://www.codeforces.com/contest/46/problem/E">Codeforces Beta Round #43 Problem E</A>. I used iostream(cin) in the competition and got TLE. After the competition, I saw some comments that cin caused TLE. After I replaced cin with scanf, I got AC. So, it is said "For large input, use cstdio instead of iostream." However I believe C++ users want to use iostream. Can't we avoid the guideline?</P><P><STRONG>Short answer:</STRONG></P><P>I found one promising way. Unfortunately, it is applicable not to VC but to gcc. Call std::ios_base::sync_with_stdio(false) at the beginning of your code. Here is the graph to show performance comparison among iostream with the call, without the call and cstdio, <EM><STRONG>...
A way to use C++ iostream for large input (gcc only), In programming competition such as Codeforces, reading a large number of inputs is somtimes

Полный текст и комментарии »

  • Проголосовать: нравится
  • +14
  • Проголосовать: не нравится

267.
Автор RedNextCentury, история, 9 лет назад, По-английски
[GYM] Damascus-CPC 2018 — Editorial A. Martadella Strikes Again ================== if $ R*R > 2*r*r $ print $1$, otherwise print $2$ $R$ and $r$ should be **long long** or **double** to avoid overflow [C++ Code](https://pastebin.com/1CKZu6yN) B. Amer and Graphs ================== Since the edges are undirected ,we can store the edges ${u,v}$ as $(u \le v)$ for every edge $(1 \le i \le n)$. Let's assign a unique number for every unique edge in the array, then our problem will be reduced to : Find the number of different segments of the array which have the exact same elements ( same frequencies as well for each element ). This problem is a classic hashing problem that can be solved this way : let's choose some random large prime numbers $P$ and $MOD$ ,for example $P=304933 , MOD=10^9+7$. replace every element ${x_i}$ from the array with $ P^{x_i} \% MOD $. now the final problem is about finding different segments of the array which have the same sum value $\% MOD$ . This sol...
let's choose some random large prime numbers $P$ and $MOD$ ,for example $P=304933 , MOD=10^9+7$.

Полный текст и комментарии »

Теги gym
  • Проголосовать: нравится
  • +20
  • Проголосовать: не нравится

268.
Автор reirugan, 12 месяцев назад, По-английски
Codeforces Round 1065 (Div. 3) Editorial I hope you all enjoyed the contest! Special thanks to - [user:djm03178,2025-11-18] for suggesting the inclusion of C1, and for helping with test writing on all problems, especially F - [user:satyam343,2025-11-18] for helping me solve H - [user:Dominater069,2025-11-18] for providing the idea for one of the solutions to E - [user:Intellegent,2025-11-18] for providing one of the proofs for the solution to D, and for providing the idea for one of the solutions to F <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> #### [...
We would like to choose the largest number of double operations

Полный текст и комментарии »

Разбор задач Codeforces Round 1065 (Div. 3)
  • Проголосовать: нравится
  • +129
  • Проголосовать: не нравится

269.
Автор Spheniscine, история, 7 лет назад, По-английски
Notes on FFT / NTT, and the "ultimate" NTT with modulus > 9 * 10^18 Prerequisites: you need to be familiar with both [modular arithmetic](https://codeforces.me/blog/entry/72527) and Fast Fourier Transform / number theoretic transform. The latter can be a rather advanced topic, but I personally found [this article](https://cp-algorithms.com/algebra/fft.html) helpful. Note that there are some relatively easy optimizations/improvements that can be done, like precalculating the modular inverse of $n$, the "bit-reversed-indices" (can be done in $O(n)$ with DP), as well as the powers of $\omega_n$. Also useful is modifying it so that the input array length can be any power of two $\leq n$; some problems require multiplying polynomials of many different lengths, and you'd rather the runtime be $O(n \log n)$ over the sums of lengths, rather than (number of polynomials * maximum capacity). Also helpful is knowing how to use NTT to solve problems modulo $998244353$, like [problem:1096G] and [problem:1251F]. Note that for some problems it's easier to think of...
case could overflow even this large modulus, but it can be handled with the "multiplication with

Полный текст и комментарии »

  • Проголосовать: нравится
  • +183
  • Проголосовать: не нравится

270.
Автор ABalobanov, 12 месяцев назад, По-русски
Codeforces Round 1070 (Div.2) Editorial Thank you all for participation! We hope, you enjoyed the problems. ###[problem:2176A] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Which element of the array cannot be removed using the described operations? </spoiler> <spoiler summary="Hint 2"> Under what condition the element $a_j$ **cannot** be removed? </spoiler> </spoiler> <spoiler summary="Solution"> Note that the element $a_1$ cannot be removed using the described operations. In general, the $j$-th element **cannot** be removed if $a_j$ is not less than all elements $a_1 \ldots a_{j - 1}$. Otherwise, among the elements $a_1 \ldots a_{j - 1}$, there will always be an element $a_i > a_j$, which means that $a_j$ can be removed. The constraints are small enough, so for each element, this statement can be checked in $O(n)$ for one check &mdash; resulting in a total of $O(n^2)$ for the test. The idea for solving it in $O(n)$ is as follows: - We will process the elements starting from $a...
greatest common divisor $g$ from $maxA$ down to $1$. If we simply wanted to count thenumber of pairs

Полный текст и комментарии »

Разбор задач Codeforces Round 1070 (Div. 2)
  • Проголосовать: нравится
  • +139
  • Проголосовать: не нравится

271.
Автор shorya1835, 21 месяц назад, По-английски
Editorial for Insomnia'25 [A \- XO-OR](https://codeforces.me/gym/590997/problem/A) <spoiler summary="Solution"> To solve this problem optimally, we need to ensure that we maximize the size of the set $S$ while satisfying the given constraints on XOR and OR operations. A necessary condition for a valid set is that $ y $ must be a **subset** of $ v $. In terms of bits, this means every bit that is set in $ y $ must also be set in $ v $. If $ y > x $, then at least one bit in $ y $ is missing from $ x $, making it impossible to construct a valid set where the XOR of elements results in $ y $. Thus, in such cases, the answer is immediately $ -1 $. To understand how we construct valid sets, consider forming all possible subsets of the bits set in $ v $. The total number of such subsets is $ 2^{pc} $, where $ pc $ is the number of set bits in $ v $. Each individual bit contributes exactly $ 2^{(pc - 1)} $ times across all subsets, meaning the overall XOR of the entire set cancels out to $ 0 $ when $ pc \ge...
gap is **much smaller** than $n$. 3. Thus, for any subset of odd vertices $X$, thenumber of

Полный текст и комментарии »

Разбор задач Insomnia 2025
  • Проголосовать: нравится
  • +73
  • Проголосовать: не нравится

272.
Автор Sharon, история, 8 лет назад, По-английски
A Public Apology (+Compensation) The Introduction ---------------- On March 32nd of this year I created a blog post to share some new coding techniques that are quite easy to code and serve as very powerful optimizations (Context: [https://codeforces.me/blog/entry/58667](https://codeforces.me/blog/entry/58667)). Now of course I know I single-handedly transformed the competitive programming meta as problems had to be done according to new standards now that it is possible to make O(N) code work O(1). Super fast. However, I have to share an upsetting discovery that I made. This blog post might be too sad for you, so discretion is advised. I have added certain checkpoints within this post where you can take a break if you get too sad and you may resume reading later. I have also added some cute pictures of animals to help out with your sadness. The Story --------- It all started yesterday, when I used my usual O(1) trick to O(N) trick on problem E2 from the last contest (It seems that Mirzayanov has not a...
search trick and dividing by a large number.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +222
  • Проголосовать: не нравится

273.
Автор KADR, 14 лет назад, По-русски
Editorial of Codeforces Round #153 This is a complete English version of the editorial of Codeforces Round #153. If you have any questions or suggestions, feel free to post them in the comments. ### [problem:252A] (A div 2) Let's iterate over all segments in our array. For each of them we'll find the $xor$ of all its elements. Then we need to output the maximal $xor$ we've seen. ### [problem:252B] (B div 2) If all elements in the array are equal then there's no pair of numbers we are looking for. Now we can assume that there exist at least 2 different numbers in the array. Let's iterate over all pairs of different numbers in the array and for each such pair we'll check if it can be the answer. If some pair indeed can be the answer, we'll output it and terminate the program. Otherwise, there is no pair of numbers we are looking for, so we need to output -1. It may seem that the complexity of described algorithm is $O(N^3)$. Actually it's not true and the real complexity is $O(N)$. One may notice that in ...
largest number. For further optimization one can use $bitset$ in Gaussian elimination, although it

Полный текст и комментарии »

Разбор задач Codeforces Round 153 (Div. 1)
Разбор задач Codeforces Round 153 (Div. 2)
  • Проголосовать: нравится
  • +34
  • Проголосовать: не нравится

274.
Автор Geothermal, история, 7 лет назад, По-английски
AtCoder Beginner Contest 146 English Solutions #A &mdash; Can't Wait for Holiday The only approach here is the trivial one--compare the input to each of the possible seven values and print the appropriate answer for each of them. One reasonably fast way to implement this is to create an array $A$ containing the seven inputs, with "SUN" in position zero and "SAT" in position six. Then, we compare $S$ to each value in the array and, upon finding the value $i$ such that $A[i] = S$, we print $7-i$. This is valid because the next Sunday after the day represented by our input would come in position seven. Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc146/submissions/8604159) --- #B &mdash; ROT N Again, the only real solution here is to directly implement the approach given in the problem statement. However, character arithmetic gives us a fairly nice way to do so. For each character in $S$, we can compute the position of the corresponding letter in the alphabet by taking $S[i]$ minus...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +90
  • Проголосовать: не нравится

275.
Автор Nakagawa.Kanon, история, 5 месяцев назад, По-английски
Me trying to study Atcoder World Tour Finals 2026 Algorithm : E — Even Rows ![ ](/predownloaded/77/c3/77c355894f49137e2eda44b44cc2e53a9fd7371e.png) It took days for me to just to barely understand the editorials and from my own opinion, it was so obscure and omitted lot of thing to barely make sense so I had an idea to share my own analysis here for everyone to discuss. Please note this is a wall of text since I want to elaborate on every ambiguous part of editorial and explain my flow of logic as much as possible and for anyone patient enough to read through the end, please share some advice and opinion to optimize and speed up my logic arguments, maybe fixing some typo or request some clarification of my explanation if possible. Thank you for reading. First about the problem statement, it can be divide into 3 parts : - Input : + A table with size $N\times M$ + Each cell is either empty or has a piece on it - Algorithm 1 : Take a table with pieces on it as input + Define the way to move a piece in the table + The ...
with a unique ball node with recorded number of row it got created from the table the in the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +165
  • Проголосовать: не нравится

276.
Автор PraveenDhinwa, 12 лет назад, По-английски
Codeforces Round #258 Editorial **[problem:451A]** From a grid of size $n * m$, if we remove an intersection point, then the grid after removing the sticks passing through it, will of size $n - 1$, $m - 1$. Notice when the grid consists of a single horizontal stick and m vertical sticks, If we pick any intersection point, then the updated grid will be only made of vertical sticks. You can see that there is no intersection point in the grid now. So $ans(n, m) = ans(n - 1, m - 1)$ ^ $1.$ $ans(1, *) = 1$ $ans(*, 1) = 1$ So we can notice that answer will depend on the parity of $minimum(m, n)$. You can prove it using the previous equations. You can also check this by seeing the pattern. So finally if $min(n, m)$ is odd, then Akshat will win. Otherwise Malvika will win. You can also observe that "players will play optimally" is useless in this case. Complexity : $O$(1) **Solution codes** - [my solution](http://codeforces.me/contest/451/submission/7233706) **[problem:...

Полный текст и комментарии »

Разбор задач Codeforces Round 258 (Div. 2)
  • Проголосовать: нравится
  • +39
  • Проголосовать: не нравится

277.
Автор xiaowuc1, 3 года назад, По-английски
rationalisering — more issues with floating-point numbers I was motivated to write this blog post after reading [this blog post](https://codeforces.me/blog/entry/117430) about possible precision issues in output and requiring printing a rounded answer exactly instead of printing an answer within a tolerance. This blog post feels somewhat related insofar as that it has an issue with floating point numbers, and also a doubt as to the correctness of the underlying data. Alternatively, someone can find the mistake in my logic. The problem in question is [Rationalization](https://open.kattis.com/problems/rationalisering) which asks to find a positive rational $\frac{A}{B}$ that is within a range $[C-F, C+F]$. Among all such fractions, minimize $A$, and among all such with minimal $A$, minimize $B$. The judge data guarantee that $1 \le A, B < 10^6$. My solution path is as follows: If $C-F \le \frac{A}{B} \le C+F$, then $B(C-F) \le A \le B(C+F)$. Therefore, we can just check all $B$ in increasing order and find the smallest $B$ where $[B(C-F)...
which is deemed incorrect (as opposed to printing nothing or printing a value of $A$ that is toolarge

Полный текст и комментарии »

  • Проголосовать: нравится
  • +108
  • Проголосовать: не нравится

278.
Автор dreamoon_love_AA, история, 11 лет назад, По-английски
Codeforces Round #320 [Bayan Thanks-Round] Editorial ## [Problm 1 : Raising Bacteria](http://codeforces.me/problemset/problem/579/A) Write down $x$ into its binary form. If the $i^{th}$ least significant bit is $1$ and $x$ contains $n$ bits, we put one bacteria into this box in the morning of $(n+1-i)^{th}$ day. Then at the noon of the $n^{th}$ day, the box will contain $x$ bacteria. So the answer is the number of ones in the binary form of $x$. [code of author's friend: this](http://codeforces.me/contest/579/submission/13053439) ## [Problem 2 : Finding Team Member](http://codeforces.me/problemset/problem/579/B) Sort all possible combinations from high strength to low strength. Then iterator all combinations. If two people in a combination still are not contained in any team. then we make these two people as a team. [author's code: this](http://codeforces.me/contest/579/submission/13053526) ## [Problem 3 : A Problem about Polyline](http://codeforces.me/problemset/problem/578/A) If point ($a$,$b$) is located on t...
$ and all other $t_i$ equals to $0$. If not, we can choose the largest number $b_j$ in sequence $b

Полный текст и комментарии »

  • Проголосовать: нравится
  • +89
  • Проголосовать: не нравится

279.
Автор askd, история, 6 лет назад, По-английски
Introducing cp-notes.com — a place for your interesting competitive programming problems! **Update in 2025:** I've mostly forgotten about this site, but recently something rather funny came up: I was looking for a way to get a relatively large number of free subdomains (name of the url not mattering at all), when I realized I was still paying for cp-notes.com. So I tried to login to the AWS account owning the domain (which I haven't done in years), but it prompted me to check the email associated with it for a verification code... Unfortunately, I had used my Columbia university email out of convenience, but that has been disabled! (which I suspect has something to do with me dropping out?) I actually can still update the website (not that I was planning to) since I have some keypair saved which allows programmatic access, but not being able to use the console is a huge pain. I could also contact AWS support, but I feel like that would take a while... Anyways, it is time for me to express some of my frustrations: Fuck Columbia University! In addition to disabling my emai...
up: I was looking for a way to get a relatively large number of free subdomains (name of the url

Полный текст и комментарии »

  • Проголосовать: нравится
  • +314
  • Проголосовать: не нравится

280.
Автор PokemonMaster, история, 14 месяцев назад, По-русски
2147G Number Theory Approach # G. Modular Tetration — a Number Theory Solution ## Preliminary Comments I deleted the first post and am publishing a new one with preliminary comments. This problem turned out to be problematic and spoiled the contest for strong participants, since some cheaters copied it, but it didn’t seem difficult to me, except for deriving the final formula and a bit of implementation. During the contest, I managed to work out the implementation on paper, but I couldn’t handle the coding. I am a junior in mathematics, focusing on number theory and algebra (at the last JBMO I managed to solve both of these topics), but I still have many gaps in CP and implementation. In number theory I solve or make substantial progress on many problems from IMO shortlists. If you assign a CF-like rating to those problems, I solve problems steadily up to 2000, sometimes up to 2500, and there have been harder ones. Now I want to use number theory and mathematical implementation of programming problems ...
2147G Number Theory Approach, $$ d\mid \varphi(m)\quad\text{and}\quad d\mid b_n\ \ \text{for all large }n. $$

Полный текст и комментарии »

  • Проголосовать: нравится
  • +74
  • Проголосовать: не нравится

281.
Автор khatribiru, история, 9 лет назад, По-английски
Persistent segment tree ( Problems ) This blog is just the list of problems for Persistent segment tree. Before start you can learn the topic from [here](https://blog.anudeep2011.com/persistent-segment-trees-explained-with-spoj-problems/) , [here](https://www.geeksforgeeks.org/persistent-segment-tree-set-1-introduction/) & [here](https://drive.google.com/file/d/0BwGLW04WRv0ITEZjRWlMSFc2bk0/view) 1.[SPOJ,MKTHNUM,K-th Number](http://www.spoj.com/problems/MKTHNUM/) 2.[SPOJ,DQUERY,D-query](http://www.spoj.com/problems/DQUERY/) 3.[SPOJ,COT,Count on a tree](http://www.spoj.com/problems/COT/) 4.[SPOJ,TTM,To the moon](http://www.spoj.com/problems/TTM/) 5.[lightoj,1188,Fast Queries](https://vjudge.net/problem/LightOJ-1188) 6.[CF,813E,Army Creation](http://codeforces.me/problemset/problem/813/E) 7.[CF,707D,Persistent Bookcase](http://codeforces.me/contest/707/problem/D) 8.[CF,762E,Radio stations](http://codeforces.me/problemset/problem/762/E) 9.[Hackerrank,Kth Number](https://www.hackerrank.com/contest...
9.[Hackerrank,Kth Number ](https://www.hackerrank.com/contests/morgan-stanley-2015/challenges/wet

Полный текст и комментарии »

  • Проголосовать: нравится
  • +75
  • Проголосовать: не нравится

282.
Автор Al.Cash, 10 лет назад, По-английски
Geometry: 2D points and lines [Tutorial] I get an impression that a lot of coders struggle with geometric problems and prefer to avoid them. That's not much of a surprise, considering that I couldn't find a good writing explaining the basics and giving useful advice how to proceed. Moreover, some resources obfuscate this beautiful area to the point it's despised by the readers. I'll try to change that, but first I'll mention some of the better resources: [geomalgorithms.com](http://geomalgorithms.com/points_and_vectors.html) This is where you can start if you don't have a basic notion of a vector. Also there are more detailed explanations for some examples I'll list, but I dislike the implementations. [This post in Russian](http://codeforces.me/blog/entry/6642) has a link to the code that's most similar to mine, with some comments (unfortunately, also is Russian)[cut]. ### Point structure and operations Without further ado, I'll start with my code for the `Point` structure. Explanations are below, so don't rush t...
difference of two input points. Basically, the largest number we can end up with is the squared distance

Полный текст и комментарии »

  • Проголосовать: нравится
  • +222
  • Проголосовать: не нравится

283.
Автор catalystgma, история, 2 года назад, По-английски
Exponential Length Substrings in Pattern Matching Hi all, I would like to share with you a part of my undergraduate thesis on a Multi-String Pattern Matcher data structure. In my opinion, it's easy to understand and hard to implement correctly and efficiently. It's (relatively) competitive against other MSPM data structures (Aho-Corasick, suffix array/automaton/tree to name a few) when the dictionary size is specifically (uncommonly) large. I would also like to sign up this entry to [user:bashkort,2024-10-04]'s [Month of Blog Posts](https://codeforces.me/blog/entry/133806):-) Many thanks to him and peltorator for supporting this initiative. #### Abstract This work describes a hash-based mass-searching algorithm, finding (count, location of first match) entries from a dictionary against a string $s$ of length $n$. The presented implementation makes use of all substrings of $s$ whose lengths are powers of $2$ to construct an offline algorithm that can, in some cases, reach a complexity of $O(n \log^2n)$ even if there are $O...
$. The large number of squares in $s$ would make our algorithm's compression phase more efficient.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +268
  • Проголосовать: не нравится

284.
Автор Serval, 8 лет назад, По-английски
Codeforces Round #551 (Div. 2) Editorial [problem:1153A] Author: [user:Serval,2019-04-14], preparation: [user:bzh,2019-04-14] <spoiler summary="Editorial"> Find the first bus Serval can see in each route and find the earliest one. For each route, finding the first bus Serval sees can work in $O(1)$. Or mark all the time no more than $\max(s_i,t+\max(d_i))$ which bus would come or there will be no bus, then search the nearest one. </spoiler> [problem:1153B] Author: [user:Serval,2019-04-14], Preparation: [user:bzh,2019-04-14] <spoiler summary="Editorial"> Fill in all the bricks, and then remove all bricks you must remove (which in some view, there is empty). This can be solved in $O(nm)$. </spoiler> [problem:1153C] Author & preparation: [user:Serval,2019-04-14] <spoiler summary="Editorial"> First let `(` be $+1$, `)` be $-1$ and `?` be a missing place, so we will replace all the missing places in the new $+1$,$-1$ sequence by $+1$ and $-1$. Obviously, for each prefix of a correct parenthesis s...
written in the leaves to make the number written in $u$ be as large as possible. For all sons or children

Полный текст и комментарии »

  • Проголосовать: нравится
  • +91
  • Проголосовать: не нравится

285.
Автор wakanda-forever, история, 14 месяцев назад, По-английски
Codeforces Round 1059 (Div. 3) Editorial [problem:2162A] Idea: [user:wakanda-forever,2025-10-10] Preparation: [user:wakanda-forever,2025-10-10] <spoiler summary = "Solution"> Let's say we have a sequence of numbers with an average equal to $k$. Adding a number greater than $k$ increases the average, while adding a smaller one decreases it. Therefore, the maximum average subarray is formed by taking the maximum element, since including anything smaller would only lower the average. Hence, the final answer is the maximum element of the given array. Time Complexity: $O(n)$ per testcase. </spoiler> <spoiler summary = "Implementation"> ~~~~~ #include<bits/stdc++.h> using namespace std; #define ll long long int main(){ int t; cin >> t; while(t--){ int n; cin >> n; vector<int> a(n); for(int i = 0; i < n; i++) cin >> a[i]; cout << *max_element(a.begin(), a.end()) << endl; } return 0; } ~~~~~ </spoiler> [...
type on i and j // dp[i][number of 0s] = max number of 1s, but also need to know what is the

Полный текст и комментарии »

Разбор задач Codeforces Round 1059 (Div. 3)
  • Проголосовать: нравится
  • +69
  • Проголосовать: не нравится

286.
Автор marat.snowbear, 12 лет назад, перевод, По-русски
Codeforces Round #269 Editorial [problem:471A] ------------------ Given six sticks and their lengths we need to decide whether we can make an elephant or a bear using those sticks. The only common requirement for both animals is that four leg-sticks should have same length. This means that the answer "Alien" should be given **only** if we can't find four sticks for the legs. Otherwise we will be able to make some animal. The type of the animal will depend on the relation of the remaining sticks' lengths. If they are equal then it will an elephant, if they are different we will have a bear. So this algorithm should solve the problem: 1. Find the number which appears at least four times in the input. 2. If no such number exist then the answer is "Alien". 3. Otherwise remove four entries of that number from the input. 4. After removing that number you will have two numbers left, compare them and decide whether it's an elephant or a bear. One shortcut for this problem might be to sort the in...
give non-decreasing array. This number might be very large and it might easily overflow even long

Полный текст и комментарии »

Разбор задач Codeforces Round 269 (Div. 2)
  • Проголосовать: нравится
  • +186
  • Проголосовать: не нравится

287.
Автор DanTheMan., 18 месяцев назад, По-английски
mBIT 2025 Editorial Thank you to everyone who competed in mBIT 2025! It was a record breaking year for us with 84 in-person participants and 135 online participants. We hoped you guys enjoyed it as much as we did. We tried hard to make the problems fun and interesting for as wide of a skill gap as possible. In fact, this year's competition had an in-person team of middle schoolers that was unfamiliar with for loops, and an online team with all three participants in the top 15 in the world in codeforces. We are glad to contribute to all niches of the computer science community: beginner and advanced, local and global. Thank you all for your enthusiasm. Congratulations to the winners: **Online Advanced:** - 1st place &mdash; HoMaMaOvo &mdash; Masaki Nishimoto, Riku Kawasaki, Yui Hosaka - 2nd place &mdash; mathforcesbox &mdash; Brian Xue, Bing-Dong Liu, Alex Chen - 3rd place &mdash; bluepuppygreenturtle &mdash; Rain Jiang, Kai Jiang **Online Intermediate:** - 1st place &mdash; NULP Lega...
Now, how can we quickly compute the number of operations we can achieve following this strategy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +77
  • Проголосовать: не нравится

288.
Автор dacin21, история, 8 лет назад, По-английски
On the mathematics behind rolling hashes and anti-hash tests This blog assumes the reader is familiar with the basic concept of rolling hashes. There are some math-heavy parts, but one can get most of the ideas without understanding every detail. The main focus of this blog is on how to choose the rolling-hash parameters to avoid getting hacked and on how to hack codes with poorly chosen parameters. # Designing hard-to-hack rolling hashes ## Recap on rolling hashes and collisions Recall that a rolling hash has two parameters $(p, a)$ where $p$ is the modulo and $0 \leq a < p$ the base. (We'll see that $p$ should be a big prime and $a$ larger than the size $\left|\Sigma\right|$ of the alphabet.) The hash value of a string $S = s_0 \dots s_{n-1}$ is given by $$ h(S) := \left(\sum\limits_{i=0}^{n-1} a^{n-1-i} s_i\right) \mod p $$ For now, lets consider the simple problem of: given two strings $S, T$ of equal length, decide whether they're equal by comparing their hash values $h(S), h(T)$. Our algorithm declares $S$ and $T$ t...
$ large enough, $X \neq 0$. Moreover $\left|X\right| < a^n$. An upper bound for thenumber of

Полный текст и комментарии »

  • Проголосовать: нравится
  • +371
  • Проголосовать: не нравится

289.
Автор NALP, 16 лет назад, По-русски
Yandex.Algorithm 2011 Qualification 2 (Tutorial) <p></p><h2>Task A. Double Cola</h2><div><div>Let's designate characters on the first letter of the name. The queue looks like: SH-L-P-R-G, through 5 cans: SH-SH-L-L-P-P-R-R-G-G, through 10 cans: SH-SH-SH-SH-L-L-L-L-P-P-P-P-R-R-R-R-G-G-G-G.</div><div><br></div><div>The regularity is clear, and the&nbsp;solution&nbsp;is very simple: we will be iterated on $p$ - we will find such minimum $p$ that $5 \cdot 2^p&gt; n$ (thus if this number is less or equally we will subtract it from $n$) then we know that at first $2^p$ Sheldon's stand, then $2^p$ Leonard's and so on. And now we can easily answer who took a can number $n$ (namely there was a person with number $n / 2^p$ in sequence SH-L-P-R-G (in 0-indexation).</div></div><h2>Task B. Sets</h2><div><div>For the&nbsp;solution&nbsp;the following important fact is required to us: we will admit elements $v$ and $u$ are in one set then in any of $n \cdot (n - 1) / 2$ of sequences from the input data where meets $v$ &nbsp;$u$ necessarily meets. And...
number the list of numbers of sequences where there is this number, and will unite two numbers if these

Полный текст и комментарии »

  • Проголосовать: нравится
  • +16
  • Проголосовать: не нравится

290.
Автор kien_coi_1997, 12 лет назад, По-английски
An efficient way to strengthen up your segment tree. I'm going to talking about a coding style in segment tree which I used for a long time. Not only is it more systematically, but it also support more kind of segment tree. 1. Old style ------------ Assume that we are making a segment tree support operators assign elements in a range (assign-range L R X) and get max element in a range (max-range L R). I found a large number of people use the following way to build segment tree: ~~~~~ void lazy_update(int u, int ll, int rr) { if (Lazy[u]==-1) return; // assume that -1 is unused value if (ll!=rr) Lazy[u*2]=Lazy[u*2+1]=Lazy[u]; Max[u]=Lazy[u]; Lazy[u]=-1; } void assign_range(int u, int ll, int rr, int L, int R, int X) { lazy_update(u, ll, rr); // call a function to lazy-update node u (which operate segment ll..rr) if (ll>R || L>rr) return; if (L<=ll && rr<=R) { Lazy[u]=X; lazy_update(u, ll, rr); return; } assign_range(2*u, ll, (ll+rr)/2, L, R, X); assign_range(2*u+1, (ll+rr)/2+...
I found a large number of people use the following way to build segment tree:

Полный текст и комментарии »

  • Проголосовать: нравится
  • +119
  • Проголосовать: не нравится

291.
Автор Newtech66, 5 лет назад, По-английски
Codeforces Round #782 (Div. 2) Editorial Thank you everyone for your participation. Do vote under the Feedback section, and feel free to give your review of the problems in the comments. --- [problem:1659A] <br> Idea: [user:TimeWarp101,2022-04-17] <br> Editorial: [user:TimeWarp101,2022-04-17] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Is it a good idea to have consecutive ``B``'s? </spoiler> <spoiler summary="Hint 2"> If you space out all the ``B``'s, how many regions do you have to place the ``R``'s into? </spoiler> <spoiler summary="Hint 3"> What is the best way of placing the ``R``'s into $b+1$ regions such that the maximum number of ``R``'s in a region is minimum? </spoiler> </spoiler> <spoiler summary="Solution"> [tutorial:1659A] </spoiler> <spoiler summary="Implementation (C++)"> ~~~~~ #include<bits/stdc++.h> using namespace std; using lol=long long int; #define endl "\n" int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int _=1; cin>>_; ...
$ starting from the left. What is the minimum number of times you have to select a bit to ensure it

Полный текст и комментарии »

Разбор задач Codeforces Round 782 (Div. 2)
  • Проголосовать: нравится
  • +74
  • Проголосовать: не нравится

292.
Автор top34051, 8 лет назад, По-английски
Codeforces Round #542 Hey Codeforces! We’re thrilled to invite you guys to Codeforces Round #542, which is going to take place on [Sunday, February 24, 2019, at 18:35 MSK](https://www.timeanddate.com/worldclock/fixedtime.html?day=24&month=2&year=2019&hour=18&min=35&sec=0&p1=166). There will be a separate round for each division, and they will be rated! Problems were prepared by [user:MikeMirzayanov,2019-02-24], [user:zoomswk,2019-02-23] and me. As the round authors, we would like to thank [user:ksun48,2019-02-23], [user:isaf27,2019-02-23], [user:tuna_salad,2019-02-23], and [user:Um_nik,2019-02-23] for testing the problems; [user:300iq,2019-02-23] and [user:KAN,2019-02-23] for their help and advice in contest preparation; and the invisible [user:MikeMirzayanov,2019-02-23] for the incredible Codeforces and Polygon platforms. Each division will be given 6 tasks and 2 hours to solve them. As per the Codeforces tradition, scoring distributions will be revealed shortly before the round. We wish you th...
am sure that a large number of young people got a lot from our community, even if they did not

Полный текст и комментарии »

  • Проголосовать: нравится
  • +248
  • Проголосовать: не нравится

293.
Автор J-C, история, 9 лет назад, По-английски
Number of Solutions to a Linear Algebraic Equation ### **The Basic Problem** Suppose, we have a Linear Algebraic Equation, $X$$_1 + X_2 + X_3 = 5$. Here the values of $X_1, X_2$ and $X_3$ can be non-negative integers. We want to know in how many ways we can assign values to $X_1, X_2$ and $X_3$ so that the summation is 5. We can consider this problem as dividing 5 objects among 3 persons. And below are some possible ways to do it &mdash; <a href="https://imgbb.com/"><img src="https://image.ibb.co/e9FV2Q/Capture.jpg" alt="Capture" border="0"></a> Here by O the objects are being represented and | represents partition. As the objects are divided among 3 persons we need 2 partitions which is pretty clear from the partitioning instances above. We can finalize this problem as simple combinatorial problem of number of ways of arranging 7 objects where 5 are of first kind and the other 2 are of second kind. And the answer is $\dfrac{7!}{5! 2!}.$ So if we have n objects in total and we wan...
Number of Solutions to a Linear Algebraic Equation, terms chosen as the requirement of the problem. Here the number of objects can be aslarge as $10^{12

Полный текст и комментарии »

  • Проголосовать: нравится
  • +63
  • Проголосовать: не нравится

294.
Автор EndlessDreams, 4 года назад, По-английски
TheForces Rounds Editorials Here's the editorials of [TheForces Rounds](https://t.me/TheForcesOfficial): <spoiler summary="Round 1"> <spoiler summary="Problem A"> For a number $x$, as long as $2\le x$, it can be squared to any large number. For $0$ and $1$, the square of both numbers is equal to themselves. So just compare $0$ and $1$. <spoiler summary="Code"> ~~~ void elysia() { cin >> n; bool flag=true; for(int i=1;i<=n;++i) { cin >> a[i]; a[i]=min(a[i],2ll); if(i!=1&&a[i]<a[i-1]) flag=false; } if(flag) cout << "YES" << endl; else cout << "NO" << endl; } ~~~ </spoiler> </spoiler> <spoiler summary="Problem B"> Consider the number of times each $a_i$ is XOR in the answer. for $a_i$, calculated $i(n-i+1)$ times in the answer. Two same XOR will disappear, so checking is this an odd number then done. <spoiler summary="Code"> ~~~ void elysia() { int answer=0; cin >> n; for(int i=1;i<=n;++i) { cin >> a[i]; ...
The reason for doing this is because we have an intuition: the smallest number that meets this, large number. For $0$ and $1$, the square of both numbers is equal to themselves. So just compare $0

Полный текст и комментарии »

Разбор задач TheForces Round #10 (TEN-Forces)
Разбор задач TheForces Round #14 (Cool-Forces)
Разбор задач TheForces Round #17 (AOE-Forces)
  • Проголосовать: нравится
  • +85
  • Проголосовать: не нравится

295.
Автор Kostroma, история, 11 лет назад, По-английски
Codeforces Round #317 [AimFund Thanks-Round] Editorial [problem:572A] In this problem one need to check whether it's possible to choose $k$ elements from array $A$ and $m$ elements from array $B$ so that each of chosen element in $A$ is less than each of chosen elements in $B$. If it's possible then it's possible to choose $k$ smallest elements in $A$ and $m$ largest elements in $B$. That means that in particular, $k$-th smallest element of $A$ is less than $m$-th largest element in $B$. So, if $A[k] < B[n - m + 1]$ then the answer is "YES" and if not, then the answer is "NO". Problem author: [user:zeliboba,2015-08-22]. Problem developers: [user:AlexDmitriev,2015-08-22], [user:Kostroma,2015-08-22]. Solution code: [submission:12873382]. [problem:572B] First of all the problem may be solved for buy orders and sell orders separately. The easiest soultion is to use structure like std::map or java.lang.TreeMap. To aggregate orders we just add volume to the corresponding map element: `aggregated[price] += volume`. After ...
each transition can be made in $O(1)$: we choose large or small group to add and obtain thenumber

Полный текст и комментарии »

  • Проголосовать: нравится
  • +70
  • Проголосовать: не нравится

296.
Автор r314, история, 14 месяцев назад, По-английски
ICPC 2025-2026 season "covid rule" Hello everyone, we are facing a problem due to changes in the rules of participation in the ICPC qualification. And these changes seem unfair to us! We want to report this issue to the community and hear your opinion. Please give feedback if you have any thoughts on this. So, about the rules: In 2020 (covid year), the ICPC organizers introduced a rule according to which participation in the 20/21 online qualification will not be counted in the number of possible participation in the qualification: A student who has competed in qualifying regional contests during five different contest years is NOT eligible to compete. **Regional participation 2020/21 is not counted towards the max 5 regionals!** https://web.archive.org/web/20220324023911/https://icpc.global/regionals/rules In 2023, this rule was unexpectedly removed for the 2025-2026 season: 1. A student who has competed in qualifying regional contests during five different contest years is NOT eligible to compete wi...
A large number of people who participated in the ICPC in 2020 (online qualification) had the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +118
  • Проголосовать: не нравится

297.
Автор YipChip, история, 6 месяцев назад, По-английски
Farey sequence and Approximation of real number First, the Farey sequence $F_n$ represents the set of all completely reduced proper fractions with denominators not exceeding $n$, arranged in ascending order of value. Formally speaking, $$F_n = \left\{\frac{p}{q} \bigg\vert 0 < p < q \le n, \, \gcd(p, q) = 1\right\}$$ The asymptotic size of this sequence is $\sum\limits_{i = 1}^{n} \varphi(n) \sim \frac{3}{\pi^2}n^2 + o(n \log n)$. Regarding the Farey sequence, there are two classic conclusions: - If $\frac{a}{b}$ and $\frac{c}{d}$ are two consecutive elements in $F_n$, then $\frac{a + c}{b + d}$ is also a valid Farey fraction. - If $\frac{a}{b}$ and $\frac{c}{d}$ are two consecutive elements in $F_n$, then their next element $\frac{p}{q}$ satisfies $$\begin{cases}p = \left\lfloor\frac{n + b}{d}\right\rfloor c - a \\ q = \left\lfloor\frac{n + b}{d}\right\rfloor d - b\end{cases}$$ We will only prove the second theorem above. For the Farey sequence of order $n$, two adjacent terms $\frac{a}{b} < \frac{c}{d}$ satisfy...
Farey sequence and Approximation of real number, To make $p, \, q$ highly precise (i.e., closely packed), the value of $k$ should be aslarge as

Полный текст и комментарии »

  • Проголосовать: нравится
  • +56
  • Проголосовать: не нравится

298.
Автор Wind_Eagle, история, 4 года назад, По-русски
Divide and conquer. Dynamic connectivity offline and DP optimization. Divide and conquer by queries. Hello, Codeforces! I have wanted to write an educational blog for a long time, but I couldn't find a topic for it. And recently I remembered that Codeforces doesn't have a good blog on one of my favorite topics: the "divide and conquer" technique. So I want to talk about it. The outline will be something like this: 1) Divide and conquer. What this technique is and what it is for. Example. 2) Dynamic connectivity offline with divide and conquer. Divide and conquer dp optimization. 3) Let me tell you about a method I invented myself: divide and conquer by queries. In this case, we divide not only the array, but also the queries into groups. So, here we go. First, about what this technique is. The point is about the following: let's say we have an array. Then, if we know how to calculate the answer for two parts of it, and if we know how to get the answer for the whole array from the answers of two parts, we can apply the divide and conquer technique. Let me show you the si...
An array of $n$ triples of numbers is given, as well as the number $D$. Also given $q$ of queries

Полный текст и комментарии »

  • Проголосовать: нравится
  • +93
  • Проголосовать: не нравится

299.
Автор satyam343, 3 года назад, По-английски
think-cell Round 1 Editorial Thank you for your participation! I hope you liked atleast one problem from the set (: [problem:1930A] Idea: [user:satyam_343,2024-02-18] Editorial: [user:Non-origination,2024-02-18] <spoiler summary="Hint 1"> Selecting the smallest two elements on the whiteboard is a good choice in the first move. </spoiler> <spoiler summary="Solution"> Let $b$ denote the sorted array $a$. Assume that $b$ contains only distinct elements for convenience. We prove by induction on $n$ that the maximum final score is $b_1 + b_3 + \ldots + b_{2n-1}$. For the base case $n = 1$, the final and only possible score that can be achieved is $b_1$. Now let $n > 1$. **Claim**: It is optimal to choose $b_{1}$ with $b_{2}$ for some move. <spoiler summary="Proof"> Suppose that in some move, $b_{1}$ is choosen with $b_i$ and $b_{2}$ is choosen with $b_j$, for some $2 < i,j < 2n, i \not = j$. The contribution to the score according to these choices is $\min(b_{1}, b_{i}) + \min(b_{2...
$ is the largest index such that there are an equal number of $\mathtt{0} $ s and $\mathtt{1} $ s in

Полный текст и комментарии »

Разбор задач think-cell Round 1
  • Проголосовать: нравится
  • +151
  • Проголосовать: не нравится

300.
Автор halyavin, 10 лет назад, По-английски
The case of slow printf and scanf I know what is the problem ================== _Where we are going we need all the courage we can get_ When I first read the comment that our shiny new gcc 6.2 C++14 compiler has slow printf and scanf I immediately knew what I would do the next weekend. The new MinGW switched to custom implementation and I didn't need anything else to tell what the problem is. _Of course_, their format string parsing is too slow, they copy data around countless times, no file buffering is used and they have enough levels of indirection to make finding the real code feeling like a treasure hunt. What else could be the problem after all? Keeping this thoughts in mind I patiently waited for a weekend. When I finally opened MinGW source and searched for printf function, I was pleasantly surprised. The real implementation was only a couple hops away and soon enough I was looking at the heart of printf code. MinGW did try to conceal it a bit though by naming it mingw_pformat.c. But a ~100Kb source fi...
when I thought about internal buffer for ungetc for the umpteenth time. It is wastefullylarge

Полный текст и комментарии »

  • Проголосовать: нравится
  • +280
  • Проголосовать: не нравится

301.
Автор Nickolas, 15 лет назад, По-русски
Codeforces Round #105 (Div. 2): editorial So, here goes the editorial. I'll tell you right away that nobody guessed [user:MikeMirzayanov,2012-02-02]'s problem (nice disguise, er?) --- it was problem C about the picky princess. Actually, this was the first problem of the round, the rest of problems I invented to keep up the lovely topic. [problem:148A] The number of dragons D can be quite small, so the problem can be solved in a straightforward way, by iterating over dragons 1 through D and checking each dragon individually. Time complexity of such solution is O(D). [cut] There exists a smarter solution with O(1) complexity, based on inclusion-exclusion principle. You'll have to count the numbers of dragons which satisfy at least one, two, three or four of the damage conditions $N_i$, i.e., dragons who have index divisible by LCM of the corresponding sets of numbers. Remember that the number of numbers between 1 and D which are divisible by T equals $D / T$. Finally, the number of dragons that get damaged equals $N_...
method if the total number of dragons was too large for iterating over it.

Полный текст и комментарии »

Разбор задач Codeforces Round 105 (Div. 2)
  • Проголосовать: нравится
  • +47
  • Проголосовать: не нравится

302.
Автор zscoder, история, 7 лет назад, По-английски
Valentine's Day Contest 2020 Editorial I hope you enjoyed the contest! Expected problem difficulty is F < A < (G ~ D) < (C ~ E) < B (though it might be different for different people). I will mainly focus on explaining the full solution to the problems but I will briefly mention how to pass certain subtasks. ### Problem A &mdash; Leakage <spoiler summary="Solution"> This is unfortunately the most standard problem of the set. Obviously, we can model the friends as vertices and friendships as edges in an undirected graph. The problem basically asks us to answer queries of the form: "For a pair of vertices $u, v$, find the number of vertices $w \neq u, v$ such that removing $w$ from the graph disconnects $u$ and $v$". Removing vertices and disconnecting graphs should remind one of articulation points. The data structure to solve this problem is [block-cut tree](https://en.wikipedia.org/wiki/Biconnected_component#Block-cut_tree). Each biconnected component is considered as a block. An articulation point might be...
we have a target value $H$ of the number of nontrivial (area > 1) horizontal strips. We want to

Полный текст и комментарии »

Разбор задач Valentines Day Contest 2020
  • Проголосовать: нравится
  • +175
  • Проголосовать: не нравится

303.
Автор halyavin, история, 10 лет назад, По-английски
Proving Open Cup Problem. The problem D in the latest Open Cup involves function <i>f</i>(<i>n</i>) which is defined as the minimum sum of sequence <i>b</i><sub>1</sub>, ..., <i>b</i><sub><i>k</i></sub> such that any sequence <i>a</i><sub>1</sub>, ..., <i>a</i><sub><i>l</i></sub> with sum less than or equal to <i>n</i> can be dominated by some subsequence of <i>b</i>. One sequence dominates the other, if they have the same length any every element of the first sequence greater than or equal to corresponding element of the second sequence. It turns out that <i>f</i>(<i>n</i>) = <i>n</i> + <i>f</i>(<i>k</i>) + <i>f</i>(<i>n</i> &minus; 1 &minus; <i>k</i>) where <i>k</i> = [(<i>n</i> &minus; 1) / 2]. But why? If this equation still keeps you up at night, you can finally sleep well now. I have found a wonderful proof of this statement which fits the bounds of this site. <p> [cut] Two sides of the proof ================== Let us construct the <i>b</i> sequence first. For brevity, we will say that sequenc...
be the largest number such that all sequences with sum less than or equal to k are covered

Полный текст и комментарии »

  • Проголосовать: нравится
  • +169
  • Проголосовать: не нравится

304.
Автор biximo, история, 20 месяцев назад, По-английски
CP Toolkit V2 UPDATE!! <hr /> CP TOOLKIT V2 NEW UPDATE!!! ================== This new update comes PACKED with a ton of new features, which I'll list below. Newly Added Core Features ------------------------- **Graph Editor** An intuitive editor where nodes move smoothly. Build and edit graphs with drag-and-drop interaction. ![ ](https://i.imgur.com/jWjoNJa.png) **Graph Generator** Generate Trees, Cactus Graphs, Complete Graphs, Connected Graphs, Planar Graphs, Forests, and more. Perfect for creating custom test cases. ![ ](https://i.imgur.com/N0eWRmh.png) **Big Integer Calculator** Handles large integer operations with full precision. Great for number theory problems. ![ ](https://i.imgur.com/YxdeMpO.png) **Array Visualizer** Cleanly displays 1D and 2D arrays. Automatically adjusts font size and cell spacing for large arrays. ![ ](https://i.imgur.com/lWA3FPH.png) **NTT-Friendly Prime Generator** Select primes of specific length and base. Browse from a list of 320,...
**Big Integer Calculator** Handles large integer operations with full precision. Great fornumber

Полный текст и комментарии »

  • Проголосовать: нравится
  • +53
  • Проголосовать: не нравится

305.
Автор JaySharma1048576, 5 лет назад, По-английски
Codeforces Round #730 (Div. 2) Editorial #### [A: Exciting Bets](https://codeforces.me/contest/1543/problem/A) <spoiler summary="Hint 1"> $GCD(a,b)=GCD(a-b,b)$ if $a>b$ </spoiler> <spoiler summary="Hint 2"> $a-b$ does not change by applying any operation. However, $b$ can be changed arbitrarily. </spoiler> <spoiler summary="Tutorial"> If $a=b$, the fans can get an infinite amount of excitement, and we can achieve this by applying the first operation infinite times. Otherwise, the maximum excitement the fans can get is $g=\lvert a-b\rvert$ and the minimum number of moves required to achieve it is $min(a\bmod g,g-a\bmod g)$. <spoiler summary="Proof"> Without loss of generality, assume $a>b$ otherwise we can swap $a$ and $b$. We know that $GCD(a,b) = GCD(a-b,b)$. Notice that no matter how many times we apply any operation, the value of $a-b$ does not change. We can arbitrarily change the value of $b$ to a multiple of $a-b$ by applying the operations. In this way, we can achieve a $GCD$ equal to $a-b$. Now, ...
equal to $b$ or increase $b$ to the smallest multiple of $g$ greater than $b$. Thenumber of

Полный текст и комментарии »

Разбор задач Codeforces Round 730 (Div. 2)
  • Проголосовать: нравится
  • +181
  • Проголосовать: не нравится

306.
Автор Bufu, 4 месяца назад, По-английски
Codeforces Round 1115 (Div. 2) Editorial Thank you for participating in Codeforces Round 1115 (Div. 2)! We hope you enjoyed the problems. The round was prepared by [user:Bufu,2026-08-06] and [user:TomitaMatei,2026-08-06], and coordinated by [user:cry,2026-08-06]. --- #### [problem:2252A] <spoiler summary="Solution"> The boss's shield permanently activates and blocks all subsequent damage only when two cards of the exact same value are played back-to-back. Importantly, the card that actually triggers the shield still deals its normal damage. This means we want to play as many cards as possible *before* being forced to place two identical cards adjacent to each other. We should only do this on the very last card we play. Let the most frequent card in our hand have a damage value of $X$, and let its frequency be $F$. Let the number of all *other* cards be $O = n - F$. To maximize the number of $X$ cards we can play, we must use the $O$ "other" cards as separators. By placing an "other" card between ever...
$ elements overall, and find the minimum number of largest elements that sum to at least $v_k$. The

Полный текст и комментарии »

Разбор задач Codeforces Round 1115 (Div. 2)
  • Проголосовать: нравится
  • +40
  • Проголосовать: не нравится

307.
Автор Geothermal, история, 7 лет назад, По-английски
Codeforces Round #575 Solutions Hi all! As I've done several times in the past, I've written up an unofficial set of solutions to Codeforces Round 575 so that some solutions will be available before system testing completes. If my code gets hacked, I'll update the appropriate problem's solution as soon as I can. --- #A &mdash; Three Piles of Candies We claim that the answer is always $\lfloor \frac{a+b+c}{2} \rfloor$. We clearly can't do any better: if Alice and Bob could each get more candies than this, then in total, they would have more than $a+b+c$ candies, which is impossible. To prove that this is always doable, let Alice take the smallest pile and Bob take the second-smallest pile. Then, distribute enough candies from the largest pile so that Alice has as many candies as Bob (which is always possible because the largest pile must contain more candies than the difference between the other two piles). Then, distribute the remaining candies from the large pile as evenly as possible. Runtime: $O(...
number of "errors" (i.e. positions at which the original string differs from the goal string) in the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +95
  • Проголосовать: не нравится

308.
Автор EbTech, история, 7 лет назад, По-английски
How to Compete in Rust Having spent a number of Codeforces rounds practicing the ins and outs of [Rust](https://www.rust-lang.org/), I think it's finally safe to encourage wider participation in the language! This guide is intended primarily for C++ programmers who may have taken interest in Rust, but had doubts regarding its feasibility in timed contests. On Quora, [I summarized why I think Rust is suitable for contests in 2019 onward](https://www.quora.com/Would-you-prefer-Rust-for-competitive-programming/answer/Aram-Ebtekar). Granted, the learning curve is substantial enough that it may not seem that way at first. To make the transition easier, for anyone who's interested, here I'll go over some aspects of my Codeforces submissions in more detail, with some tips along the way. [My solution to 1168C: And Reachability](https://codeforces.me/contest/1168/submission/54903799) [My solution to 1158D: Winding polygonal line](https://codeforces.me/contest/1158/submission/55060881) Right away, you'll no...
- Output via `BufWriter`. This is needed for speed, if you want to write a large number of lines

Полный текст и комментарии »

  • Проголосовать: нравится
  • +112
  • Проголосовать: не нравится

309.
Автор Monogon, история, 5 лет назад, По-английски
[Tutorial] Solving Interval Problems with Geometry There are a lot of programming problems where a collection of intervals comes up, either directly or indirectly. In this tutorial, I want to present a nice way to visualize a collection of intervals, and how you can solve problems with it. An interval $[l, r]$ is just a pair of integers $l$ and $r$ such that $l\le r$. Let's make a 2D plot where the horizontal axis is $l$ and the vertical axis is $r$. Then our interval will be represented by the 2D point $(l, r)$. But an interval is more than just a pair of numbers: it describes the set of points $x$ such that $l\le x\le r$. How can we visually tell whether a number $x$ is covered by an interval? Well, we can represent it by a point $(x, x)$ in the plane. Then we can imagine that the interval's 2D point can see down and right, and the interval covers all the points it can see. Here's an example where we see how the interval $[2, 4]$ covers the points $2$, $3$, and $4$. <center> <img src="/predownloaded/60/b8/60b8b63a2b9682f...
visually tell whether a number $x$ is covered by an interval? Well, we can represent it by a point

Полный текст и комментарии »

  • Проголосовать: нравится
  • +255
  • Проголосовать: не нравится

310.
Автор TheScrasse, история, 3 года назад, По-английски
Editorial of Pinely Round 3 (Div. 1 + Div. 2) The official implementations of all the problems are [here](https://drive.google.com/file/d/1q2PHS9nJt84FRwfMoiMslQULFE4dTMU4/view?usp=sharing). <spoiler summary="Timeline of the round proposal (may contain spoilers)"> (problems D', H', etc. were not used) - Feb 19, 2022: I proposed problem D' to [contest:1654], but it was not used. - Mar 13, 2023: I invented problem A. - May 16: I invented problem H'. - May 19: I realized problem G can be solved in $O(n)$ time and we used it in the Italian team selection test for IOI. - Jul 04: I opened a Div. 1 proposal containing A, D', G, H' and other problems which are not going to be used. - Aug 09: I invented problem I, with intended solution in $O(n^3)$. - Sep 27: I invented problem C. - Oct 14: [user:errorgorn,2023-12-23] replied to my contest proposal. - Nov 02: I invented problem D''. [user:errorgorn,2023-12-23] solved problem I in $O(n^2 \log n)$. - Nov 08: I invented problems E and F. I didn't propose problem F because I th...
the number of distinct values after the operation, using $k$. Let's try $k = 2$. It works in all

Полный текст и комментарии »

Разбор задач Pinely Round 3 (Div. 1 + Div. 2)
  • Проголосовать: нравится
  • +354
  • Проголосовать: не нравится

311.
Автор wakanda-forever, 4 недели назад, По-английски
Codeforces Round 1131 (Div. 3) Editorial Thanks for participating in the round. We hope you enjoyed the problems!!! ####[problem:2278A] <div style="height:16px"></div> <spoiler summary = "Idea"> The problem requires the remaining characters in the numerator $p$ to form exactly the string `six` after completely cancelling out the denominator $q$. This means the collection of characters in $p$ must be exactly the characters in $q$ combined with the letters `s`, `i`, and `x`. Therefore, if we append the string `six` to $q$, the modified string $q$ must be an exact anagram of $p$. We can check this condition by sorting both strings and verifying if they are identical, or by comparing their character frequency counts. Time Complexity: $\mathcal{O}(n + m)$. </spoiler> <spoiler summary = "Implementation"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ int n, m; string p, q; cin >> n >> m >> p >> q; q += ...
Since the maximum frequency is at least as large as the remaining frequencies, thenumber of rounds

Полный текст и комментарии »

Разбор задач Codeforces Round 1131 (Div. 3)
  • Проголосовать: нравится
  • +46
  • Проголосовать: не нравится

312.
Автор TheScrasse, история, 5 лет назад, По-английски
[Tutorial] Product Trick Hello everyone,<br> in this tutorial we will see a trick that can be useful in combinatorics and/or DP tasks. In particular, you can use it when the statement says something similar to "the score of an array is the product of its elements, find the sum of the scores over all the possible arrays". Prerequisites: basic combinatorics and DP The trick ------------------ The trick is very simple. "The score of an array $a$ is $\prod_{i=1}^n a_i$" can be rephrased as "if there are $n$ boxes, and the $i$-th box contains $a_i$ distinguishable balls, the score of $a$ is equal to the number of ways to color a ball for each box". This is quite obvious, but it can be extremely powerful. Let's see some problems that are trivialized by this trick. [Dwango Programming Contest 6th, problem C](https://atcoder.jp/contests/dwacon6th-prelims/tasks/dwacon6th_prelims_c) (rating: 2618) ------------------ <spoiler summary="Hint 1"> You have to output the sum of the happiness over all po...
$ boxes, and the $i$-th box contains $a_i$ distinguishable balls, the score of $a$ is equal to thenumber

Полный текст и комментарии »

  • Проголосовать: нравится
  • +217
  • Проголосовать: не нравится

313.
Автор BledDest, история, 9 лет назад, перевод, По-русски
Educational Codeforces Round 38 — Editorial <spoiler summary="A. Word Correction"> Hint: When does some vowel stay in string? <spoiler summary="Solution"> Iterate over the string, output only consonants and vowels which don't have a vowel before them. [Model solution](https://pastebin.com/J0py2Gef) </spoiler> </spoiler> <spoiler summary="B. Run For Your Prize"> Hint $1$: It's never profitable to go back. No prizes left where you have already gone. <spoiler summary="Hint 2"> Hint $2$: The optimal collecting order will be: some prefix of prizes to you and the other prizes to your friend (some suffix). <spoiler summary="Solution"> You can find the total time with the knowledge of the prefix length. The final formula is $\min(a_n - 1, 10^6 - a_1, \min \limits_{i = 1}^{n - 1} (\max(a_i - 1, 10^6 - a_{i + 1})))$. [Model solution](https://pastebin.com/mKhxYUxK) </spoiler> </spoiler> </spoiler> <spoiler summary="C. Constructing Tests"> Hint: At first we will solve the problem mentioned in the statem...
with zeroes (we denote this array as $a$). $i$-th element of the array will denote somenumber in a

Полный текст и комментарии »

  • Проголосовать: нравится
  • +84
  • Проголосовать: не нравится

314.
Автор snuke, 12 лет назад, По-английски
Codeforces Round #263 Tutorial [Div2 A Appleman and Easy Task](http://codeforces.me/contest/462/problem/A) (Author: [user:wolf_sothe,2014-08-26]) This is a simple implementation problem. You can solve by searching adjacent cells of every cell. [Div2 B Appleman and Card Game](http://codeforces.me/contest/462/problem/B) (Author: [user:wolf_sothe,2014-08-26]) This is simple greedy problem, but it seemed to be reading-hard. The statement says, "Choose K cards from N cards, the score of each card is (the number of cards which has the same character in <b>K</b> cards. (not in N cards)" It is clear that this total score is (the number of 'A' in K cards)^2 + (the number of 'B' in K cards)^2 + ... + (the number of 'Z' in K cards)^2 This value will be maximized by the simple greedy algorithm, take K cards from most appearred character in N cards, the second most appearred character in N cards, and so on. [Div1 A / Div2 C Appleman and Toastman](http://codeforces.me/contest/461/problem/A) (Author: [user:ho...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +50
  • Проголосовать: не нравится

315.
Автор E869120, 9 лет назад, По-английски
A mystery of CF contribution distribution Recently, I'm interested in CF rating and contribution distribution, and I searched this.<br /> I already searched about mysteries of rating distribution ([Blog](http://codeforces.me/blog/entry/52470)), so I wrote here about contribution distribution. (Thank you for comments)<br /> <br /> **Method of Searching**<br /> <ul> <li>[Here](http://codeforces.me/top-contributed) is the leaderboard of top contributor.</li> <li>I searched the rank of contribution -51, -46, -41, -36,..., -1, 4, 9, 14,..., 164, 169, 174, 179. I searched the number of contributors too.</li> <li>Then, I make the distribution graph.</li> <li>Each range of the graph is [-inf, -50), [-50, -45), [-45, -40),... , [175, 180), [180, inf]. Each value of x-axis of the graph is the **minimum value** in range. For example, if the value of axis is 15, this means the range is [15, 20).</li> <li>The minumum value of range [-inf, -50) is _inf_, but in distribution graph this value is _-1000_.</li> </ul> <br /> Howeve...
* Obviously, the number of people who have contribution [100, 105), [105, 110), [110, 115

Полный текст и комментарии »

  • Проголосовать: нравится
  • +43
  • Проголосовать: не нравится

316.
Автор dalex, 15 лет назад, По-русски
Codeforces Beta Round 76 - Analysis <p>At first I tell about the contest at all.<br></p>My problems in the contest were A-div2,&nbsp; B-div2,&nbsp; C-div2/A-div1,&nbsp; E-div2/C-div1,&nbsp; D-div1. I wanted to make only div.2 round, but then we decided to give you seven problems at both divisions. <a class="rated-user user-admin" href="../../../profile/MikeMirzayanov" title="Штаб, MikeMirzayanov">MikeMirzayanov</a> prepared the problem about milk pouring and <a class="rated-user user-orange" href="../../../profile/anonymous" title="Майор anonymous">anonymous</a> gave E-div1 problem. Also <a class="rated-user user-admin" href="../../../profile/RAD" title="Штаб, RAD">RAD</a> gave some advices to complicate problems Azembler and Flags a bit.<br><p>And now let's start analysis.<br><br><br><b>Problem A (div.2) - Restoring Password</b><br><br>Password was very easy to restore. You should just iterate over groups of 10 characters in the first string and over all codes. Then, if some number's code is equal to the group - print t...
answer, should not go to the states where you get a number larger than $n$ or less than current

Полный текст и комментарии »

Разбор задач Codeforces Beta Round 76 (Div. 2 Only)
  • Проголосовать: нравится
  • +26
  • Проголосовать: не нравится

317.
Автор galen_colin, история, 6 лет назад, По-английски
(Another) editorial of contest (by egor.anisevich) in honor of ending of academic year and exams [Link to contest](https://codeforces.me/contestInvitation/4036ec99932a47484351d57a812de34c7a4fbb2c) [Author's editorial](https://codeforces.me/blog/entry/78650) This is a duplicate of my comment [here](https://codeforces.me/blog/entry/78415?#comment-639262). I've gotten a couple of requests to make it a blog (for some reason), so here it is. Note: this is unofficial, I was just a competitor <spoiler summary="A"> This is mostly about knowing how your language works. Division, however, gets picky. It's a good idea to **not use doubles** because they have precision issues ([read](https://codeforces.me/blog/entry/76595?locale=en)). Instead, you can use integer division, which automatically truncates (in C++, at least), possibly having to be careful with negatives in other languages. For the actual implementation, it seems like the test cases are designed so overflow won't happen and you won't have to mod with negative numbers, so the rest is simple. My submission: [subm...
$. Be careful with output (use `setprecision` with a large number of digits in C++) to make sure the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +25
  • Проголосовать: не нравится