You can use several words in query to find by all of them at the same time. In addition, if you are lucky search understands word forms and some synonyms. It supports search by title and author. Examples:

  • 305 — search for 305, most probably it will find blogs about the Round 305
  • andrew stankevich contests — search for words "andrew", "stankevich" and "contests" at the same time
  • user:mikemirzayanov title:testlib — search containing "testlib" in title by MikeMirzayanov
  • "vk cup" — use quotes to find phrase as is
  • title:educational — search in title

Results

1.
By MikeMirzayanov, history, 23 months ago, translation, In English
Предновогоднее обновление: подбор случайных задач для мэшапов Привет, Codeforces! Осталась всего пара дней до 2025 года. Напоследок в этом году залечу с обновлением &mdash; надеюсь, оно окажется полезным. Теперь в свой мэшап вы можете автоматически подбирать случайные задачи по ряду критериев и ограничений. Задачи берутся из архива, необычные задачи исключаются автоматически. Итак, нажимайте ссылку "Добавить случайные задачи" под списком задач и переходите к форме добавления. <center> <img style="zoom:75%;" src="/predownloaded/c0/ed/c0ed597ef33e0bcfdd5d7f24a473d1da873892a1.png"/> </center> Здесь можно: * исключить задачи, которые сдавали/пытались сдать/создали как авторы зарегистрированные на мэшап участники (чтобы задача была исключена, достаточно одного зарегистрированного участника, который её может знать), * если мэшап находится в группе (например, это группа ваших тренировок), то исключить все задачи из других контестов этой группы, * исключить задачи с подзадачами &mdash; такие задачи часто как-то связаны между собой и...
search, brute force) — будет выбрана задача, содержащая хотя бы один тег из списка. Названия, search, brute force): a problem containing at least one tag from the list will be selected, укажите список тегов через запятую, например, tags:dp, binary search, brute force, ., tags:dp, binary search, brute force): a problem containing at least one tag from the list

Full text and comments »

  • Vote: I like it
  • +2609
  • Vote: I do not like it

2.
By MikeMirzayanov, 3 years ago, In English
Codeforces: Results of 2023 [Annual Report] Hello, Codeforces. Let's recall 2023, shall we? In this post, I want to summarize this year. You know, a lot of terrible things happen in the world, and personally, this year was the hardest and most sorrowful for me. But today, we'll remember something else. We'll remember what this year was like for Codeforces. Recently, Codeforces turned 14 years old. Not bad, right? And for many years now, when asked "What is Codeforces?" the first thing I say is — it's a community! [cut]<br/> #### Personal Thanks! On behalf of the community (and myself), I say thank you to everyone who tries, helps, and makes efforts to keep the community alive. Thank you to the developers! Although I continue to engage in development and other technical activities, I'm glad that these guys made an effort and improved the platform: [user:geranazavr555,2024-02-04], [user:unreal.eugene,2024-02-04], [user:vbandurin,2024-02-04], [user:ChurakovaAlexandra,2024-02-04], [user:medvezhonokok,2024-02-04]...
against brute force attacks on the login page. * Several fixes in the contest proposal subsystem, micro-websites against brute force attacks on the login page. * Several fixes in the contest proposal

Full text and comments »

  • Vote: I like it
  • +1748
  • Vote: I do not like it

3.
By shiven, history, 2 years ago, In English
A summary of what passes for an Indian ICPC Contest, apparently The online round for the India’s ICPC was held on 23rd. And also a week before that. The first time around, the organisers tried debuting a self-hosted DOMjudge instance. That didn’t go too well, so a recontest was scheduled on CodeChef. If you’re not too familiar with the Indian ICPC system — this online prelims is used to select teams that can participate in the offline regionals. From a single university, usually approx. 2 teams (for the top unis) or 1 (for almost all unis that aren’t in top-15) qualify. As you could guess, it’s quite easy for good teams to miss a spot. Looking at the first contest’s rankings, teams from rank 2 to 100+ all had 4 solves. Owing to severe system issues in the first contest, the time penalties weren’t too reliable differentiators, leading to the recontest this Saturday. In hindsight, we forgot to be grateful for the problemset and reliable testcases the first time. I’m sure everyone agrees that the basic requirements (ignoring all other stuff...
^ {\log^2 N}) \approx 2^{121}$ brute force, written by the contest admin, finalised as the official, some incorrect model solution. The admin then ACed with a recursive brute-force , with the above non, . Wrong, ofc. Also works. - $O(2 ^ {\log^2 N}) \approx 2^{121}$ brute force, written by the contest, Somehow, the end result → neither does the model brute-force solution work in time, nor do the test

Full text and comments »

  • Vote: I like it
  • +925
  • Vote: I do not like it

4.
By -is-this-fft-, history, 4 years ago, In English
On "is this greedy or DP", forcing and rubber bands #### Introduction When it comes to "problem-solving techniques", there are roughly 3 levels: 1. Concrete algorithms (Kruskal's algorithm, Li-Chao tree, fast Fourier transform) 2. General patterns (dynamic programming, greedy, square-root decomposition) 3. Meta-strategies ("how do I even go about solving this problem?") There is some grey area, but in general this classification works well. [Many tutorials](https://codeforces.me/catalog) have been written about ideas that fall into 1 or 2. But very little has been written about the third category. On the catalog, I think the only blogs that really qualify are [this](62730) and [this](20548). There is also [this](92248?#comment-809401) valuable comment. As to why there is so little written, I think I can identify two reasons. - Most strong contestants don't really consciously think about these. After solving a problem with FFT, it's hard not to know you used FFT. If you used DP, even if you did it without thinki...
often brute-force and notice the pattern) but it is not what it means in general., , you can often brute-force and notice the pattern) but it is not what it means in general

Full text and comments »

  • Vote: I like it
  • +548
  • Vote: I do not like it

5.
By twosquares, 11 months ago, In English
Good Bye 2025 Editorial We'd like to thank you all for participating in the contest, and hope you enjoyed it. Any feedback would be appreciated! <!-- You lost the game. --> <spoiler summary="Rate the contest"> - Great contest: - Good contest: - Average contest: - Bad contest: </spoiler> --- <spoiler summary="Did Franklin (from problem D) succeed in massacring a village of innocent elves like Frieren and Dilhan (from problem E)?"> The official lore is that he got lost in a forest of oddly colored Christmas trees (from problem F) and decided instead to write this editorial. </spoiler> <!-- ########### --> <!-- #PROBLEM A# --> <!-- ########### --> <h2>[problem:2178A]</h2> <spoiler summary="Did you like the problem?"> - Great problem: - Good problem: - Average problem: - Bad problem: - Did not solve: ...
We can brute force over all possible subsets of the smaller bipartite

Full text and comments »

Tutorial of Good Bye 2025
Tags sus
  • Vote: I like it
  • +697
  • Vote: I do not like it

6.
By Dominater069, 2 years ago, In English
Analyzing how good O1-Mini actually is I would like to thank [user:redpanda,2024-09-13] and [user:qmk,2024-09-13] for their great help in writing and reviewing this blog. They are also the users who queried O1-mini for all the following problems. We tried O1-mini on several problems, from a variety of sources. Let's list the results first. **Note** : - Some of the WA verdicts here actually means that the AI just "stopped thinking" which means the AI thought for a long enough time without any useable results so it ran into an error. - All ratings mentioned are Codeforces ratings, the Atcoder ratings have been converted to codeforces rating. To measure the approximate codeforces rating of the atcoder problems mentioned here, you can use https://kenkoooo.com/atcoder/#/table/ + https://silverfoxxxy.github.io/rating-converter. <h4> D2ABs </h4> - [problem:1762B] [<a class="rated-user user-gray" title="Gray">1100</a>] <a class="rated-user user-green" title="Green AC">AC</a> - [problem:1998B] [<a class="rated-...
like $min(a, b)$, it gets there by brute forcing., Problems requiring some thinking which can't be easily replaced by brute -forcing solutions is the

Full text and comments »

  • Vote: I like it
  • +583
  • Vote: I do not like it

7.
By YouKn0wWho, 4 years ago, In English
[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...
brute force.

Full text and comments »

  • Vote: I like it
  • +634
  • Vote: I do not like it

8.
By maomao90, 2 years ago, In English
Meta Hacker Cup... Why must you be so special?? _Disclaimer: This is a rant about Meta Hacker Cup and may not contain any useful information._ Meta Hacker Cup is one of the biggest annual programming competitions, but it has the strangest submission format, unlike any other online judge. Why does it have to be so different? Let’s take a look at how Meta Hacker Cup 2024 Round 1 went for [user:maomao90,2024-10-06] > The time now is 1:00 AM in Singapore. The contest starts, and maomao90 begins solving the problems. > The time now is 1:41 AM. maomao90 has solved problems A, B, and C without much trouble and starts working on problem D. After quickly coming up with a theoretical solution, maomao90 begins coding. > The time now is 2:05 AM. The code is ready and passes the sample tests. maomao90 proceeds to validate the solution. > The time now is 2:06 AM. Validation passes, and the input zip file is downloaded. > The time now is 2:07 AM. maomao90 runs the code on the final test. ![Image showing assertion failed](https...
If it’s intentional, what's the goal? To make participants suffer? Brute-force algorithms often

Full text and comments »

  • Vote: I like it
  • +510
  • Vote: I do not like it

9.
By maomao90, history, 5 years ago, In English
Tutorial on SIMD vectorisation to speed up brute force I decided to write a blog on this as I was doing a problem on our local judge and I decided to try to speed up my brute force code. However, it was quite difficult to find resources on SIMD vectorisation, so I decided to try to compile some of the resources I found to hopefully allow more people to learn <s>to scam brute force solutions</s> Thanks to ~iloveioi,2022-01-02 and ~jamessngg,2022-01-02 for proofreading. Introduction ================== SIMD stands for single instruction, multiple data. SIMD allows us to give vector instructions which will allow the code to run faster. Vector instructions are instructions that handle short (length 2-16) vectors of integers / floats / characters in a parallel way by making use of the extra bits of space to do operations simultaneously. The most common form of vectorisation is making use of pragmas such as ~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") ~~~~~ This form of vecto...
Tutorial on SIMD vectorisation to speed up brute force, setters to code these SIMD solutions to make sure that brute force doesn't pass or if the problem, to speed up my brute force code. However, it was quite difficult to find resources on SIMD

Full text and comments »

  • Vote: I like it
  • +277
  • Vote: I do not like it

10.
By kpw29, 6 years ago, In English
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....
$ neighboring occurrences of $D$ to search for the optimal interval. We can generalize thebrute-force, , we can simply brute-force this pair with partial sums $(D,V)$ in $O(n)$.

Full text and comments »

  • Vote: I like it
  • +515
  • Vote: I do not like it

11.
By Monogon, history, 6 years ago, In English
Efficient 3D Convex Hull Tutorial _Warning: The following contains graphic depictions of geometry, precision errors, and degenerate cases. Viewer discretion is advised._ ### Prerequisites I assume the reader is familiar with: - 2D Convex Hulls - 3D Vector Operations (dot and cross products) ### Introduction Recall that in the 2D convex hull problem, you are given a set of 2D points, and you must compute the smallest convex polygon containing all the given points. By convex, we mean that for any two points $A$ and $B$ inside the polygon, the entire line segment $AB$ is also inside the polygon. The problem in 3D is completely analogous. You are given $n$ 3D points, and you must compute the smallest convex polyhedron containing all the given points. Similarly, a polyhedron is convex if for any two points $A$ and $B$ inside the polyhedron, the line segment $AB$ is also inside the polyhedron. In the 2D case, it is more obvious what the output is. We can simply output a circular list of vertices on the ...
examining the brute force case, we learned how to perform the most fundamental operation in any 3D convex, ### Brute Force Algorithm in $O(n^4)$

Full text and comments »

  • Vote: I like it
  • +393
  • Vote: I do not like it

12.
By Zhtluo, history, 3 years ago, In English
All You Need is Randomly Guessing — How to Improve at Codeforces I hope [my previous blog](https://codeforces.me/blog/entry/126310) has convinced you that the best way to improve at Codeforces is to be more Russian, i.e. to improve your math capability. Unfortunately, humble mortals such as you and I are not gifted with the talent that esteemed Russian grandmasters such as 74TrAkToR had: _Surely, it is beneficial to have a code reference for many algorithms and data structures, but I also think that just superficially knowing the algorithm and maybe having implemented it once or twice before is sufficient to use it without a reference?_ _&mdash; Some other Codeforces grandmaster_ Therefore, in this blog I will explore the dark side of Russian-ness &mdash; randomly guessing &mdash; that is forsaken by every Russian grandmaster of the light side I know. However, it has been very helpful to me, and I hope that it serves you well, too. ## Example 1 I will start by using an example to demonstrate my thought process. This problem [1923C](h...
conclusion based on a body of observations. In CP this means to brute-force small cases and do some pattern

Full text and comments »

  • Vote: I like it
  • +431
  • Vote: I do not like it

13.
By -Morass-, history, 9 years ago, In English
Problem Topics Good Day to you! I've been asked to make some topic-wise list of problems I've solved. Even though I couldn't involve all problems, I've tried to involve at least "few" problems at each topic I thought up (I'm sorry if I forgot about something "easy"). I've alredy made such list once anyway I've tried to include more problems now &mdash; so here it is: <spoiler summary="aho"> http://www.spoj.com/problems/ADAJOBS/ URI 2226 (5) //[NICE][NUMBERS][DP] http://www.spoj.com/problems/SUB_PROB/en/ http://codeforces.me/contest/696/problem/D 8 http://www.spoj.com/problems/AHOCUR/ 5 //Aho-Corassic + DP https://www.codechef.com/problems/LYRC (5) //Sample aho-brute-force http://codeforces.me/problemset/problem/346/B //Proposed by [user:bradyawn,2019-08-03] </spoiler> <spoiler summary="automat"> 6861 [LA] //CYK UVA 10679 //Suffix Automat http://www.spoj.com/problems/STRMATCH/ //Suffix Automat &mdash; trie might do too http://www.spoj.com/problems/NSUBST...

Full text and comments »

  • Vote: I like it
  • +428
  • Vote: I do not like it

14.
By ninja_28, history, 6 years ago, In English
CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial [problem:1498A] ================== #### [**Video Editorial**](https://www.youtube.com/watch?v=lV5cb8wh3sE) **Author and Problemsetting:** [user:ninja_28,2021-03-29] **Editorialist:** [user:sigma_g,2021-03-29] <spoiler summary="Hint"> Can you think of the simplest properties that relate a number and its sum of digits? </spoiler> <spoiler summary="Hint 2"> Note that if $X$ is a multiple of 3, then **both** $X$ as well as the sum of digits of $X$ are a multiple of 3! Can you put this property to use here? </spoiler> <spoiler summary="Hint 3"> If $X$ is a multiple of 3, then $\texttt{gcd-sum}(X) \ge 3$. Therefore, we are guaranteed that at least every third number will satisfy the constraints required by our problem $(\texttt{gcd-sum}(X) > 1)$. </spoiler> <spoiler summary="Solution"> Therefore, for the input $n$, we can simply check which one of $n$, $n+1$, and $n+2$ has its gcd-sum $> 1$, and print the lowest of them. </spoiler> <spoi...
Let us take an example. We have some, Observe if we can reduce our search space, We can actually stop our search as soon as, We have a brute force $\mathcal{O}(N\cdot M^2)$ solution.

Full text and comments »

  • Vote: I like it
  • +419
  • Vote: I do not like it

15.
By Endagorion, history, 6 years ago, In English
Codeforces Global Round 8: editorial Thank you for waiting! I hope you've enjoyed the problems. Let me know what you think in the comments! **UPD**: I almost forgot but here are some notes, as well as challenges for all problems. For a lot of them I don't have a solution and would be happy to hear your ideas. [tutorial:1368A] <spoiler summary="Challenge (awful)"> Find a closed formula for the answer. For simplicity assume $a \leq b$, </spoiler> [tutorial:1368B] <spoiler summary="Challenge (?)"> As mentioned above, the problem is not that easy in general case when there are a lot of repeated letters. Still, is it possible to do? Any solution faster than brute-force would be interesting, or even some ideas or observations. </spoiler> <spoiler summary="Notes"> I find it much harder to create a good easy problem than a good hard problem. This position in paricular gave me a lot of trouble, we had to scratch three or four other versions. Not to say the result is very inspiring, but the previous ones were...
brute-force would be interesting, or even some ideas or observations.

Full text and comments »

  • Vote: I like it
  • +335
  • Vote: I do not like it

16.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Graph Algorithms Welcome to the new episode of [user:PrinceOfPersia,2015-01-31] presents: Fun with algorithms ;) You can find all the definitions here in the book "Introduction to graph theory", Douglas.B West. [cut] Important graph algorithms : DFS --- The most useful graph algorithms are search algorithms. DFS (Depth First Search) is one of them. While running DFS, we assign colors to the vertices (initially white). Algorithm itself is really simple : ~~~~~ dfs (v): color[v] = gray for u in adj[v]: if color[u] == white then dfs(u) color[v] = black ~~~~~ Black color here is not used, but you can use it sometimes. Time complexity : $O(n + m)$. #### DFS tree DFS tree is a rooted tree that is built like this : ~~~~~ let T be a new tree dfs (v): color[v] = gray for u in adj[v]: if color[u] == white then dfs(u) and par[u] = v (in T) ...
**One) Brute force $$**

Full text and comments »

  • Vote: I like it
  • +355
  • Vote: I do not like it

17.
By galen_colin, 3 years ago, In English
fix problem ratings pls (the rainboy effect) [The first few paragraphs of this blog, above the first spoiler, are just for story purposes and are irrelevant to the problem statement] One fateful day, a naive and young version of me from about 5 days ago had a dream. A dream to stop being so terrified of hard problems. A dream to conquer the most challenging stuff that CF ever had to offer. A dream to... ok, enough of that, that's so stupid. Basically, I've been grinding 3500s lately, mostly for fun (and my god, has it been fun). Two days prior, I found myself solving [1919G](https://codeforces.me/contest/1919/problem/G). That went fine, but after getting it, I noticed that despite G being 3500, it wasn't even the hardest problem in the contest &mdash; that honor went to the next problem, [1919H](https://codeforces.me/contest/1919/problem/H) (the subject of this blog), which had **no solves in-contest**. I concluded that I would have to be insane to try that, and moved on to other problems. Well, yesterday, I decided I...
longer to debug them than the short time I spent writing the brute-force)., (A secret tip — you can even use brute-force checking as a substitute for proving your, -400 lines of logic-heavy meat for each one, because I took an extra 3-5 minutes to write abrute-force

Full text and comments »

  • Vote: I like it
  • +360
  • Vote: I do not like it

18.
By TheScrasse, history, 6 years ago, In English
Editorial of Codeforces Round #701 (Div. 2) [problem:1485A] Author: [user:TheScrasse,2021-02-07]<br> Preparation: [user:MyK_00L,2021-02-07] <spoiler summary="Hint 1"> Suppose that you can use $x$ operations of type $1$ and $y$ operations of type $2$. Try to reorder the operations in such a way that $a$ becomes the minimum possible. </spoiler> <spoiler summary="Hint 2"> You should use operations of type $2$ first, then moves of type $1$. How many operations do you need in the worst case? ($a = 10^9$, $b = 1$) </spoiler> <spoiler summary="Hint 3"> You need at most $30$ operations. Iterate over the number of operations of type $2$. </spoiler> <spoiler summary="Solution"> Notice how it is never better to increase $b$ after dividing ($\lfloor \frac{a}{b+1} \rfloor \le \lfloor \frac{a}{b} \rfloor$). So we can try to increase $b$ to a certain value and then divide $a$ by $b$ until it is $0$. Being careful as not to do this with $b<2$, the number of times we divide is going to be $O(\log a)$. In particular, i...
Brute force doesn't work (even if you optimize it): there are

Full text and comments »

  • Vote: I like it
  • +263
  • Vote: I do not like it

19.
By snowysecret, 5 years ago, In English
Editorial for Codeforces Round #761 (Div. 2) Thanks for participating, hope you enjoyed the problems! Implementations for the problems are chosen randomly among testers, and I made some changes to their codes (for example, deleted meaningless comment lines). Please do not hesitate to provide feedback in the comments, so I can improve in setting problems next time. **UPD**: Sorry but there is a checker bug in problem E. All submissions of problem E will be rejudged soon. **UPD2:** Rejudge done, the round remains rated. <spoiler summary="Statistics"> Number of FST for rated participants: - Problem A: $29$ - Problem B: $90$ - Problem C: $12$ - Problem D1: $4$ - Problem D2: $0$ - Problem E: $6$ Number of AK: $22$ Number of clarifications: $85$ </spoiler> [problem:1617A] <spoiler summary="Hint"> When is the lexicographically smallest permutation of $S$ (i.e. the sorted string) not the answer? </spoiler> <spoiler summary="Solution"> If there are no occurrences of `a`, `b` or `c` in $S$, ...
Solution 1: Brute force from $a = 2, 3, 4, \dots$ and calculate the value of $b$ ($b = n - a - 1

Full text and comments »

  • Vote: I like it
  • +425
  • Vote: I do not like it

20.
By purplesyringa, history, 5 years ago, In English
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...
Prior to that, it is reasonable to analyze polynomial hash functions via brute force for a moment.

Full text and comments »

  • Vote: I like it
  • +308
  • Vote: I do not like it

21.
By Sammarize, 12 years ago, translation, In English
Way of problemsetter *The mystery of creating rounds unveiled by author of the 4 of them! The guide for preparing the round without horror-fiction and pastorals!* Thanks for [user:RodionGork,2014-06-13], who push me to writing this post and thanks for [user:lucAbalo,2014-06-13], who push [user:RodionGork,2014-06-13] to pushing me to writing this post. Also, many thanks to [user:RodionGork,2014-06-13] for the translation of this post to English. ##1. Inventing problems It's hard to advise anything on this point. There's no some standard way of creating problems &mdash; and if one have existed we'll have only "complicated algorithmic exercises" instead of "problems". People who participated in Russian Code Cup do know well the tasks of that sort. To cook good and interesting problem there should be some **idea!** which came to your mind (and later to minds of participants of the contest). Even the simplest problems of `A` level for the `Div2` should have some **idea**. So here is the war...
It is important to care of writing tasks and tests in such a way that optimized brute-force will

Full text and comments »

  • Vote: I like it
  • +458
  • Vote: I do not like it

22.
By antontrygubO_o, 7 years ago, In English
Background of Good Bye 2019 Hi there! The recent Good Bye 2019 was very important event for us, and thanks for all the positive feedback we got, especially from [user:Radewoosh,2020-01-01]! As a follow-up, we would like to share some background on its preparation. ### **Problems:** **A**: This one was the hardest to come up with. We wanted it to be super easy but still to include some idea, and this is like the $10$th version of the problem. **B**: Initially there was another problem at this position. However, it turned out to be too hard for B (one orange couldn’t do it during the testing), and people didn’t like it in general, so we came up with another task. **C**: Funny, but we didn’t know that it’s always possible to make array good with adding at most $1$ element before the contest. **D**: This problem was created just 3 days before the contest to make it more balanced :O. We are glad that the contest did turn out to be well-balanced. **E**: Initially we wanted this problem to be at positi...
**F**: This problem caused a lot of troubles because we wanted to cut $n^2$ brute force solution

Full text and comments »

  • Vote: I like it
  • +374
  • Vote: I do not like it

23.
By arvindf232, history, 2 years ago, In English
How might LGMs cheat using current AI. Or, are these not cheating? Disclaimer: My natural English ability is questionable. I have passed the blog through chatgpt to correct grammatical mistakes. I experimented with o1-mini and tried to understand its implications for competitive programming on Codeforces at level 2500 or higher. Obviously, the current AI cannot outright provide you with solutions; however, there are already ways it can help quite a lot. ### Brute Force Writing I believe most competitors regularly use brute-forces. They are kind of an admission of failure to find your mistakes on your own. Previously, brute-forces came with the cost of taking 5 minutes to write. I would not do it unless it is a very hard problem, or I have tried debugging by hand for 10 minutes and seen nothing. If AI usage is assumed, then these 5 minutes would be completely saved. Five minutes would correspond to approximately a 10 performance rating if on the final problem and increasingly more on earlier problems. ### Translations of Languages Thi...
### Brute Force Writing I believe most competitors regularly use brute-forces. They are kind of an

Full text and comments »

  • Vote: I like it
  • +218
  • Vote: I do not like it

24.
By Phantasmagorias, history, 5 years ago, In English
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...
this solution. For the trains of $x+y>\sqrt m$, we can modify every period by brute force because

Full text and comments »

  • Vote: I like it
  • +799
  • Vote: I do not like it

25.
By Dormi, history, 5 years ago, In English
Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial [problem:1534A] Author: [user:Crackersamdjam,2021-06-13] <spoiler summary="Hint 1"> Let's say you know the colour of the first square, what colours can you figure out next? </spoiler> <spoiler summary="Hint 2"> Colour it like a chessboard, but there's more than one possible chessboard! </spoiler> <spoiler summary="Hint 3"> Brute force the color of the first square! </spoiler> <spoiler summary="Tutorial"> [tutorial:1534A] </spoiler> <spoiler summary="Solution"> [submission:119400830] </spoiler> [problem:1534B] Author: [user:Dormi,2021-06-13] <spoiler summary="Hint 1"> Consider the contribution of each pillar to the answer. </spoiler> <spoiler summary="Hint 2"> How does doing the operation on a pillar change the contribution to the answer? </spoiler> <spoiler summary="Hint 3"> You only want to do an operation on a pillar if the top cell contributes 2 to the answer. </spoiler> <spoiler summary="Tutorial"> [tutorial:1534B] </spoiler> ...
Brute force the color of the first square!

Full text and comments »

  • Vote: I like it
  • +314
  • Vote: I do not like it

26.
By fchirica, 13 years ago, In English
Codeforces Round #225 — Editorial [problem:384A] ================== Usually, when you don’t have any idea how to approach a problem, a good try is to take some small examples. So let’s see how it looks for N = 1, 2, 3, 4 and 5. With C I noted the coder and with * I noted an empty cell. ![ ](http://s28.postimg.org/8z1d7k399/New_Bitmap_Image.png) By now you should note that answer is N ^ 2 / 2 when N is even and (N ^ 2 + 1) / 2 when N is odd. Good. Generally, after you find a possible solution by taking examples, you need to prove it, then you can code it. In order to proof it, one needs to do following steps: 1/ prove you can always build a solution having N ^ 2 / 2 (or (N ^ 2 + 1) / 2) pieces. 2/ prove that N ^ 2 / 2 (or (N ^ 2 + 1) / 2) is maximal number – no other bigger solution can be obtained. For proof 1/ imagine you do coloring like in a chess table. ![ ](http://s27.postimg.org/ysqhphx0z/New_Bitmap_Image.png) The key observation is that by placing all coders on black squares of tab...
1/ and 2/ are done brute force, like in second subproblem (the only difference is we choose 3, Implemented brute force, you get O(1) per update and O(N) per query. However, these both are

Full text and comments »

  • Vote: I like it
  • +418
  • Vote: I do not like it

27.
By huangzirui, history, 4 years ago, In English
Editorial of Codeforces Round 796 [problem:1688A] Idea: [user:huangzirui,2022-06-03]. Solution: [user:huangzirui,2022-06-03]. Preparation: [user:huangzirui,2022-06-03]. Good problem Average problem Bad problem Did not solve <spoiler summary="Hint"> Consider $x=2^k$ and $x\ne 2^k$ separately. </spoiler> <spoiler summary="Solution"> Let $p_i$ be the $i$-th bit of $x$, $q_i$ be the $i$-th bit of $y$ (both indexed from $0$). $x\ \texttt{and}\ y > 0\Leftrightarrow \exists i,\ p_i= q_i = 1$. $x\ \texttt{xor}\ y > 0\Leftrightarrow \exists i,\ p_i\ne q_i$. To satisfy the first condition, find the minimum integer $k$ satisfying $p_k=1$, and assign $1$ to $q_k$. If $x\ne 2^k$, the second condition is satisfied now. Otherwise, find the minimum integer $j$ satisfying $p_j=0$, and assign $1$ to $q_j$. The time complexity is $O(1)$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include<bits/stdC++.h> ...
We wrote a brute force program, and it runs more than 2 seconds on polygon. However, many

Full text and comments »

  • Vote: I like it
  • +276
  • Vote: I do not like it

28.
By zscoder, history, 4 years ago, In English
[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...
By brute forcing all fractions with numerator and denominator

Full text and comments »

  • Vote: I like it
  • +308
  • Vote: I do not like it

29.
By Error_Yuan, 15 months ago, In English
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...
Brute force to find the optimal value of $N$ and $B$. , We can use brute force to find suitable values for $N$ and $B$. In the main correct solution, we

Full text and comments »

  • Vote: I like it
  • +218
  • Vote: I do not like it

30.
By kostia244, 7 years ago, In English
Tricks Which Will Increase Your Rating! Hello Codeforces! I got some interesting tricks to share with you. ### 1. a_i := (a_i + x)%mod Range Updates, Max Range Queries Apply usual range addition, but after each update run the following code: ```cpp void normalize(int l, int r) { while(getmax(l, r).max >= mod) { set(getmax(l, r).pos, getmax(l, r).max%mod); } } ``` What is the complexity of this code? We all know that each time we %%=mod$ number which is $\geqslant mod$ it halves, that means each number will be updated $O(log)$ times, we will perform $O(n\cdot\log{n}\cdot\log{a})$ operations in total. So each update will be $O(\log{n}\cdot\log{a})$ amortized! ### 2. $O(\log^2{\log{n}})$ Segment Tree Segment tree queries are queries on path. Instead of doing them in the usual brute force-ish way we can use HLD! Since maximum path length is $2\cdot\log{n}$, thus operations are now operations are $O(\log^2{\log{n}})$, which is better than $O(\log{n})$. ### 3. Faster Dinic's We know t...
Segment tree queries are queries on path. Instead of doing them in the usual brute force-ish way we

Full text and comments »

  • Vote: I like it
  • +429
  • Vote: I do not like it

31.
By box, history, 6 years ago, In English
[Tutorial] Square root decomposition and applications A brief introduction into the applications of square root decomposition ================== Square root decomposition is the process of separating a structure of size $O(N)$ into $O(\sqrt{N})$ "blocks" of size $O(\sqrt{N})$ each, in a way that aids manipulation of the entire structure. Square root decomposition is extremely versatile. Some of its most well-known use cases are: - answering queries on a static array, with methods such as Mo's algorithm or block precomputation - "lazy" brute force modifications, where it is easy to query an entire block, but tag pushing isn't obvious - separating objects based on a threshold, when there exists both an $O(x)$ algorithm and an $O(n/x)$ algorithm In this tutorial we will walk through multiple types of square root decomposition. Answering queries on a static array, offline (Mo's algorithm) --- Consider a problem where we are asked to find the answer for certain intervals $[l,r]$. We can't quickly compute the answer for an ar...
- "lazy" brute force modifications, where it is easy to query an entire block, but tag pushing, is no brute force changes, for each block it will take a total of $O(B\log B)$ time, because, ridiculously high initialization constant for Mo's it might be better to run brute force when queries or, ### Optimizing brute force: [problem:911G], When a node has a pretty small amount of children, we can answer the queries withbrute force, as, brute force.

Full text and comments »

  • Vote: I like it
  • +272
  • Vote: I do not like it

32.
By Kevin114514, history, 4 years ago, In English
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...
, otherwise, brute force the whole set $S'$ and find the elements appearing the most times. For the, Hint: Consider a brute force dynamic programming solution and try to optimize it.

Full text and comments »

  • Vote: I like it
  • +74
  • Vote: I do not like it

33.
By errorgorn, history, 6 years ago, In English
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...
$111$. We can use brute force to find the answer to all values less than or equal to $1099$ and, $. Then $X=(A+C \cdot 111) \cdot 11 + D \cdot 111$. So we can just brute force all $11$ value of $D

Full text and comments »

  • Vote: I like it
  • +199
  • Vote: I do not like it

34.
By ko_osaga, history, 4 years ago, In English
SMAWK algorithm as an alternative for D&C optimization Yesterday I participated in a local contest involving a problem about Monge arrays. I could've wrote some d&c optimization, but I got bored of typing it so I copypasted [user:maroonrk,2023-01-01]'s SMAWK implementation to solve it. Today, I somehow got curious about the actual algorithm, so here it goes. ## 1. Definition I assume that the reader is aware of the concept of D&C Optimization and Monge arrays. The goal of SMAWK is to compute the row optima (ex. row minima or maxima...) in a $n \times m$ **totally monotone** matrix. By *totally monotone*, it means the following: **Def: Monotone.** The matrix is monotone if the position of row optima is non-decreasing. **Def: Totally Monotone (TM).** The matrix is totally monotone if every $2 \times 2$ submatrix is monotone. Totally monotone matrices are monotone (proof easy but nontrivial), but not vice versa. The latter is a stronger condition. Note that Divide and Conquer Optimization works on a monotone matrix, therefore ...
the optimal position for row $i$. We have $opt(2k-1) \le opt(2k) \le opt(2k+1)$, sobrute-force all

Full text and comments »

  • Vote: I like it
  • +152
  • Vote: I do not like it

35.
By errorgorn, 6 years ago, In English
Codeforces Global Round 13 Editorial [problem:1491A] ------------------ Setter: [user:syksykCCC,2021-02-28] Prepared by: [user:syksykCCC,2021-02-28] <spoiler summary="Hint 1"> How can we find the largest $k$ such that the $k$-th smallest element of the array is $0$? </spoiler> <spoiler summary="Hint 2"> How can we maintain $k$? </spoiler> <spoiler summary="Solution"> Let's define $cnt$ to represent the number of 1s in the array. For the modifications, if $a_i$ is already $1$ now, then we let $cnt \gets cnt - 1$. Otherwise, let $cnt \gets cnt + 1$. For the querys, just compare $cnt$ with $k$. If $cnt \ge k$, the answer will be $1$. Otherwise, the answer will be $0$. The complexity : $O(n + q)$. </spoiler> <spoiler summary="Code (C++)"> ```c++ #include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n, q, a[N], cnt; int main() { scanf("%d%d",&n,&q); for(int i = 1; i <= n; ++i) { scanf("%d",a+i); cnt += a[i]; } while(q--) { int opt, x; ...
In terms of implementation, we can run the first $2n$ by brute force

Full text and comments »

  • Vote: I like it
  • +255
  • Vote: I do not like it

36.
By kingofnumbers, history, 10 years ago, In English
Steps to perform well on codeforces contest _note: this is just sarcastic blog_ Here are the steps to follow in order to perform well in codeforces contests: **1- Have a fast internet connection:** codeforces servers might be heavily loaded and be down, but during the down period the server might be up for short moments, and if you have fast connection you can catch theses moments and get chance to open the problems or submit your solution, also when you finsh coding a solution in the last minute you need fast connection to quickly submit **2- read all the old problems on codeforces:** admins nowadays allow problems to be repeated or to be very similar to some old problem (or at least they don't take care to avoid that), so if you read all problems on codeforces (you don't have to solve them) you can know that a problem is repeated and copy/paste one of the solutions of the old problem, you might take some time to find the old problem but it can still be less time than to solve it. **3- practice your googling skill...
to write brute force solution as mentioned in previous step, **6- try out brute force solutions before the contest end:** it is very often that a contest

Full text and comments »

  • Vote: I like it
  • +226
  • Vote: I do not like it

37.
By Vladithur, history, 4 years ago, In English
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, Try to brute force for $k < 50$. Do you see anything suspicious

Full text and comments »

  • Vote: I like it
  • +237
  • Vote: I do not like it

38.
By EvenImage, 12 years ago, In English
Codeforces Round #268 Editorial I'll upload my example solutions and will post links to them as soon as it becomes possible. All the problems in Div 1 don't have the unique solution. I list several solutions to each problems. There are also some interesting bonus problems. I can't solve some of them yet :( If you have interesting ideas, feel free to share and discuss your ideas in the comments. :) My English is poor, so if there are some mistakes or something you can't understand, you can also discuss it in the comments. [problem:469A] [I Wanna Be the Guy](http://kayin.moe/iwbtg/downloads.php) is an interesting game. I strongly recommend it to you. The problem itself is easy. Just check if all the levels could be passed by Little X or Little Y. [submission:7894174] [problem:469B] This problem is not hard. Just iterator over all possible $t$, and check if the schedule of Little X and Little Z will overlap. [submission:7894252] **Bonus:** 1. $p,q\leq 50, l,r\leq 10^9$ 2. $p,q,l,r\leq 1...
hand or brute forces.

Full text and comments »

  • Vote: I like it
  • +124
  • Vote: I do not like it

39.
By AquaMoon, 3 years ago, In English
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 ...
Now that we have a brute force algorithm for $O (n^2 \log A)$, how can we optimize it?

Full text and comments »

  • Vote: I like it
  • +201
  • Vote: I do not like it

40.
By Wind_Eagle, history, 5 years ago, translation, In English
Where the author of the contest came up entertaining. Cheating cheaters. Hello, Codeforces! A month ago I have wrote [my blog about cheaters](https://codeforces.me/blog/entry/94300). Under that blog, a number of suggestions have accumulated, and there is a number of interesting ideas that could be applied to sabotage a group of cheaters. I've often seen comments along the lines of: <spoiler summary="Pictures">. <a href="https://imgbb.com/"><img src="https://i.ibb.co/r65zfTL/cheat1.png" alt="pic1" border="0"></a> <a href="https://imgbb.com/"><img src="https://i.ibb.co/Yh6ZfY8/cheat2.png" alt="pic2" border="0"></a> </spoiler> Well, doing what [user:Ari,2021-09-28] suggested wasn't really what I wanted to do, but it was worth checking out what would happen if the wrong solutions were sent. I asked some famous user what would happen if I sent the wrong solutions to cheaters. He told me that someone had done this before and that he was quickly debunked. I wondered whether I could cheat cheaters without getting caught. But for this, I had to do so...
a brute-force solution on E2, which obviously didn't work.

Full text and comments »

  • Vote: I like it
  • +526
  • Vote: I do not like it

41.
By caterpillow, 2 years ago, In English
Build Your Own Treap! Hallo codeforcers, As some of you may know, the almighty treap is one of the most versatile data structures out there. It can serve as an ordered + indexed set, a lazy segment tree, and even a dynamic array — all at the same time. However, its immense versatility comes at a cost: there are so many different variations that making a one-template-fits-all is impossible. Alas, is fate such that we must write it from scratch — every, single, time? Fear no more! I present to you [BYOT: Build your own treap!](https://caterpillow.github.io/byot) Now, you can summon a hand-crafted treap to overkill your Div2D in mere _seconds_. Gone are the days of using your brain to come up with a clever solution — just go to the site, click on what you need, and enjoy your AC! To see how it is used, you can see some example implementations below. If you find any bugged configurations or have any suggestions, please leave a comment under this blog. Be warned, no rating refunds will be issued...
- union (brute force), Instead of writing a clever solution, I simply brute forced the range of strongly recommended

Full text and comments »

  • Vote: I like it
  • +248
  • Vote: I do not like it

42.
By Monogon, history, 5 years ago, In English
[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...
$ will be above it. So we don't need to check all the previous intervals by brute force: just remember

Full text and comments »

  • Vote: I like it
  • +255
  • Vote: I do not like it

43.
By null_awe, 2 years ago, In English
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...
Because we only need to use option $2$ once, we can brute force where we use that operation and

Full text and comments »

  • Vote: I like it
  • +294
  • Vote: I do not like it

44.
By Endagorion, 12 years ago, In English
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...
representation for all numbers up to $n$, or even a brute-force recursive solution (which is not guaranteed to

Full text and comments »

Tutorial of Codeforces Round 300
  • Vote: I like it
  • +312
  • Vote: I do not like it

45.
By ecnerwala, 11 years ago, In English
8VC Venture Cup 2016 — Final Round Editorial ###[problem:635A] We can iterate over each possible rectangle and count the number of violists enclosed. This can be optimized with rectangular prefix sums, though the simple brute force is sufficient for this problem. Runtime: $O(n^6)$ ###[problem:634A] Notice that, as we move the empty pedestal around the circle, we cyclically permute the statues (and the empty pedestal can be anywhere). Thus, we can reach one state from another if and only if, after removing the empty pedestal, they are cyclic shifts of each other. The starting and ending configurations are permutations, so we can check this in linear time. Runtime: $O(n)$ ###[problem:627A] For any two integers $a$ and $b$, we have $s = a + b = (a \oplus b) + (a \& b) * 2$, where $a \oplus b$ is the xor and $a \& b$ is the bitwise AND. This is because $\oplus$ is non-carrying binary addition. Thus, we can find $a \& b = (s - x) / 2$ (if this is not an integer, there are no solutions). Now, for each bit, we ha...
optimized with rectangular prefix sums, though the simple brute force is sufficient for this problem.

Full text and comments »

  • Vote: I like it
  • +113
  • Vote: I do not like it

46.
By wuhudsm, history, 2 years ago, In English
TheForces Round #37 (Brute-Forces1) Editorial [A: Niimmm](https://codeforces.me/gym/105491/problem/A) Idea:[user:yugandhar_master,2024-03-14] First solve:[user:lonely_forever,2024-11-07] <spoiler summary="tags"> `brute force` `dp` `math` </spoiler> <spoiler summary="solution"> If Bob is winning for given $n$ stones then Alice will win for $n + 2$ stones and $n + 3$ stones, because in $n + 2$ case Alice will remove $2$ stones and in $n + 3$ case Alice will remove $3$ stones resulting in $n$ stones where players switch their turns i.e., now Bob will play like first player for these $n$ stones, so obviously Alice will win. From this information we can create $dp$ table, where $dp[x]$ refers who will win if pile contains $x$ stones. The base case is for $n = 1$ where Bob will win. So from this $dp$ table , if Alice is already winning no need to add stones , otherwise we will iterate untill we reach the state where Alice will win. If we observe the pattern, it will look like `LWWWLLWWWLLWWWLLWWWLL...` where...
TheForces Round #37 (Brute-Forces1) Editorial, `brute force` `dp` `math`

Full text and comments »

  • Vote: I like it
  • +21
  • Vote: I do not like it

47.
By Noble_Mushtak, history, 4 years ago, In English
Every Technique and Algorithm I Used to Become Grandmaster Hi everyone, I became grandmaster today so I decided to go down memory lane and review every problem I have ever done in a CodeForces contest to look back and see every technique and algorithm I had to use to become a grandmaster. I am not sure how useful this is, I mostly think it's fun to look at all the old solutions I wrote and how different it was from how I write code now. The main takeaway is that, as many people have said before, you don't need to know or memorize a bunch of advanced algorithms to become grandmaster. As you will see, there are many problems where I just used "ad hoc reasoning," meaning there's not a standard technique I used to solve the problem and you just need to make some clever mathematical observations to solve the problem. Also, there are many popular algorithms that I have never needed in a CodeForces contest despite being a grandmaster: - Sparse tables, Fenwick trees, and segment trees - String algos, like rolling hashes, Knuth-Morris-Pratt, suffix...
- [Problem B](https://codeforces.me/contest/1194/submission/57028169): Brute force and row/column, - [Problem C](https://codeforces.me/contest/1633/submission/144680927): Brute force - [Problem D](https, - [Problem A](https://codeforces.me/contest/1151/submission/52961256): Brute force - [Problem B, - [Problem A](https://codeforces.me/contest/699/submission/19235692): Brute force - [Problem B

Full text and comments »

  • Vote: I like it
  • +213
  • Vote: I do not like it

48.
By awang11, history, 9 months ago, In English
Codeforces Round 1085 (Div. 1 + Div. 2) Editorial <center> <table class="tex-tabular bordertable" style="border-left: none; border-right: none; border-top: 1px solid; border-bottom: 1px solid; border-collapse: collapse;"> <tbody> <tr> <td class="tex-tabular-text-align-center" style="border-left: none; border-right: none; border-top: none; border-bottom: none;"> <span class="tex-font-size-small"> <span class="tex-font-style-it"> <a href="https://www.youtube.com/watch?v=HCYKLnT0UNU">Trophy Presentations — Asuka Ota, Ryo Nagamatsu, Mario Kart Wii</a> </span> </span> </td> </tr> </tbody> </table> </center> **UPD 1:** added hints, problem credits, more specific acknowledgements and some remarks. Implementations are on the way, sorry for making y'all wait! **UPD 2:** Implementations are finally here. [problem:2207A] Author: [user:awang11,2026-03-09] Preparers: [user:awang11,2026-03-09], [user:IceSerpent,2026-03-09] Anal...
Brute force.

Full text and comments »

  • Vote: I like it
  • +146
  • Vote: I do not like it

49.
By Laakeri, history, 7 years ago, In English
On Multidimensional Range Queries The following question is frequently asked in Codeforces ([46390](https://codeforces.me/blog/entry/46390), [45157](https://codeforces.me/blog/entry/45157), [11324](https://codeforces.me/blog/entry/11324)): _Is there a 2D segment tree that supports range addition and range minimum?_ In this blog post I give evidence that such a data structure does not exist, or if it did exist it would not generalize to higher dimensions. In particular I show that if for all $d$ a $d$-dimensional data structure that performs such queries in $O(polylog(N))$ time did exist, then the [exponential time hypothesis](https://en.wikipedia.org/wiki/Exponential_time_hypothesis) would fail. Such a data structure exists for range addition and range sum, so this is a non-trivial claim separating the hardness of these problems. ## Update 2021: A paper " Algorithms and Hardness for Multidimensional Range Updates and Queries" in ITCS 2021 by Joshua Lau and Angus Ritossa ([https://arxiv.org/abs/2101.02003](https:...
of $x_{v_1}, \ldots, x_{v_k}$, and know if the clause is satisfied or not. We brute force over all

Full text and comments »

  • Vote: I like it
  • +397
  • Vote: I do not like it

50.
By Endagorion, history, 9 years ago, In English
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 ...
you can't prove but have to confirm, a good idea is to _stress test_ it: implement abrute-force

Full text and comments »

  • Vote: I like it
  • +255
  • Vote: I do not like it

51.
By Xiaohuba, 13 months ago, In English
Codeforces Global Round 30 Editorial ## A Sequence Game Idea from [user:cmk666,2025-11-06], Prepared by [user:cmk666,2025-11-06] <spoiler summary="Hint 1"> Think some straightforward necessary conditions. They are also sufficient. </spoiler> <spoiler summary="Tutorial"> [tutorial:2164A] </spoiler> ## B Even Modulo Pair Idea from [user:244mhq,2025-11-06], Prepared by [user:NetSpeed1,2025-11-06] <spoiler summary="Hint 1"> Consider a brute force solution. What's the actual complexity of it? </spoiler> <spoiler summary="Tutorial"> [tutorial:2164B] </spoiler> ## C Dungeon Idea from [user:Link_Cut_qwq,2025-11-06], Prepared by [user:Xiaohuba,2025-11-06] <spoiler summary="Hint 1"> If you gain a new sword after killing a monster, its damage will be greater or equal than the previous sword. </spoiler> <spoiler summary="Hint 2"> When will we attempt to kill monsters with $c_i = 0$? </spoiler> <spoiler summary="Hint 3"> Consider a greedy approach. </spoiler> <spoiler summ...
Consider a brute force solution. What's the actual complexity of it

Full text and comments »

  • Vote: I like it
  • +176
  • Vote: I do not like it

52.
By zscoder, history, 7 years ago, In English
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...
For subtask $1$, brute forcing all possible paths work. For subtask, Subtask 1 can be solved by brute forcing which vertices to delete and Subtask 2 can be solved with, Subtask 1 can be solved with pure brute force. There exists a $O(N\log{N} + Q\log^{2}N)$ solution

Full text and comments »

  • Vote: I like it
  • +175
  • Vote: I do not like it

53.
By Flamire, history, 2 years ago, In English
EPIC Institute of Technology Round August 2024 (Div. 1 + Div. 2) Editorial [2002A &mdash; Distanced Coloring](https://codeforces.me/contest/2002/problem/A) idea & solution: [user:xcyle,2024-08-12] <spoiler summary="Hint 1"> Consider the case with $n=m=k$. </spoiler> <spoiler summary="Hint 2"> Generalize the solution for all $n,m,k$. </spoiler> <spoiler summary="Tutorial"> It can be shown that for any $k\times k$ subgrid, the colors we use must be pairwise distinct. Thus, we have an lower bound of $\min(n,k)\cdot\min(m,k)$. We can show that this lower bound is indeed achievable by coloring the upper-left $\min(n,k)\cdot\min(m,k)$ subgrid with distinct colors, and copy-pasting it to fill the rest of the grid. Time complexity: $O(1)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int t, n, m, k; int main() { scanf("%d", &t); while (t--) { scanf("%d%d%d", &n, &m, &k); printf("%d\n", min(n, k)*min(m, k)); } return 0; } ~~~~~ </spoiler> [2...
by $n-p$ and $n-q$. We just need to run any brute force solution (dfs with memorization or dp) on, . Brute force runs very fast on $n=18$, which forced us to increase constraints., Instead of hashmaps, you can also insert all $S$ and $T$'s into a trie, and run abrute force dfs

Full text and comments »

  • Vote: I like it
  • +125
  • Vote: I do not like it

54.
By Errichto, 11 years ago, In English
Codeforces Round #318 [RussianCodeCup Thanks-Round] Editorial [Div2B &mdash; Bear and Three Musketeers](http://codeforces.me/contest/574/problem/B) Warriors are vertices and "knowing each other" is an edge. We want to find connected triple of vertices with the lowest sum of degrees (and print $sum-6$ because we don't want to count edges from one chosen vertex to another). Brute force is $O(n^3)$. We iterate over all triples $a,b,c$ and consider them as musketeers. They must be connected by edges (they must know each other). If they are, then we consider sum of their degrees. We must notice that there is low limit for number of edges. So instead of iterating over triples of vertices we can iterate over edges and then iterate over third vertex. It gives us $O(n^2 + n m)$ and it's intended solution. To check if third vertex is connected with other two, you should additionally store edges in 2D adjacency matrix. It's also possible to write it by adding "if" in right place in brute forces to get $O(n^2 + nm)$. Check it out in [cod...
Brute force is $O(n^3)$. We iterate over all triples $a,b,c$ and consider them as musketeers, It's also possible to write it by adding "if" in right place in brute forces to get $O(n^2 + nm

Full text and comments »

  • Vote: I like it
  • +57
  • Vote: I do not like it

55.
By mohammedehab2002, 8 years ago, In English
Codeforces round #525 editorial [problem:1088A] --------------- Well, the constraints allow a brute-force solution, but here's an $O(1)$ solution: If $x=1$, there's no solution. Otherwise, just print $x-x\%2$ and 2. Code link: https://pastebin.com/LXvuX8Ez Time complexity: $O(1)$. [problem:1088B] --------------- Let $s$ be the set of numbers in input (sorted and distinct). In the $i^{th}$ step, $s_i$ is subtracted from all bigger or equal elements, and all smaller elements are 0. Thus, the answer in the $i^{th}$ step is $s_i-s_{i-1}$ ($s_0=0$). Code link: https://pastebin.com/bpz1YxBe Time complexity: $O(nlog(n))$. [problem:1088C] --------------- The editorial uses 0-indexing. Both solutions make $a_i=i$. #### First solution, n adds and 1 mod First, let's make $a_i=x*n+i$ (for some $x$). Then, let's mod the whole array with $n$ (making $a_i=i$). If the "add update" changed one index, we can just add $i+n-a_i\%n$ to index $i$. The problem is, if we make $a_i=x*n+i$, then updat...
Well, the constraints allow a brute-force solution, but here's an $O(1)$ solution:

Full text and comments »

  • Vote: I like it
  • +116
  • Vote: I do not like it

56.
By misteg168, history, 14 months ago, In English
Codeforces Global Round 29 Editorial Thanks everybody for participating in the round! ### [A. Shortest Increasing Path](https://codeforces.me/contest/2147/problem/A) Author: [user:BernatP,2025-09-20] Preparation: [user:BernatP,2025-09-20] <spoiler summary="Hint1"> How big can the answer be? </spoiler> <spoiler summary="Hint2"> Which coordinates can you reach in $2$ or $3$ moves? </spoiler> <spoiler summary="Solution"> [tutorial:2147A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> #define endl '\n' using namespace std; #define int long long signed main(){ ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--){ int x,y; cin>>x>>y; if(x==y || x==y+1 || y==1)cout<<-1<<endl; else if(x<y)cout<<2<<endl; else cout<<3<<endl; } } ~~~~~ </spoiler> ### [B. Multiple Construction](https://codeforces.me/contest/2147/problem/B) Author: [user:danx,2025-09-20] Preparation: [user:danx,2025-09-20] <spoiler summary="Hint1"> Don't over comp...
answer is $1$ by brute force.

Full text and comments »

  • Vote: I like it
  • +195
  • Vote: I do not like it

57.
By wuhudsm, 3 years ago, In English
Codeforces Round 930 (Div. 1, Div. 2) Editorial Thank you for participation and we hope you enjoy this round :) #### [D2A &mdash; Shuffle Party](https://codeforces.me/contest/1937/problem/A) Idea : [user:chromate00,2023-08-27] <spoiler summary="Hint (for thinkers)"> If you think in terms of $k$, it might be hard to find the solution. Maybe it will be helpful if you fix $d$ and find the $k$ which will be swapped with $d$. </spoiler> <spoiler summary="Hint (for observers)"> Try bruteforcing for, say, $n \le 20$. Do you see a pattern? </spoiler> <spoiler summary="Tutorial"> On $n=1$, the answer is trivially $1$. On $n=2$, index $1$ and $2$ are swapped. The answer is therefore $2$. For $n>2$, let us assume the element $1$ is on index $a$ and it will be swapped with index $k$. Then, $a$ must be $k/2$. We will prove this by contradiction. Let us assume that there is no divisor greater than $a$, and $a$ is lesser than $k/2$. But then, as $a$ is a multiple of $2$ in the base condition, $k$ must be a multiple of $2...
If we brute force to construct the graph, the time complexity will be $O(n^2m)$, which is

Full text and comments »

  • Vote: I like it
  • +192
  • Vote: I do not like it

58.
By errorgorn, 5 years ago, In English
On Div2ABs 2 years ago, [user:antontrygubO_o,2022-04-27] wrote [a blog](https://codeforces.me/blog/entry/75163) about div2ABs where he expressed his opinions that d2ABs should not be about "here is a statement, please implement what is written there". Thanks to him, the quality of d2ABs (and problem quality in general) have certainly improved. However, I still believe that there still quite large differences between how coordinators/problemsetters view d2ABs and how the intended participants view them. From the survey made by [user:kpw29,2022-04-27], we can see that most people agree that most people agree that we should **primarily** consider the target audience when proposing a task. I too think if a task is boring to div 1 contestants, we should not think of that as a reason to immediately disqualify a problem from being a d2A. ![ ](https://codeforces.me/predownloaded/70/b5/70b515da85a4dc3b362cf4eb0963dbd1fb642819.png) I think when people judge the interesting-ness of d2As, they try...
just brute force and checking certain conditions that are easy enough to think about (e.g. what are, only cover simple topics like math, brute force, and simulation, they allow any beginner cper to

Full text and comments »

  • Vote: I like it
  • +330
  • Vote: I do not like it

59.
By BrayanD, history, 5 years ago, In English
Editorial of Codeforces Round #768 ### [problem:1631A] Author: [user:humbertoyusta,2022-01-27] <spoiler summary="Hint 1"> Think about how $max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$ will contribute to the answer. </spoiler> <spoiler summary="Hint 2"> The maximum of one array is always $max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$. How should you minimize then? </spoiler> <spoiler summary="Solution"> Let $m_1 = \max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$. The answer will always be $m_1 \cdot m_2$ where $m_2$ is the maximum of the array that does not contain $m_1$. Since $m_1$ is fixed, the problem can be reduced to minimize $m_2$, that is, minimize the maximum of the array that does not contain the global maximum. WLOG assume that the global maximum will be in the array $b$, we can swap elements at each index $x$ such that $a_x > b_x$, ending with $a_i \leq b_i$ for all $i$. It can be shown that the maximum of array $a$ is minimized in this way. Time complexity: $O(n)$ <spoiler ...
and it worked quickly for $n \geq 16$, the case $n \leq 8$ can be handled with brute force., with brute force.

Full text and comments »

  • Vote: I like it
  • +246
  • Vote: I do not like it

60.
By henotrix, 15 months ago, In English
Codeforces Round 1045 (Div. 2) Editorial Unfortunately, the round turns out to be very unbalanced :( I'm deeply sorry about this issue. I hope you still enjoy the problems. <spoiler summary="Rate the contest! (definitely not copied from past contests)"> <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:2134A] <spoiler summary="Hint 1"> Check the parity of numbers $a$, $b$, and $n$. </spoiler> <spoiler summary="Solution"> Let us first consider the $b$ blue cells. Since all $b$ cells appear in the final painting, for the coloring to be symmetric, they must be placed at the middle of the grid...
Brute force over the number of runs of the binary string. Find the

Full text and comments »

  • Vote: I like it
  • +199
  • Vote: I do not like it

61.
By zscoder, history, 6 years ago, In English
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!)...
. one solution uses the numbers $528,952,971,972,999$). You can write a simple brute force and run

Full text and comments »

  • Vote: I like it
  • +247
  • Vote: I do not like it

62.
By szdytom, 4 months ago, In English
Codeforces Round 1113 (Div. 2) Editorial [problem:2248A] <spoiler summary="Hint1"> Alice deletes a `0`, Bob deletes a `1`. Which occurrence should each of them choose? </spoiler> <spoiler summary="Hint2"> Deleting a `0` makes the string lexicographically larger. Does the position of that `0` matter? </spoiler> <spoiler summary="Hint3"> After Alice's move, Bob sees one string and deletes a `1`. What is his best move? </spoiler> <spoiler summary="Solution"> Deleting a `0` at an earlier position is always better for Alice. Indeed, compare deleting the `0`s at positions $i < j$: the two results agree before position $i$, and at position $i$ the first result has `1` while the second still has `0`. So Alice deletes the **first** `0`. After that, Bob wants to minimize the string. By the symmetric argument he deletes the **first** `1` of the remaining string, which is the first `1` of the original string, since deleting a `0` never changes the order of the `1`s. Hence the answer is the original string with it...
```cpp #include using namespace std;

Full text and comments »

  • Vote: I like it
  • +154
  • Vote: I do not like it

63.
By Radewoosh, history, 11 years ago, In English
VK Cup 2016 — Round 3 — Editorial Editorial was created by [user:Errichto,2016-05-07], but he said that he has enough contribution, so I'm posting it for you. ;) #1 [problem:673A] (invented by [user:GlebsHP,2016-05-07] &mdash; thanks!) You are supposed to implement what is described in the statement. When you read numbers $t_i$, check if two consecutive numbers differ by more than $15$ (i.e. $t_i - t_{i-1} > 15$). If yes then you should print $t_{i-1}+15$. You can assume that $t_0 = 0$ and then you don't have to care about some corner case at the beginning. Also, you can assume that $t_{n+1} = 91$ or $t_{n+1} = 90$ (both should work &mdash; do you see why?). If your program haven't found two consecutive numbers different by more than $15$ then print $90$. If you still have problems to solve this problem then check codes of other participants. [submission:18286606] #2 [problem:673B] (invented by [user:Errichto,2016-05-07]) Some prefix of problems must belong to one division, and the remaining suf...
You may wonder why there was $2^{32}$ instead of $10^9+7$. It was to fight with making thebrute

Full text and comments »

Tutorial of VK Cup 2016 - Round 3
  • Vote: I like it
  • +109
  • Vote: I do not like it

64.
By wuhudsm, history, 20 months ago, In English
TheForces Round #41 (Magical-Forces) Editorial [A](https://codeforces.me/gym/105805/problem/A) Idea:[user:imranakki,2025-01-23], [user:wuhudsm,2025-01-23] <spoiler summary="solution"> Let $x = n \times k + r$, where $r$ is the remainder when $x$ is divided by $n$ ($r < n$). $x + $ $(x$ $mod$ $n)$ $= n \times k + r + r = n \times k + 2 \times r = n$ First case: $k = 0$ $2 \times r = n$, $r$ must be an integer, so we have $+1$ solution if $n$ is even. Second case: $k = 1$ $n + 2 \times r = n$, $\Rightarrow r = 0$, here we have $+1$ solution for every $n$. In general: If $n$ is even, we have $2$ solutions. If $n$ is odd, we have only $1$ solution. </spoiler> <spoiler summary="code(C++)"> ```cpp #include <bits/stdc++.h> using namespace std; #define ll long long #define fast \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0); int main(){ fast; ll t; cin>>t; while(t--){ ll n; cin>>n; ...
it with brute force., we can just do brute force.

Full text and comments »

  • Vote: I like it
  • +19
  • Vote: I do not like it

65.
By cyand1317, history, 8 years ago, In English
Codeforces Round #487 (Div. 2) Editorial Selamat petang! The curtain has fallen on [contest:989]. Have you enjoyed the problems themselves? Or the stories? Or both? Neither? I hadn't ever intended to create a hard contest, believe me... (╥﹏╥) The author will try to find ways to estimate the difficulty better in the future. Also, stronger pretests, notes taken. Anyways, hope you've all enjoyed the challenges you've faced, and gained something from this round. Congratulations to those who performed well, and commiserations to those waiting for their next chance to shine (^_−)−☆ Below are the tutorials of all problems. Feel free to point out mistakes (if any) or share your ideas in the comments! I might be overcomplicating or confusing something > < [tutorial:989A] <spoiler summary="Short Ruby solution"> ~~~~~ puts gets.codepoints.each_cons(3).any?{|x,y,z|x*y*z==287430}?'Yes':'No' ~~~~~ </spoiler> [tutorial:989B] <spoiler summary="Noam's C++ solution"> ~~~~~ #include <bits/stdc++.h> #define endl '\...
~~~~~ #include #include

Full text and comments »

  • Vote: I like it
  • +144
  • Vote: I do not like it

66.
By Error_Yuan, history, 2 years ago, In English
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...
unintended brute force), [user:jiangly,2024-11-09] at 02:55:12 (intended, orz!)

Full text and comments »

  • Vote: I like it
  • +136
  • Vote: I do not like it

67.
By awang11, 23 months ago, In English
Codeforces Round 996 (Div. 2) Editorial Hope you enjoyed the problems! **UPD 1:** Added implementations! **UPD 2:** It seems my wording for the solution to C is not the best, and it is causing some confusion. I've updated it to be better! **UPD 3:** Implementation links didn't work for some reason, so I've just added the code directly. [problem:2055A] <spoiler summary="Hint 1"> Look at the distance between the frogs. </spoiler> <spoiler summary="Solution"> Notice that regardless of how the players move, the difference between the numbers of the lilypads the two players are standing on always alternates even and odd, depending on the starting configuration. Then, the key observation is that exactly one player has the following winning strategy: * Walk towards the other player, and do not stop until they are forced onto lilypad $1$ or $n$. For instance, if Alice and Bob start on lilypads with the same parity, Bob cannot stop Alice from advancing towards him. This is because at the start of Alice's ...
// brute force section // polynomial division bool ok = 1

Full text and comments »

  • Vote: I like it
  • +142
  • Vote: I do not like it

68.
By darkshadows, history, 11 years ago, In English
DP on Trees Tutorial A certain question on Quora and some junior asking about DP on Trees is what inspired this post. Its been a long time since I wrote any tutorial, so, its a welcome break from monotonicity of events. Pre-requisites: - Will to read this post thoroughly. :) - Also, you should know basic dynamic programming, the optimal substructure property and memoisation. - Trees(basic DFS, subtree definition, children etc.) Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follow the optimal substructure. We all know of various problems using DP like subset sum, knapsack, coin change etc. We can also use DP on trees to solve some specific problems. We define functions for nodes of the trees, which we calculate recursively based on children of a nodes. One of the states in our DP usually is a node $i$, denoting that we are solving for the subtree of node $i$. As we do examples, things will get clear for you. ...
(v)$ is dependent on where we root the tree. If we do a brute force, it'll be $O(N^2)$. We need

Full text and comments »

  • Vote: I like it
  • +251
  • Vote: I do not like it

69.
By ChthollyNotaSeniorious, history, 4 years ago, In English
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...
$S$ in brute force. Every time we do ‘Repeat’, we take out all the numbers larger than $tot$, then

Full text and comments »

70.
By NemanjaSo2005, 3 years ago, In English
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] ...
If $|y|$ is small, we can just brute force it. Otherwise, we can transform it into a query on the, If a query involves a small number of elements, we can just brute force it. Otherwise, we do the

Full text and comments »

  • Vote: I like it
  • +103
  • Vote: I do not like it

71.
By wangmarui, history, 11 months ago, In English
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...
RE, MLE? greedy, dp? natural time? map, umap? giveup rating, get score. brute force, right

Full text and comments »

Tutorial of Hello 2026
  • Vote: I like it
  • +146
  • Vote: I do not like it

72.
By balbit, history, 5 years ago, In English
Let's Solve Some More Hard Problems! Inspired by ivan100sic's [problem list blog](https://codeforces.me/blog/entry/98630), I'll pick 10 nontrivial-seeming recent POI (Polish Olympiad in Informatics) problems that I haven't solved and track my progress here. It seems to me that POI is better suited for this format as their editorials are quite difficult to find (if possible [at all](https://szkopul.edu.pl/problemset/problem/v2Y2_UW56ENMcbwP22tkTb7a/site/?key=statement)). While Ivan's original challenge was supposed to last an entire year, I'm not nearly as patient, so I won't look for editorials only until February 1st (in just over 2 weeks). Hopefully I'll have completed at least 80% by that time. Until then, GLHF!!! The List: 1. [Multidrink 2013](https://szkopul.edu.pl/problemset/problem/GyDCbdIgFY5FsMa9iIsBl3hf/site/?key=statement) [Solved Jan 15] <spoiler summary="Fun-ness:"> 5/10 <spoiler summary="Comments"> My thought process on this problem went like "ew this is disgusting implementation" => ...

Full text and comments »

Tags pow, odz, eni, abh, ai
  • Vote: I like it
  • +149
  • Vote: I do not like it

73.
By ODT, history, 9 years ago, In English
Codeforces Round #449 Editorial [897A &mdash; Scarborough Fair](http://codeforces.me/contest/897/problem/A) By [user:mcfx,2017-12-04] For every $i$ in range $[l,r]$, if $c_i$ is $c_1$ then change it into $c_2$... Because $n, m$ are all very small, $O( nm )$ can easily pass it. PS. You can use binary search tree to solve it in $O( m\log n )$ time. [897B &mdash; Chtholly's request](http://codeforces.me/contest/897/problem/B) By [user:mcfx,2017-12-04] The $k$-th smallest zcy number is $conn(str(k),rev(str(k)))$, where $str$ denotes the decimal representation of a positive integer as a string, $conn$ denotes the concatenation two strings, and $rev$ denotes the reverse of a string. Then go over the smallest $k$ such numbers and sum them up to obtain the answer. [896A &mdash; Nephren gives a riddle](http://codeforces.me/contest/896/problem/A) By [user:mcfx,2017-12-04] $f(n)=str_1+f(n-1)+str_2+f(n-1)+str_3$. First we can compute the length of $f(n)$ for all possible $n$. For a pair of $(n...
But on codeforces, this can optimize brute force algorithm from 5600ms to about 2500ms..., I'm really sorry for letting the brute force algorithm pass the tests..., The most naive brute forces uses about 8000ms to 9000ms, I added some tricks and the fastest can, }{2} \rceil +1$, precisely, and use binary search or brute force to complete the "finding" process.

Full text and comments »

  • Vote: I like it
  • +180
  • Vote: I do not like it

74.
By wuhudsm, history, 2 years ago, In English
TheForces Round #34 (ABC-Forces) Editorial [A An OK Problem](https://mirror.codeforces.com/gym/105350/problem/A) Idea:[user:Binary_Thinker,2024-03-14] Preparer:[user:Ahmed_Jamal_Sultan,2024-09-17] <spoiler summary="solution"> We can observe that "O" and "K" do not "interlock" with each other. So this problem is just finding two disjoint $4 \times 3$ sub-grids. Using brute force is enough. Bonus: solve the problem when $n,m \le 10^3$. </spoiler> <spoiler summary="code(C++)"> ~~~~~ #include <bits/stdc++.h> using namespace std; #define int long long void solve() { int n, m; cin >> n >> m; int ans = 0; for (int i = 0; i < n-3; i++) { for (int j = 0; j < m-2; j++) { for (int i2 = 0; i2 < n-3; i2++) { for (int j2 = 0; j2 < m-2; j2++) { if (min(i, i2) + 3 < max(i, i2) || min(j, j2) + 2 < max(j, j2)) { ans++; } } } } } cout << ans << "\n";...
. So this problem is just finding two disjoint $4 \times 3$ sub-grids. Using brute force is enough.

Full text and comments »

  • Vote: I like it
  • +31
  • Vote: I do not like it

75.
By Geothermal, history, 7 years ago, In English
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...
and checking consecutive numbers to see if they have difference $1$ or in $O(N^2)$ bybrute-forcing, difference. Alternatively, since the bound on $n$ is fairly low, we can just brute-force all pairs of, This problem falls to a brute-force approach. Clearly, the solution must differ from the first

Full text and comments »

  • Vote: I like it
  • +109
  • Vote: I do not like it

76.
By Nisiyama_Suzune, 9 years ago, In English
[Tutorial] Math note — Möbius inversion If you've ever taken some lessons on competitive programming, chances are that you have already heard about one of the most famous formula: the Möbius inversion. This article is aimed to provide some basic insight on what is the Möbius inversion, as well as how to apply it in various programming tasks. Prequisite ================== If you are not familiar with the linear sieve and multiplicative functions, it is recommended that you read about them first [here](http://codeforces.me/blog/entry/54090). I will introduce some frequently used notations and lemmas first. Notation ------------------ 1. $[P]$ refers to the boolean expression, i.e. $[P]=1$ when $P$ is true, and $0$ otherwise. 2. $\lfloor x \rfloor$ refers to rounding $x$ down to the nearest integer. Thus $\lfloor \frac{q}{p} \rfloor$ refers to the integer division. 3. $d|n$ means that d can divide n (without a remainder). The following functions are all multiplicative functions, where $p$ is a prime numbe...
, if we compute the sum above with brute force, the overall complexity will be $O(n \log n)$.

Full text and comments »

  • Vote: I like it
  • +202
  • Vote: I do not like it

77.
By Edvard, history, 11 years ago, translation, In English
Editorial of Educational Codeforces Round 11 ### [problem:660A] The problem was suggested by Ali Ibrahim [user:New_Horizons,2016-04-09]. Note that we should insert some number between any adjacent not co-prime elements. On other hand we always can insert the number $1$. <spoiler summary="С++ solution"> ~~~~~ const int N = 1010; int n, a[N]; bool read() { if (!(cin >> n)) return false; forn(i, n) assert(scanf("%d", &a[i]) == 1); return true; } void solve() { function<int(int, int)> gcd = [&](int a, int b) { return !a ? b : gcd(b % a, a); }; vector<int> ans; forn(i, n) { ans.pb(a[i]); if (i + 1 < n && gcd(a[i], a[i + 1]) > 1) ans.pb(1); } cout << sz(ans) - n << endl; forn(i, sz(ans)) { if (i) putchar(' '); printf("%d", ans[i]); } puts(""); } ~~~~~ </spoiler> Complexity: $O(nlogn)$. ### [problem:660B] The problem was suggested by Srikanth Bhat [user:srikkbhat,2016-04-09]. In this problem you should simply do what was written in the problem sta...

Full text and comments »

  • Vote: I like it
  • +32
  • Vote: I do not like it

78.
By GlowCheese, 2 years ago, In English
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'...
However, as $k$ is increased to $10^{12}$ we cannot brute-force the same way as the previous

Full text and comments »

  • Vote: I like it
  • +218
  • Vote: I do not like it

79.
By Serval, 20 months ago, In English
Codeforces Round #1011 (Div. 2) Editorial <spoiler summary="Fun Fact 0"> [Attention is all you need](https://arxiv.org/abs/1706.03762). </spoiler> <spoiler summary="Fun Fact 1"> The current problems are the original A A B C D E, respectively. </spoiler> <spoiler summary="Fun Fact 2"> The idea for problem D came up after eating at Sushiro, and the idea for problem E came up after eating at McDonald's. However, Sushiro is not a buffet restaurant. :( </spoiler> <spoiler summary="Fun Fact 3"> The intended solutions are short. </spoiler> <spoiler summary="Fun Fact 4"> Some (very) strong testers couldn't solve E when testing, and that's why we gave E so much score. </spoiler> <spoiler summary="Fun Fact suggested by testers"> ![...](/predownloaded/61/a0/61a03f0e26b325e41dd12a2aa483b30b9e9e7c30.png) </spoiler> #### [problem:2085A] <spoiler summary="Hint 1"> When $s$ is lexicographically equal to or greater than the reversal of $s$, is it possible to make $s$ *universal* by performing the operations? ...
solved by brute force.

Full text and comments »

  • Vote: I like it
  • +156
  • Vote: I do not like it

80.
By Proofy, 16 months ago, In English
[Tutorial] Bitmasks and sets are two sides of the same coin ### **Prescript** This is a beginner concept that I think many people know but I haven't seen written explicitly anywhere, and I have explained it before multiple times to many people asking me "where can I learn more about bitmasks and bitwise operations?" I haven't seen this explained anywhere so that I can refer them to this resource. Hence, I'm writing about it myself. The techniques in this blog are very intuitive and simple to the extent that you can wonder "why are we even talking about this?" But I do often find it very useful to state something explicitly (and formally), because sometimes intuition can be misleading if not held accountable and made explicit. Throughout the blog, I try to make the concepts as easy to read as possible while also not eliminating formality. So, I keep the more formal writings enclosed inside spoiler blocks <spoiler summary="like this one"> I am a spoiler block, I contain the formal jargon. </spoiler> which you can feel free to ...
2. Submasks and supermasks and brute force over subsets, This means that if we have an array of $n \leqslant 20$ elements, then we can brute force the

Full text and comments »

  • Vote: I like it
  • +104
  • Vote: I do not like it

81.
By Sersawy, history, 12 months ago, In English
[Tutorial] Monotonic Stack Optimization for "Last-Segment" DP I recently encountered several problems that looked like standard $O(N^2)$ Dynamic Programming but required a faster solution. I noticed a recurring theme: using **Monotonic Stack** to optimize transitions dependent on range statistics (like min/max/GCD). Sometimes these problems can also be solved using the convex hull trick, but the stack-based approach is often much simpler. However, not all "Monotone Stack DPs" are the same. Sometimes we use the stack to optimize the **transition loop**, and other times we use it to optimize the **input array itself**. In this post, I will explain the intuition behind these two distinct patterns. ----- ## Pattern 1: Optimizing the Transition **Target:** Problems where the cost function behaves like a "Step Function." ### The Problem We are dealing with a 1D DP recurrence of the form: $$dp[i] = \min_{0 \le j < i} \{ dp[j] + \text{cost}(j+1 \dots i) \}$$ Where $\text{cost}(j+1 \dots i)$ depends on a range statistic (e.g., ...
// 3. Brute force stack (size ~ sqrt(A)) dp[i] = INF; for(auto& [val, cost] : st) { dp[i

Full text and comments »

  • Vote: I like it
  • +197
  • Vote: I do not like it

82.
By _istil, 2 years ago, In English
Good Bye 2024: 2025 is NEAR Editorial Thank you for participating in this round! Problems A and G are authored by [user: Cocoly1990,2024-11-23] and the rest by me. Currently, I'm not sure if the editorials are fine enough. Please feel free to tell me where I can improve. <spoiler summary=" Rating Predictions"> | | A | B | C | D | E | F | G | H | I | | :--------------------------------: | :--: | :---------: | :--: | :----------: | :--: | :--: | :----------: | :--: | :----------: | | [user:wyrqwq,2024-12-20] | 800 | 1200 | 1400 | 1700 | 1900 | 2500 | [2800, 3300] | 3200 | [800, 3000] | | [user:Cocoly1990,2024-12-20] | 800 | 1300 | | | | | 3000 | | | | [user:TheScrasse,2024-12-20] | 800 | 1200 | ? | 1800 | | 2500 | 3000 | 3000 | 3500 | | [user:LMydd0225,2024-12-20] | 800 | ...
Is your brute forces actually faster (maybe you can explain it by, Next, let's accelerate the process of filling in short strings. The hack for brute-force filling

Full text and comments »

  • Vote: I like it
  • +59
  • Vote: I do not like it

83.
By flamestorm, 5 years ago, In English
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...
characters are $\texttt{<}$ and $\texttt{>}$. In this case, there is a brute- force solution that swaps, or trivialized by brute force, but I think brute forcing is an important skill to have (especially, Brute force small $n$ and find a pattern. , Therefore, the intended solution goes as follows: write a brute force for small $n$ ($n \leq 30, This runs in $\mathcal{O}(n\sqrt{n})$ per test case if you lazily brute force, or $\mathcal{O}(n, brute force the three triangular numbers and find the answer for each $n$.

Full text and comments »

  • Vote: I like it
  • +100
  • Vote: I do not like it

84.
By Lewin, 9 years ago, In English
Good Bye 2017 Editorial Here's the editorial. Hope you have a happy new year! Code can be found here: https://www.dropbox.com/sh/i9cxj44tvv5pqvn/AACQs7LLNyTZT-Gt_AMf7UQFa?dl=0 <spoiler summary="New Year and Counting Cards"> Let's start off a bit more abstractly. We would like to know if the statement "if P then Q" is true, where P and Q are some statements (in this case, P is "card has vowel", and Q is "card has even number"). To do determine this, we need to flip over any cards which could be counter-examples (i.e. could make the statement false). Let's look at the truth table for if P then Q (see here: http://www.math.hawaii.edu/~ramsey/Logic/IfThen.html). The statement is only false when Q is false and P is true. Thus, it suffices to flip cards when P is true or Q is false. To solve this problem, we need to print the count of vowels and odd digits in the string. <spoiler summary="stats"> First solve: [user:ksun48,2017-12-29] at 00:01:01 Breakdown of results for submissions that passed...
This problem is intended as an implementation problem. The bounds are small enough that abrute

Full text and comments »

Tutorial of Good Bye 2017
  • Vote: I like it
  • +336
  • Vote: I do not like it

85.
By LMydd0225, history, 2 years ago, In English
Codeforces Round 969 (Div. 1, Div. 2) Editorial [problem:2007A] <spoiler summary="Hint 1"> How many odd integers are there in a pair $(a, b, c)$? <spoiler summary="Answer"> At least 2. </spoiler> </spoiler> <spoiler summary="Hint 2"> It's always better to put **exactly $2$** odd integers and **exactly $1$** even integer in one pair of $(a, b, c)$. Is there a way to always choose optimal $(a, b, c)$? </spoiler> <spoiler summary="Hint 3"> Try consecutive integers. </spoiler> <spoiler summary="Tutorial"> [tutorial:2007A] </spoiler> <spoiler summary="Implementation"> ```py T = int(input()) for _ in range(T) : l, r = map(int, input().split()) print(((r + 1) // 2 - l // 2) // 2) ``` </spoiler> [problem:2007B] <spoiler summary="Hint"> Consider the position of the maximum value in one array. If there's multiple maximum values, choose any. What can you observe? <spoiler summary="Answer"> The position of the maximum value never changes. That is, if one element is the maximum value...
intersection of the rows and columns. Just try every possible situation and do brute force on it.

Full text and comments »

  • Vote: I like it
  • +138
  • Vote: I do not like it

86.
By ivanz, 5 years ago, In English
Why are there so many dislikes at the announcement of the Round #745? **It is very sad to see [user:interlude,2021-09-30] at the bottom of the user rating by contribution. I liked Round #745, even considering that I solved only one problem in the first division. The tasks seemed interesting to me, they do not have complicated statements and there is something to think about.** **It seems to me that many people did not like that the C problem was solved by a complete brute force with clipping.** My solution works like this: we iterate over the upper left cell of the rectangle containing the portal, then its height...
what to do, the optimal solution is a slightly optimized brute force., **It seems to me that many people did not like that the C problem was solved by a completebrute

Full text and comments »

  • Vote: I like it
  • +253
  • Vote: I do not like it

87.
By wuhudsm, history, 15 months ago, In English
TheForces Round #44 (DIV3.5-Forces) Editorial [A](https://codeforces.me/gym/106049/problem/A) Idea:[user:Muhammad-Ahmad,2025-08-22] <spoiler summary="solution"> The key observation is that the parity of the distance between Alice and Bob always changes after one move. Therefore, if $|x - y|$ is even, Alice can always move closer to Bob and corner him to win. Otherwise, Bob will win. </spoiler> <spoiler summary="code(C++)"> ```cpp #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; template <typename T> using os = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template <typename T> using oms = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>; #define mod 1000000007 #define mod2 998244353 #define ll long long #define bl __int128_t #define pb push_back #define all(v) v.begin(),v.end() #define bs binary_search #define rall(v) v.rbegin()...
If $k$ is chosen for the first time, we can recalculate the answer using brute force. Otherwise

Full text and comments »

  • Vote: I like it
  • +26
  • Vote: I do not like it

88.
By Geothermal, history, 7 years ago, In English
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...
We can solve this with a brute-force simulation, simply implementing the procedure given in the

Full text and comments »

  • Vote: I like it
  • +117
  • Vote: I do not like it

89.
By Bahamin, history, 16 months ago, In English
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...
Choose a vertex $v$, brute force on the back-edges that pass through $v, Take a DFS tree, at most $5$ back-edges pass through each vertex, then choose a vertex $v$,brute

Full text and comments »

  • Vote: I like it
  • +243
  • Vote: I do not like it

90.
By pilliamw, 10 months ago, In English
What makes a good Div2A? As a [problemsetter](https://codeforces.me/blog/entry/147831), this is a question that I've been thinking about for a very long time &mdash; writing high-quality and challenging tasks for a contest's problemset is a valuable and much-discussed skill, but barely anyone ever talks about or even remembers the first two problems of a contest (barring Div1s, which this blog post largely doesn't apply to). This is a great shame in my eyes; Div2As always boast the highest solve counts in virtually every Div2 round, and are accessible to the widest audience of Codeforces users, but are almost never discussed in the comments section of the contest blog post or editorial. Is this simply because such tasks are considered trivial in the eyes of most Codeforces users (at least, those rated above 1200) and therefore not worth discussing? Perhaps, but there are usually about two to four thousand people per contest who solve the Div2A and Div2B but fail to solve anything beyond that, meaning that...
ideally reduce the problem to something more satisfying than just a simple brute force with bounds, - **Avoid "Brute Force" as main solutions**:

Full text and comments »

  • Vote: I like it
  • +88
  • Vote: I do not like it

91.
By cry, 2 years ago, In English
Codeforces Round 988 (Div. 3) Editorial #### [problem:2037A] Problem Credits: [user:cry,2024-10-25] <br> Analysis: [user:cry,2024-10-25] <spoiler summary="Solution "> We want to count how many times we can choose $i$ and $j$ such that $a_i = a_j$. Suppose $f_x$ stores the frequency of $x$ in $a$. Once we choose $a_i = a_j = x$, $f_x$ is subtracted by $2$. Thus, the answer is the sum of $\lfloor \frac{f_x}{2} \rfloor$ over all $x$. </spoiler> <spoiler summary="Code (Python) "> ```py t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) print(sum([a.count(x) // 2 for x in range(n + 1)])) ``` </spoiler> #### [problem:2037B] Problem Credits: [user:cry,2024-10-25] <br> Analysis: [user:chromate00,2024-11-17] <spoiler summary="Are you a python user and failing test 4?"> It is worth noting that test $4$ is especially made to blow up python dictionaries, sets, and Collections.counter. If you are time limit exceeding, consider using a frequency array of le...
Denote $dp[i]=$ the number of ways to get to city $i$. Brute-forcing

Full text and comments »

  • Vote: I like it
  • +128
  • Vote: I do not like it

92.
By SPyofgame, history, 5 years ago, In English
Can somebody hack my brute-forces solution ? ### The Statement Here in this problem [1107D. Compression](https://codeforces.me/contest/1107/problem/D) Given an integer $n$ and a binary table $A[n][n]$ We are asked to find maximum $x$ that exist a binary table $B\left[\left \lceil \frac{n}{x} \right \rceil \right]\left[\left \lceil \frac{n}{x} \right \rceil \right]$ That this equation is satisfied $B\left[\left \lceil \frac{i}{x} \right \rceil \right]\left[\left \lceil \frac{j}{x} \right \rceil \right]$ $= A[i][j]\ \forall\ 1 \leq i, j \leq n$ (sorry but I dont know why the latex is broken like that) ### The solution So my approach is to check for all $v | n$ if there is exist such table. Let call a square $(lx, ly)$ is a subtable $A[lx..rx][ly..ry]$ for $$\begin{cases} 1 \leq lx \leq rx \leq n\\ 1 \leq ly \leq ry \leq n\\ rx - lx + 1 = v\\ ry - ly + 1 = v\\ v\ |\ rx\\ v\ |\ ry\\ \end{cases}$$ So there are $\frac{n}{v} \times \frac{n}{v}$ such subtables Binary Table $...
Can somebody hack my brute-forces solution ?, For brute-force version, I check it by comparing each position one by one.

Full text and comments »

  • Vote: I like it
  • +7
  • Vote: I do not like it

93.
By kiwii, history, 5 years ago, In English
COMPFEST 13 — Editorial ## [1575A. Another Sorting Problem](https://codeforces.me/contest/1575/problem/A) Author: [user:hocky,2021-10-03] Developer: [user:richiesenlia,2021-10-03] Editorialist: [user:hocky,2021-10-03] <spoiler summary="Idea"> Observe that the even-indexed character of the string can be transformed from `A`-`Z` to `Z`-`A`. E.g. for the first example: - AA → AZ - AB → AY - BB → BY - BA → BZ - AZ → AA Now, you can use any known algorithms to sort the string as usual. You can sort it in linear time with trie, or `std::sort` in $O(nm \log n)$ time. Time Complexity : $O(nm)$ or $O(nm \log n)$ </spoiler> ## [1575B. Building an Amusement Park](https://codeforces.me/contest/1575/problem/B) Author: [user:Panji,2021-10-03] Developer: [user:hocky,2021-10-03], [user:rama_pang,2021-10-03] Editorialist: [user:hocky,2021-10-03], [user:rama_pang,2021-10-03] <spoiler summary="Idea"> We can binary search the answer $r$ in this case. Here, bird's habitats ar...
There are no dirty tricks to solve this problem. Brute force all possible, The transition can first be precomputed with brute force in $O(n^3)$ or with Aho-Corasick.

Full text and comments »

  • Vote: I like it
  • +102
  • Vote: I do not like it

94.
By qwexd, 4 years ago, In English
Hacking [GUIDE] _I've seen quite a lot of people asking about hacking but I couldn't find any guide in codeforces so I decided to make this blog._ --- ### **What is Hacking?** $\ $ In a codeforces round, test cases might not be enough to judge your code. It's very normal since we can't expect setters to consider every single wrong solution to add new test cases. In other words, if your code gets Accepted during the contest, this doesn't mean your submission is necessarily correct. To avoid incorrect solutions that get Accepted due to the lack of enough test cases to judge during the round we use Hacking. $\ $ There are two types of Hacking, one of them is after the contest and the other is during the contest; but the general idea of hack is providing a test case where you think someone's solution fails. The judge checks this specific test case you provided and determine if the solution actually fails. (Comparing outputs with actually working pre-made jury code to check if i...
), you can generate a test that causes worst-case and brute-force over slow codes and submit hacks one, - Second, can find an edge case that doesn't appear at pretests and brute force over random, . That's because you must not just copy-paste the solution to gain time for stress-testing andbrute

Full text and comments »

  • Vote: I like it
  • +166
  • Vote: I do not like it

95.
By Bazoka13, 3 years ago, In English
Codeforces Round #947 Editorial [problem:1975A] Idea: [user:Bazoka13,2024-05-25] Solution: [user:Bazoka13,2024-05-25] Prepared by: [user:Bazoka13,2024-05-25] <spoiler summary="Hint 1"> We can't do any insertions by the operation. </spoiler> <spoiler summary="Hint 2"> If the answer is yes, we can make $a$ become non-decreasing in no more than one operation. </spoiler> <spoiler summary="Solution"> Read the hints. If $a$ is non-decreasing initially, the answer is yes. If $a$ isn't non-decreasing initially, we can find the smallest $i$ such that $a_i> a_{i+1}$. Then we choose $x=[a_1,a_2,...,a_i]$ and $y=[a_{i+1},a_{i+2},...,a_n]$. If the array $y+x$ is non-decreasing, the answer is yes. Otherwise, the answer is no. </spoiler> <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; const int N = 1e5+10; int a[N]; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; for(int i=1;i<=n;i++){ cin>>a[i]; } ...
Assume that we use FFT to brute force solve this problem every time. See Hint.3 for the specific

Full text and comments »

  • Vote: I like it
  • +111
  • Vote: I do not like it

96.
By Elegia, history, 23 months ago, In English
More on D-Finite Functions I: Theories Hello everyone. Several years ago [user:jqdai0815,2025-01-03] released a [blog](https://codeforces.me/blog/entry/76447) on the topic of D-Finite functions. In this blog, I will introduce some more theories, and show the relation between some CP problems. Also, I found out that what I show is like opening Pandora's box: it provides some new ways to solve problems, but they also somehow prevent us from really understanding them. Therefore, I'll also talk about some of my personal critiques on this topic. Since this blog is quite long, I'll divide it into several parts. This is the first part. ## Appetizer We start with this toy problem. **$n$-King Problem.** Given $n$, count the number of permutations $\sigma$ of $[n]$ such that for any $i$, $|\sigma(i) - \sigma(i+1)| \neq 1$. Of course, this sequence has already been studied before, it is the [A002464](https://oeis.org/A002464) in OEIS. You can find its recurrence relation $$ a_n = (n+1)a_{n-1} - (n-2)a_{n-2} - (n-5...
the first several terms in some brute-force way, and then use Gaussian elimination to find the P

Full text and comments »

  • Vote: I like it
  • +123
  • Vote: I do not like it

97.
By llaki, 12 years ago, In English
Rockethon 2015 Editorial (This is a beta version of editorial. It will be changed later) I hope everybody enjoyed the contest. Here we'll present some of the author's solutions to the problems together with some other approaches that we came up with. The editorial is prepared by Lasha Lakirbaia, Anton Lomonos, and Ievgen Soboliev. A &mdash; Game ================== (developed by Ievgen Soboliev & Eldar Bogdanov, editorial written by Lasha Lakirbaia) The problem can be solved with dynamic programming technique. Let $winner[a][b][move]$ denote who wins if both players play optimally and the first has a balls left in his box, the second has $b$ balls left in his box and move defines who is to move next. To determine the value of $winner[a][b][move]$, we should consider all the possible moves the next player can make and see whether any of them lead into the position $winner[x][y][move2]$ in which this player can win with optimal play. Thus, values of winner can be defined recursively. Ok it was a jok...
First solution (the easiest) — brute force

Full text and comments »

  • Vote: I like it
  • +172
  • Vote: I do not like it

98.
By kartik8800, 7 years ago, In English
CSES Range Queries section editorial **UPD:** some video editorials on range query data structures: [youtubePlaylist](https://www.youtube.com/playlist?list=PLb3g_Z8nEv1isaHPaXL1j-pSo60812JtY) Hello Codeforces, In this blog I will try to write a well detailed editorial for the CSES Range Queries section. The motivation for this editorial comes from https://codeforces.me/blog/entry/70018. Quoting [user:icecuber,2020-05-09] "I think [CSES](https://cses.fi/problemset/) is a nice collection of important CP problems, and would like it to have editorials. Without editorials users will get stuck on problems, and give up without learning the solution. I think this slows down learning significantly compared to solving problems with editorials. Therefore, I encourage others who want to contribute, to write editorials for other sections of CSES." So here I am writing an editorial for the range queries section. If you find any error or maybe have a better solution to some problem please do share. Range Sum Queries I =...
[a,b] we shall do a brute force., in the range [a,b]. For remaining partially included buckets do a brute force (actually iterate over, Brute force : Start checking every hotel from left to right for the number of rooms it has, Brute force is quite simple if you simply simulate what is mentioned in the problem. Let us, The brute force can be done by simply iterating from index a to b and maintaining number of

Full text and comments »

  • Vote: I like it
  • +181
  • Vote: I do not like it

99.
By 36champ, 6 months ago, In English
Codeforces Round 1101 (Div. 2) — Editorial [Problem A &mdash; Convergence](https://codeforces.me/contest/2232/problem/A) Problem Idea: [user:36champ,2026-05-30] <br> Solution Idea: [user:36champ,2026-05-30] <spoiler summary="Hint 1"> What if the meeting location is fixed? </spoiler> <spoiler summary="Solution"> If the meeting location is fixed, the answer is max(the number of people to the left of that position, the number of people to the right of that position. This can be solved in $O(n^2)$ by iterating through all position that has at least one person on it. This problem can also be solved in $O(n\log n)$ by sorting and setting the meeting position to the median of all positions. </spoiler> <spoiler summary="Code"> ```cpp #include <bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vll; typedef vector<vll> vvll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; int main() { ios_ba...
For this subtask, it is possible to brute-force the number of ambiverts acting as introverts and

Full text and comments »

  • Vote: I like it
  • +97
  • Vote: I do not like it

100.
By -1e11, 20 months ago, In English
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...
guess the answer through brute force.

Full text and comments »

  • Vote: I like it
  • +169
  • Vote: I do not like it

101.
By darkshadows, 12 years ago, In English
CodeCraft'15 IIIT Hyderabad Editorial [problem:100589A] ------------------ Given a rooted tree(at node 1) of **N** nodes,you have to handle a total of **Q** operations of type: **1 U L X**: Increase coins by **X** of all nodes at a distance of **L** from root. **2 X**: Report sum of all coins in subtree rooted at **X**. **N** <= 10<sup>5</sup> **Q** <= 10<sup>4</sup> #### Difficulty: Medium-Hard ####Explanation: This approach uses a very specific technique of maintaining a buffer of update queries and updating the whole tree once buffer size exceeds a constant limit(we maintain this limit as sqrt(M)). ~~~~~ buffer=[] q=input while q--: query = input() if query==update: buffer.add(query) else: //say query is “2 X” //the answer that has been already calculated for node X prevans= ans(X) for i=0 to buffer.size(): //add to prevans the effect of buffer[i] //let’s say buffer[i]=”1 U L...
In worst case the number of triplets will be in order of **O(P*Q*R)**, hence brute force solution

Full text and comments »

  • Vote: I like it
  • +81
  • Vote: I do not like it

102.
By pikel_rik, history, 6 years ago, In English
Binary Search + Brute Force Imagine you're given an array $A$ of length $n$ and you're required to find the largest subset of this array that satisfies a certain condition. Let's assume that the given condition makes the problem $NP-$complete and also allows the following to be true: 1. If there exists a subset of length $k$ that satisfies the given condition, then assuming that $k > 1$, there necessarily exists subsets of length $l$, $1 \le l < k$, that satisfies the condition. 2. If there does not exist a subset of length $k$ that satisfies the given condition, then assuming $k < n$, there necessarily will not exist any subset of length $l$, $k < l \le n$, that satisfies the condition. In short, the binary search property holds. Since the problem is $NP-$complete, however, there exists no efficient function that allows us to find whether there exists a subset of length $k$ that satisfies the condition or not. So the only thing we can do is iterate over all subsets of length $k$ and check whether eac...
Binary Search + Brute Force, My question is, if we use binary search on this problem armed with the brute force function, brute force function mentioned above, what would the time complexity of this algorithm be in the worst

Full text and comments »

  • Vote: I like it
  • +9
  • Vote: I do not like it

103.
By Mindeveloped, history, 23 months ago, In English
[Suggestion] Some Problem Tags Might Need Revamp Problem tags, which are supposed to help people categorize problems, some of them doesn't make much sense and need revamp. For example, take a look at [problem:2057E2]. At the time of this blog, it has tags "binary search" "brute force" "dp" "dsu" "graphs" "shortest paths" "sortings". Some of them doesn't make much sense to me. "dsu" "graphs" "shortest paths" are fine imo. They either describe the core idea or the main techniques the problem use. Then "dp" might be a bit controversial, it is probably about the fact that the modified Floyd algorithm is based on DP. It could be reasonable, especially if you didn't recognize that you are using Floyd algorithm when adding edges dynamically. The editorial also agrees with this idea. This trick seems rather classical to me. I don't think this is a big problem. However the rest of them does not make much sense imo. For "binary search", I guess it's about the binary search approach for E1. That is too slow and cannot pass E2. And f...
"sorting the elements in some order" as the key part. "brute force" makes absolutely no sense. Again, a, " "brute force" "dp" "dsu" "graphs" "shortest paths" "sortings". Some of them doesn't make much sense

Full text and comments »

  • Vote: I like it
  • +101
  • Vote: I do not like it

104.
By wuhudsm, history, 3 years ago, In English
TheForces Round #20 (7-Problem-Forces) Editorial [A](https://codeforces.me/gym/104471/problem/A) <spoiler summary="code"> ``` #include <bits/stdc++.h> #define int long long #define fi first #define se second using namespace std; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t --> 0) { int n; cin >> n; vector<int> a(n); vector<int> b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; vector<int> ord(n); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&](int x, int y) { if (b[x] == b[y]) return a[x] > a[y]; return b[x] == 1; }); int ans = a[0] * b[0]; int suma = 0, sumb = 0; for (int i = 0; i <...
For queries that are not complete blocks, consider direct brute force maintenance of the A-array

Full text and comments »

  • Vote: I like it
  • +36
  • Vote: I do not like it

105.
By ksun48, history, 11 years ago, In English
Editorial for CROC 2016 Elimination Round [problem:645A] --- **Idea:** [user:yummy,2016-03-18] One solution is to just brute force and use DFS to try all the possibilities. Alternatively, note that two puzzles can be changed to each other if and only if the $A$, $B$, and $C$ have the same orientation—clockwise or counterclockwise—in the puzzle. A third option, since the number of possibilities is so small, is to simply classify all of the $4!=24$ configurations by hand. <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; string b, b1, b2, e, e1, e2; int main(){ cin >> b1 >> b2 >> e1 >> e2; swap(b2[0], b2[1]); swap(e2[0], e2[1]); b = b1 + b2; e = e1 + e2; b.erase(b.find('X'), 1); e.erase(e.find('X'), 1); if((b + b).find(e) != string::npos){ cout << "YESn"; } else { cout << "NOn"; } } ~~~~~ </spoiler> [problem:645B] --- **Idea: [user:ksun48,2016-03-18]** Loosely speaking, we’re trying t...
One solution is to just brute force and use DFS to try all the possibilities. Alternatively, note

Full text and comments »

  • Vote: I like it
  • +89
  • Vote: I do not like it

106.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 141 English Solutions #A &mdash; Weather Prediction Store the three weather states in an array. Then, identify the element of the array equal to the input value, and print the next element in the array. Time complexity: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc141/submissions/7514223) --- #B &mdash; Tap Dance We can employ brute force here, checking each element of the string individually and printing No as soon as we find one that doesn't satisfy the given condition. Of course, if all elements of the string comply with the requirements, the answer is Yes. To implement the solution faster, note that the given conditions are equivalent to \texttt{S[i] != 'L'} when $i$ is odd and \texttt{S[i] != 'R'} when $i$ is even, so you can implement each of them using just one condition instead of three. Time complexity: $O(N)$. [Click here for my submission.](https://atcoder.jp/contests/abc141/submissions/7515237) --- #C &mdash; Attack Survival Suppose pla...
We can employ brute force here, checking each element of the string individually and printing No as

Full text and comments »

  • Vote: I like it
  • +64
  • Vote: I do not like it

107.
By -firefly-, history, 16 months ago, In English
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; | |...
= 1]$. We can then brute force to find the first edge, remove it, and then try to find the second

Full text and comments »

  • Vote: I like it
  • +110
  • Vote: I do not like it

108.
By kostka, 12 years ago, In English
Hack me! (CF Round #263, Div. 2) Welcome again! I decided to split statistics for both division. Post for first division <strike>will be added later</strike> is <a href="http://codeforces.me/blog/entry/13572">here</a>. So, let's look at hacks in [contest:462]. <small><strike>Some statistics are missing &mdash; I have some problems with downloading all data (Codeforces seems little crowded today). They will be also added later.</strike></small> **Update**: Europe went asleep, so I added missing stats. [cut] <h3>Stats</h3> Problem | Successful hacks | Unsuccessful hacks | Other | Sum | :---:|:---:|:---:|:---:|:---:| [problem:462A] | 5 (17%) | 25 (83%) | 0 (0%) | 30 | [problem:462B] | 1193 (71%) | 188 (11%) | 306 (18%) | 1687 | [problem:462C] | 0 (0%) | 55 (36%) | 98 (64%) | 153 | ### Fastest hackers Problem | Time | Hacker | Defender | Hack :---:|:---:|:---:|:---:|:---:| [problem:462A] | 00:50:08 | [user:ak.bewildered,2014-08-26] | [user:abdohammam95,2014-08-26] | <a href="http://codefo...
Most of these solutions were just brute-force approach. Pretests weren't too hard to pass.

Full text and comments »

  • Vote: I like it
  • +113
  • Vote: I do not like it

109.
By wuhudsm, history, 16 months ago, In English
Codeforces Round 1040 (Div. 1, Div. 2) Editorial Thank you for participation and we hope you enjoy this round :) <spoiler summary="How did you find the contest?"> - Great: - Good: - Average: - Bad: - Trash: </spoiler> <spoiler summary="Which problem is your most favourite?"> - D2A: - D2B: - D1A: - D1B: - D1C1: - D1C2: - D1C3: - D1D: - D1E: - D1F1: - D1F2: </spoiler> <spoiler summary="Which problem you hate the most?"> - D2A: - D2B: - D1A: - D1B: - D1C1: - D1C2: - D1C3: [likes:favorite,2039E3_...
$ value using brute force. This inspires us to use the Mo's algorithm.

Full text and comments »

  • Vote: I like it
  • +118
  • Vote: I do not like it

110.
By MinakoKojima, 14 years ago, In English
Codeforces Round #183 Editorial Overview ... ================== 。。。(; Д ;) 。 Tutorial ... ================== - [Problem 2A. Pythagorean Theorem II](http://codeforces.me/problemset/problem/304/A) Math, implementation This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math. Check the following article if you are interested. [http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple](http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple) - [Problem 2B. Calender](http://codeforces.me/problemset/problem/304/B) Math, implementation This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math. Check [user:kabar,2013-05-13]'s code if you are interested. [http://codeforces.me/contest/304/submission/3715756](http://codeforces.me/contest/304/submission/3715756) - [Problem A. Lucky Permutation Triple](http://codeforces.me/problemset/problem/303/A) Ma...
Math, Graph theory, Brute-force, Congruent, This problem can be solve by brute-force, but it come up with a nicer solution if we involve some

Full text and comments »

  • Vote: I like it
  • -10
  • Vote: I do not like it

111.
By PinkRabbitAFO, history, 7 years ago, In English
Codeforces Round #635 Problem "Mahjong Set" Ununofficial Editorial Hello there, here's an unofficial editorial for [1136D. Yui and Mahjong Set](https://codeforces.me/contest/1336/problem/D) by a tester [user:PinkRabbit,2020-04-16]. Observation: Focus on the differential of triplets/straights before and after an operation. By doing an operation on $a_i$, you'll find that the differential of triplets equals $x (x - 1) / 2$, where $x$ equals $a_i$ before the operation. So if we did a single operation on $a_i$, we can get the exact value of initial $a_i$ iff initial $a_i \ge 2$, otherwise initial $a_i$ must be equal to $0$ or $1$. If we did two (or more, but unnecessary?) operation on $a_i$, we can now get the exact value of initial $a_i$ no matter whether $a_i$ is less than $2$ or not. One of the most natural ideas is to perform operation in the order of $1, 2, \ldots, n$, it works like this: - Now, assume we get the exact value of $a_1 \sim a_i$, and we want to determine $a_{i + 1}$. - If $a_{i + 1} \ge 2$, done. Just consider the ...
Why not brute force? Try all possibilities of $a_1$ and $a_2$ (not many, $2^2 = 4$ at most) and run

Full text and comments »

  • Vote: I like it
  • +141
  • Vote: I do not like it

112.
By Gheal, 5 years ago, In English
Infoleague Spring 2022 Round Editorial <spoiler summary="Vote your favourite problem"> <spoiler summary="Div 2"> Div 2A &mdash; The Hatchet Div 2B &mdash; Floor Or Xor Div 2C &mdash; Yet Another Constructive Problem Didn't participate, idc </spoiler> <spoiler summary="Div 1"> Div 1A &mdash; Bamboo Coloring Div 1B &mdash; Xor Or Floor Div 1C &mdash; Jump Didn't participate, idc </spoiler> </spoiler> [103633A &mdash; The Hatchet](https://codeforces.me/gym/103633/problem/A) ------------------ Author: [user:tibinyte,2022-03-30] <spoiler summary="Rate Problem"> 1700 or less 1800 1900 2000 2100 or more Didn't solve it, idk </spoiler> <spoiler summary="Solution"> ### Subtask 1 : $N \le 10^2$ This subta...

Full text and comments »

  • Vote: I like it
  • +30
  • Vote: I do not like it

113.
By 0doO, history, 3 years ago, In English
[Editorial] Codeforces Round 939 (Div. 2) Thank you for taking part in our contest, we know leaves a lot to be desired. But we believe that you can find interesting among our problems. ## [A. Nene's Game](https://codeforces.me/contest/1956/problem/A) Idea: [user:Otomachi_Una,2024-04-13] <spoiler summary="Tutorial"> Obviously, a person at place $p$ will be kicked out if and only if $p \ge a_1$. Therefore, the answer is $\min(n,a_1-1)$. </spoiler> <spoiler summary="Solution"> ```cpp #include<bits/stdc++.h> using namespace std; #define ll long long #define MP make_pair mt19937 rnd(time(0)); int a[105]; void solve(){ int q,k,n;cin>>k>>q; for(int i=1;i<=k;i++) cin>>a[i]; for(int i=1;i<=q;i++){ cin>>n; cout<<min(a[1]-1,n)<<' '; } cout<<endl; } int main(){ ios::sync_with_stdio(false); int _;cin>>_; while(_--) solve(); } ``` </spoiler> ## [B. Nene and the Card Game](https://codeforces.me/contest/1956/problem/B) Idea: [user:Otomachi_Una,2024-04-13] <spoiler summary="Hin...
So, we can simulate the process by brute force until there are no four consecutive alive monsters

Full text and comments »

  • Vote: I like it
  • +106
  • Vote: I do not like it

114.
By marat.snowbear, 12 years ago, In English
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...
Since the numbers in the input are very small you can implement 'brute force' solution as well. By

Full text and comments »

  • Vote: I like it
  • +186
  • Vote: I do not like it

115.
By YuukaKazami, 14 years ago, In English
Codeforces Round #146 Tutorial ### [problem:236A] It is a very simple problem, just count how many distinct chars in the input and output the correct answer. ### [problem:236B] First of all, we can make a table of size a*b*c to store every number's d value. Then we can just brute force through every tripe to calculate the answer. ### [problem:235A] It is a simple problem, but many competitors used some wrong guesses and failed. First of all, we should check if n is at most 3 and then we can simply output 1,2,6. Now there are two cases: When n is odd, the answer is obviously n(n-1)(n-2). When n is even, we can still get at least (n-1)(n-2)(n-3), so these three numbers in the optimal answer would not be very small compared to n. So we can just iterate every 3 number triple in [n-50,n] and update the answer. ### [problem:235B] Let us take a deep look at how this score is calculated. For an $n$ long 'O' block, it contributes $n^2$ to the answer. Let us reformat this problem a bit and consider ...
brute force through every tripe to calculate the answer.

Full text and comments »

  • Vote: I like it
  • +69
  • Vote: I do not like it

116.
By AlexLuchianov, 5 years ago, In English
[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:...
A brute force approach would build a graph where each letter of the string is represented by a node, A brute-force approach would be to iterate over all of the elements of each query interval. This

Full text and comments »

  • Vote: I like it
  • +195
  • Vote: I do not like it

117.
By box, 5 years ago, In English
On the Min25 sieve and extensions / SPOJ ASSIEVE Consider the following problem (general form of original Min25 sieve): We are given some *multiplicative* function $f(n)$, described at prime powers by $f(p^k)=g(p,k)$, where $g(p,1)$ is a polynomial of low degree, and we can calculate $g(p,k)$ for any singular $p$ and $k$ in $O(1)$. How do we calculate the prefix sum of $f(n)$ at the distinct positive integer values of $\lfloor\frac Nk\rfloor$, where $N\le 10^{10}$? Clearly, brute force or regular sieves are not going to cut it here. --- Prerequisite: For any integer $N$, for all integers $1\le k\le N$ there are at most $2\sqrt N$ distinct values of $\lfloor\frac Nk\rfloor$. Call these $2\sqrt N$ such values the *blocks* of $N$. (A note on notation: In the following text, $\frac Nk$ will be used to describe regular division, and $N/k$ will be used to denote floored division.) <spoiler summary="Proof"> For $k\le\sqrt N$, each $k$ contributes at most one distinct value, for a total of $\sqrt N$ elements. For $k>\sqrt ...
evaluating $g(p_j,c)$ with brute force, so we care about deriving the value of the first type., $, as brute force works with the other half., \frac Nk\rfloor$, where $N\le 10^{10}$? Clearly, brute force or regular sieves are not going to cut it

Full text and comments »

  • Vote: I like it
  • +161
  • Vote: I do not like it

118.
By Sanae, history, 11 months ago, In English
Tutorial for CF1167G # Tutorial for CF1167G ## English Version ### Hints What stops the rotation? A brute-force solution is straightforward, but how can we optimize it? ### Step 1 There are two cases in which the rotation stops: 1. the ray touches the building 2. the building touches another building. In the second case, write the left building is $x$ sway from the bending point and the right one is $y$ away from the bending point. With some geometry knowledge, the angle is $ \alpha=\begin{cases} \tan^{-1}(\frac{1}{x}) & x=y\\ \tan^{-1}(\frac{1}{\max(x,y)}) & |x-y|=1\\ \textrm{useless} & \textrm{otherwise} \end{cases} $ In the third case , they won't reach each other. So we can easily write a brute force $O(nm)$. [code](https://codeforces.me/contest/1167/submission/356140562) ### Step 2 The crucial idea is that if $|x|>7000$, we don't need to calculate it. It's because, due to the "not sparse" condition that two buildings have already touched each o...
A brute-force solution is straightforward, but how can we optimize it?, So we can easily write a brute force $O(nm)$.

Full text and comments »

  • Vote: I like it
  • +14
  • Vote: I do not like it

119.
By Geothermal, history, 6 years ago, In English
AtCoder Beginner Contest 184 Unofficial Editorial #A &mdash; Determinant Just perform the requested computation. There really isn't much to do here. Time Complexity: $O(1).$ [Click here for my submission.](https://atcoder.jp/contests/abc184/submissions/18318540) --- #B &mdash; Quizzes A simple brute-force simulation works here. Iterate over the characters of $S$ from left to right, adding one to the answer if the current character is an `o` and subtracting one if it's an `x` (while ensuring that the score never drops below zero). Time Complexity: $O(N).$ [Click here for my submission.](https://atcoder.jp/contests/abc184/submissions/18318362) --- #C &mdash; Super Ryuma The key observation is that the answer will always be at most three. We will provide a constructive proof. Suppose that we want to go from $(x_1, y_1)$ to $(x_2, y_2)$. In our first move, we move to any point $(x_3, y_3)$ such that $x_3 + y_3$ has the same parity as $x_2 - y_2.$ Then, we will finish with two diagonal moves. We want to ...
A simple brute-force simulation works here. Iterate over the characters of $S$ from left to right

Full text and comments »

  • Vote: I like it
  • +45
  • Vote: I do not like it

120.
By errorgorn, 4 years ago, In English
[Tutorial] Berlakamp's Algorithm for Polynomial Factorization in a Field (1698G buffed) Hi, this is going to be a solution to a "harder" version of the last problem of the recent div 2 round that I coordinated. We can actually solve the problem for $|s| \leq 60$ but we decided to lower the constraint as forcing this solution is not interesting and also way too hard for the last problem of a div 2. I would like to thank the authors for allowing me to write this blog and shamelessly farm contribution from their contest. Firstly, I would like to share a solution (credits to [user:sexpert,2022-06-28]) which solves $|s| \leq 60$ without explictly factoring the entire polynomial. <spoiler summary="spoiler"> First, we remove all factors of the polynomial with degree $\leq 20$. After that, there are $3$ cases for the remaining polynomial, it is prime, it is square, it is product of two prime polynomials. We can brute force the degrees for all cases and test them, which should run in time. </spoiler> Now, let's get into the algorithm to factorize polynomials. We will us...
product of two prime polynomials. We can brute force the degrees for all cases and test them, which

Full text and comments »

  • Vote: I like it
  • +75
  • Vote: I do not like it

121.
By canine, history, 2 years ago, In English
yet another CP extension for VSCode hello all -- if you happen to be in the market for a new competitive programming extension and use VSCode, may i humbly suggest my new [extension](https://purduecpu.com/extension)? i think it is relatively feature complete, but it's still in alpha (especially for languages other than C++) and may have some kinks that need working out. it theoretically supports C++, Java, Python, and Rust (and it's very easy to add more). i created this because i was dissatisfied that most existing solutions can't import a bunch of test cases from a directory then run them in parallel. i also believe it has a cooler UI than other extensions. as usual, i didn't think it would take this long when i started... if you encounter any difficulties, please let me know on [github](https://github.com/canislupaster/cpu-vscode). **thanks for taking a look!** ![hero image](/predownloaded/f1/90/f190d6993497b2e6a93a505706e36189f5fd0200.jpg) ### Realtime Input/Output unlike other test runners for VSCode, w...
### Stress Testing run stress tests using a generator and brute force solution against your

Full text and comments »

  • Vote: I like it
  • +177
  • Vote: I do not like it

122.
By piaoyun, history, 2 years ago, In English
An iterating AI-solving framework may boost o1's cheating ability on Codeforces. I must say that I have no ideas about the details how OpenAI tested o1 model in IOI and Codeforces contests. This framework may not work or they have tried it. Here are some facts: 1. o1 performs relatively poor in IOI with 50 tries each. 2. o1 achieves IOI Gold Medal with 10000 tries each. 3. o1 only achieves 1600+ rating (far from IOI Gold Medal) on Codeforces. 4. According to the survey by community (https://codeforces.me/blog/entry/133887), o1 can solve very hard problem (2700) but also fail some very easy problems (800) 5. Codeforces's rule prohibit o1 from having too many tries. 4 and 5 may be the reason why o1 only achieve 1600 on Codeforces. The difference between IOI Gold and 1600 is, that IOI rules provide a no-cost validation so its final score is max(for each try). I believe, OpenAI didn't pay much attention to how to conquer the submission limitation of Codeforces. They may also independently generate 50 or 10000 codes. Thus the potential of AI che...
Brute-force is always easier to write, some extremely slow brute-force like exponential algorithms

Full text and comments »

  • Vote: I like it
  • +14
  • Vote: I do not like it

123.
By Endagorion, history, 11 years ago, In English
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...
straightforward brute-force for such cases.)

Full text and comments »

  • Vote: I like it
  • +74
  • Vote: I do not like it

124.
By GrishinD, history, 2 years ago, In English
Problem 973D. My solution walk-trough ## Edit 25.09.2024 Thanks to [user:dsogari,2024-09-25]'s for pointing out in the comments a clever solution to this problem that makes for a fast and simple algorithm ($O(n)$ time, $O(1)$ extra space): <spoiler summary="C++ code"> ```cpp long long mn = LLONG_MAX, mx = 0, pref = 0, suff = 0; for (int i = 0; i < n; i++) { // O(n) pref += a[i]; suff += a[n - i - 1]; mn = min(mn, pref / (i + 1)); // floor mx = max(mx, (suff + i) / (i + 1)); // ceil } cout << mx - mn << endl; ``` </spoiler> The solution described in this post is longer and more constructive, takes $O(n)$ time and $O(n)$ extra space. While I like the short version, I also think the constructive approach has some merit since it produces not only the answer, but the final state of the array and a series of transformations to get there. Also check out [user:Orn0,2024-09-25]'s [post](https://codeforces.me/blog/entry/134298) about his solution to this problem using binary search on answer, complete ...
### Checker algorithm for brute-force testing

Full text and comments »

  • Vote: I like it
  • +141
  • Vote: I do not like it

125.
By 055D, 6 years ago, In English
Codeforces Round #665 (Div. 2) Editorial Thank you for participating. I hope you enjoyed the contest! [problem:1401A] <spoiler summary="Tutorial"> [tutorial:1401A] </spoiler> <spoiler summary="Solution Code"> ~~~~~ #include<bits/stdc++.h> #define endl '\n' using namespace std; main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int k, n, t; cin >> t; for(;t--;) { cin >> n >> k; if(n < k) cout << k - n << endl; else if(n % 2 == k % 2) cout << 0 << endl; else cout << 1 << endl; } return 0; } ~~~~~ </spoiler> <spoiler summary="Behind Story"> After 2 problems got rejected, I made this problem but it has 2D coordinate originally. </spoiler> [problem:1401B] <spoiler summary="Tutorial"> [tutorial:1401B] </spoiler> <spoiler summary="Solution Code"> ~~~~~ #include<bits/stdc++.h> #define endl '\n' using namespace std; main() { ...
] suggested to increase them up to $10^5$. In fact, I only knew brute forces solution until he tells me the

Full text and comments »

  • Vote: I like it
  • +221
  • Vote: I do not like it

126.
By I_love_Hoang_Yen, 12 years ago, In English
[GYM] ACM ICPC Vietnam National First Round 2014 — Solutions Following are unofficial solutions for all problems. [problem:100499A] ----------------- **Solution 1** The most obvious solution for this problem is to brute force all numbers, and check if it is a cool number. [My code](http://ideone.com/S5T6en) After running this code for several minutes, you should be able to get results for all $K \leq 9$. The only result for $K = 7$ is $3211000$, for $K = 8$ is $42101000$ and for $K = 9$ is $521001000$. From these results, you should be able to guess the result for $K = 10$ is $6210001000$. **Solution 2** There are many ways to optimize the above solution. The most standard way is to see that the sum of all digits is equal to K, thus if you restrict your brute force to exit when sum of digit is greater than K, you should get a solution which runs in around a few seconds. [problem:100499B] ----------------- Since all numbers are at most $10^7$, you can count number of occurrence of each value. [My code](http://ideone...
all digits is equal to K, thus if you restrict your brute force to exit when sum of digit is, The most obvious solution for this problem is to brute force all numbers, and check if it is a cool

Full text and comments »

  • Vote: I like it
  • +71
  • Vote: I do not like it

127.
By YouKn0wWho, 6 years ago, In English
Do you really understand Suffix Arrays? An Experiment took a twisted turn! I was experimenting on the following problem for quite a long time: You are given two integers $n$ and $k(1 \le k\le n \le 10^5)$. You have to find the number of permutations with length $n$ that can be obtained as a suffix array of at least one integer sequence $a_1, a_2, \ldots, a_n$ s.t. $1\le a_i \le k$. Output it modulo $998, 244, 353$. <spoiler summary="Definition of Suffix Array for an integer sequence"> Suffix Array of an integer sequence $a_1, a_2, \ldots, a_n$ is a permutation $p$ of size $n$ where $p_i$ refers to the suffix starting from index $p_i$ in $a$ and all suffixes are in sorted order. So suffix array of $[3, 1, 1, 2]$ is $[2, 3, 4, 1]$. It's basically a normal suffix array but here we have an integer sequence. </spoiler> I didn't have any clue when I came up with the problem. It's really hard to find any specific properties of a permutation which will ensure that there exists a sequence which will generate the permutation as its suffix array. So then I...
So then I wrote a brute force over smaller numbers. And it turned out that there exists an [OEIS

Full text and comments »

  • Vote: I like it
  • +132
  • Vote: I do not like it

128.
By Lewin, 11 years ago, In English
Codeforces Round #309 Editorial [Div2A: Kyoya and Photobooks](http://codeforces.me/contest/554/problem/A) ----------------------- Solving this problem just requires us to simulate adding every character at every position at the string, and removing any duplicates. For instance, we can use a HashSet of Strings in Java to do this (a set in C++ or Python works as well). Bonus: Prove that the number of ways is always (length of string + 1) * 25 + 1. Example code: http://codeforces.me/contest/554/submission/11767578 [Div2B: Ohana Cleans Up](http://codeforces.me/contest/554/problem/B) ----------------------- For each row, there is only one set of columns we can sweep so it becomes completely clean. So, there are only $n$ configurations of sweeping columns to look at. Checking a configuration takes $O(n^2)$ time to count the number of rows that are completely clean. There are $n$ configurations in all, so this takes $O(n^3)$ time total. Alternatively, another way of solving this problem is finding the m...
allowed, and all of these swaps must be disjoint. This can be discovered by writing abrute force

Full text and comments »

  • Vote: I like it
  • +115
  • Vote: I do not like it

129.
By EndlessDreams, 4 years ago, In English
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]; ...
Direct brute force compare and remove string will TLE, so, For this problem, we can use brute force to enumerate numbers from, I'm sorry to let $\Theta(n^3)$ brute force pass., if $\text{cnt}_x\le b$, we can do brute force in $\Theta(\text{cnt}_x^2)$. The worst-case

Full text and comments »

  • Vote: I like it
  • +85
  • Vote: I do not like it

130.
By n0sk1ll, history, 3 years ago, In English
Editorial for Codeforces Round #910 (Div. 2) ## [1898A *-* Milica and String](https://codeforces.me/contest/1898/problem/A) Author: [user:n0sk1ll,2023-10-01] <spoiler summary="Hint"> In one move, Milica can replace the whole string with $\texttt{AA} \ldots \texttt{A}$. In her second move, she can replace a prefix of length $k$ with $\texttt{BB} \ldots \texttt{B}$. The process takes no more than $2$ operations. The question remains &mdash; when can we do better? </spoiler> <spoiler summary="Solution"> In the *hint* section, we showed that the minimum number of operations is $0$, $1$, or $2$. We have $3$ cases: 0. No operations are needed if $s$ already contains $k$ characters $\texttt{B}$. 1. Else, we can use brute force to check if changing some prefix leads to $s$ having $k$ $\texttt{B}$s. If we find such a prefix, we print it as the answer, and use only one operation. There are $O(n)$ possibilities. Implementing them takes $O(n)$ or $O(n^2)$ time. 2. Else, we use the two operations described in the hint se...
1. Else, we can use brute force to check if changing some prefix leads to $s$ having $k$ $\texttt{B

Full text and comments »

  • Vote: I like it
  • +124
  • Vote: I do not like it

131.
By galen_colin, 6 years ago, In English
Hybrid Tutorial #-2: Centroid Decomposition **See the [original post](https://codeforces.me/blog/entry/81317) on Codeforces for a playlist of all similar tutorials and also more information about what this is.** # "Intro" *Timestamp: [00:00](https://youtu.be/-DmMLQCmz94)* This is a "hybrid tutorial" &mdash; it has both a blog and a video component. See my original post for more explanation of what this is and also a playlist of all past tutorials. You can view the full video [here](https://youtu.be/-DmMLQCmz94). This tutorial is on centroid decomposition, a cool concept that has many uses in different problems. It's also another "decomposition" technique, one of many. I feel like this subject in particular doesn't have many great tutorials online that really capture the essence of what we do with the technique, so hopefully, I can improve that with this one. # Notation We'll use $0$-indexing for the whole tutorial, and the example problem will also be $0$-indexed. In addition, "vertex" and "node" mean the same...
when there's a stupid $O(n^2)$ brute-force that will work even faster! And you would be correct to

Full text and comments »

  • Vote: I like it
  • +264
  • Vote: I do not like it

132.
By 0mar, 5 months ago, In English
Codeforces Round 1108 (Div. 2) Editorial We hope you enjoyed the contest as much as we enjoyed writing it! Thank you especially to [user:PCTprobability,2026-07-12] [for](https://codeforces.me/contest/2246/submission/382271865) [your](https://codeforces.me/contest/2246/submission/382275385) [very](https://codeforces.me/contest/2246/submission/382277166) [entertaining](https://codeforces.me/contest/2246/submission/382278076) [submissions](https://codeforces.me/contest/2246/submission/382279367) [to](https://codeforces.me/contest/2246/submission/382283699) [problem](https://codeforces.me/contest/2246/submission/382285777) [E](https://codeforces.me/contest/2246/submission/382287709). <spoiler summary="Rating predictions"> ![ ](/predownloaded/90/af/90af678d167a48f6e9c92993a28c15ea40087ed9.png) </spoiler> [problem:2246A] <spoiler summary="Hint 1"> Try to eliminate a large class of possible sums. </spoiler> <spoiler summary="Hint 2"> Think about parity. Is it possible to eliminate all odd numbers? </spo...
Brute force suggests that it is always possible in at most $n$ moves

Full text and comments »

  • Vote: I like it
  • +72
  • Vote: I do not like it

133.
By kiwii, history, 3 years ago, In English
[Tuωutoωoial] Convex Polygon Counting Hi everyone, today I'm back with another blog that sadly, [user:nor,2023-10-19] won't have to spend 45 minutes GPT-ing my anime and kaomoji propaganda to read it. &#2798;&#8333; &#707; &#10521; &#706; &#8334;&#4304; &#x1f445; --- Not sure whether there is another blog explaining this technique in a "so many visualizations" manner. There are so many paper about these problems in particular. So please put your opinions and any other similar techniques you know in the comment section &#x1f4c3;&#x1f4c3;&#x1f4dc;. I think this is a "very known technique" for <span class="rated-user user-red">GM</span>s, so you guys might want to skip reading this blog. I also do expect this is a "very common geometry problem" in China or something but, here is my attempt on explaining it. Here is a cute quote by me oωo > When it comes to polygon problems, sometimes you have to see &#128038; &#127872; &#120008;&#119890;&#119892;&#120002;&#119890;&#120003;&#120009; &#127872; &#128038; in...
brute force and fix for each pair of $2$ points, and check whether a certain triangle doesn't have any

Full text and comments »

  • Vote: I like it
  • +86
  • Vote: I do not like it

134.
By skywalkert, history, 5 years ago, In English
2019 Summer PtzCamp, Day 8: XIX Open Cup Onsite, Editorial This editorial corresponds to [contest:103652], a.k.a "Jingzhe Tang Contest 2", held on Sept. 1st, 2019. Moreover, this problem set is a selection of "CCPC-Wannafly Winter Camp 2018, Day 2 (Div. 1 & Div. 2)" held on Jan 30th, 2019. Feel free to comment on the tutorials listed in the following (with some follow-up questions left to readers). Hope you enjoy solving these problems. --- [problem:103652A] <spoiler summary="solution"> The number of updates can be counted as the number of ordered pairs $(u, v)$ such that when $u$ is going to be removed, there exists at least one path between $u$ and $v$. If the path between $u$ and $v$ is unique in the original graph, we can conclude that pair exists if $u$ is the first removed node on the path with respect to an order, and $\frac{1}{cnt(u, v)}$ of all possible orders would meet this condition, where $cnt(u, v)$ is the number of nodes on the unique path between $u$ and $v$ (inclusive). In other cases, there exist exactly tw...
One brute-force way is to enumerate three of $\frac{12!}{3!9!}$ ($= 220$) possible sets and prune

Full text and comments »

  • Vote: I like it
  • +92
  • Vote: I do not like it

135.
By ditoly, history, 8 years ago, In English
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...
result finally :( And I did not notice that the brute force can care only primes not bigger than $\sqrt, You can write a brute force or enumerate all the possibilities by yourself. If you consider each

Full text and comments »

  • Vote: I like it
  • +191
  • Vote: I do not like it

136.
By drdilyor, history, 3 years ago, In English
LAZY solution to problem D in Codeton round 8 + PYTHON solution Heyo! If you tried to solve problem D you have probably ended up trying to optimize this algorithm: <spoiler summary="C++ brute force"> ``` // input int n, k; cin >> n >> k; vector arr(n, vector<int>(n)); for (int i = 0; i < n;i++) for (int j = i; j < n; j++) cin >> arr[i][j]; vector dp(n+2, vector<int>()); dp[n] = dp[n+1] = {0}; for (int i = n-1; i >= 0; i--) { vector<int> cur; for (int j = i-1; j < n; j++) { // prepare to merge by adding a[i][j] vector<int> tomerge = dp[j+2]; if (j >= i) { for (int& x : tomerge) x += arr[i][j]; } vector<int> merged; merge(cur.begin(), cur.end(), tomerge.begin(), tomerge.end(), back_inserter(merged), greater()); cur = merged; } dp[i] = cur; } // output top k values ...
``` // input int n, k; cin >> n >> k

Full text and comments »

  • Vote: I like it
  • +142
  • Vote: I do not like it

137.
By robinyqc, history, 2 years ago, In English
Using bitset to Count Dominating Pairs in High Dimensions Hi everyone! Here I want to share a method to count dominating pairs in high dimensions, while the number of points ($n$) is small but the dimensionality ($k$) is large (like $n = 32768, k = 8$). The problem of counting dominating pairs in K-Dimension is as follows: > For two $k$-tuples $a = (a_0, a_1, \dots, a_{k - 1})$ and $b = (b_0, b_1, \dots, b_{k - 1})$, define $dom(a, b) = \prod\limits_{i = 0}^{k - 1}[a_i \geq b_i]$, which outputs $1$ if each $a_i$ is greater than or equal to $b_i$ ($a$ dominates $b$), otherwise $0$. > > Given $n$ $k$-tuples $t_0, t_1, \dots, t_{n - 1}$, for each $i \in [0, n)$, compute $g(i) = \sum\limits_{j = 0}^{n - 1} dom(t_i, t_j)$. When $k = 2$, the problem simplifies to counting inversions, solvable directly using a Fenwick Tree. For $k = 3$, one can consider a Divide and Conquer (D&C) approach, achieving a complexity of $O(n \log^2 n)$, which is excellent. Alternatively, a K-D Tree approach achieves $O(n \sqrt{n})$ complexity, also a goo...
## Brute Force Approach, An optimized brute force approach involves using bitset to enhance efficiency., At $k = 5$, the Divide and Conquer approach is notably less efficient than brute force, and the K-D

Full text and comments »

  • Vote: I like it
  • +47
  • Vote: I do not like it

138.
By Proofy, 3 years ago, In English
[Tutorial] Investigating the Harmonic Numbers #### **Introduction** This blog contains well-known facts and techniques about Harmonic Numbers that are scattered all over editorials of some problems, comments, and some parts of blog posts. The place where I found most of the facts explained here is the brilliant blog by [user:Nisiyama_Suzune,2023-07-08] about [Möbius inversion](https://codeforces.me/blog/entry/53925). However, for the untrained eye, this blog may seem as if it's investigating something advanced and the facts explained inside will be missed. Moreover, there were some omitted proofs, so I thought it would be nice to collect all these facts/techniques in one place and add their proofs in (hopefully) an understandable but precise style, which would be useful for many. ---- For starters, the $n$th harmonic number, $H_n$, is the sequence $\displaystyle H_n = \sum_{i = 1}^{n}\frac{1}{i}$. We will investigate two techniques related to this sequence. ---- #### **1. Upper bound for Harmonic Numbers** We b...
This is very useful whenever you want to brute force all divisors of numbers in a range $[1, N

Full text and comments »

  • Vote: I like it
  • +140
  • Vote: I do not like it

139.
By chenmark, history, 10 years ago, In English
Rating the Difficulty of Codeforces Problems **Update:** Due to popular request, we created a script for you to generate your own rating profile. For detailed instructions, refer to our [ui page on github](https://github.com/yjiao/codeforces-api/tree/master/ui). We plan to rewrite our code in Javascript to expand functionality, but hopefully this is helpful in the meantime. Please let us know if you have any suggestions! This project was written jointly with [user:yj12,2016-07-28]. Several heuristics exist for finding suitable practice problems on Codeforces. One common piece of advice is to sort all problems by the number of solvers and to work down the list. However, the number of solvers depends on a number of factors, including the recency of the contest, and the date and time the contest was held. Another heuristic is to try to solve problems at a certain level, for instance, all Div. 1 C problems. However, the difficulty of such problems can vary greatly from contest to contest. We decided to create a better measur...
next, followed by problems without any tags. “Implementation” and "brute force " problems appear to be

Full text and comments »

  • Vote: I like it
  • +429
  • Vote: I do not like it

140.
By tunyash, 14 years ago, translation, In English
Editoral Codeforces Round #122 Please, report me about every grammar mistake, you see. Thank you. **Problem <<Exams>>** Let's notice that $2n \le k \le 5n$. If $k < 3n$ author has to get $2$ on some exams. There are $3n-k$ such exams and that's the answer). If $3n \le k$ author will pass all exams (answer is $0$). **Problem <<Square>>** Let the pencil move by the line and put crosses through every $(n+1)$ point. Lets associate every point on the line with point on square perimeter. Namely, point $x$ on the line will be associated with point on square perimeter that we will reach if we move pencil around square to $x$ clockwise. Then lower left corner will be associated with all points $4np$ for every non-negative integer $p$. Crosses will be associated with points $k(n+1)$ for some non-negative $k$. Nearest point of overlap of two families of points will be in point LCM($n+1$, $4n$). Then we will put $\frac{LCM(n+1,4n)}{n+1} + 1$ crosses. **Problem "Cutting Figure"** Translation by [user:moskupo...
The algorithm: Check answer 1. We can simply brute-force the square to delete, and for each

Full text and comments »

  • Vote: I like it
  • +116
  • Vote: I do not like it

141.
By kalimm, history, 9 years ago, In English
How not to perform well on life(With how not to perform well on ICPC bonus) First of all, for a long time I wanted to write this blog but I keep delaying it and finally here I am. After seeing [user:matthew99,2017-08-23]'s blog I decided to my time has come. I really wanted to write like him but my English skills aren't enough to use "you would" dozens of times. So I will explain how I didn't perform well in my life, and if you do same things you will end up succeed at failing in your life. And it's very important to say at this point, I'm very bad at English, so if you're disgusted you can stop right there and I'm truly sorry about it. **TLDR** : I am a loser. I was a regular student before high school. I interested with math olympiads little bit but I didn't get even a national medal just a several contests. By the way I won a The New iPad. So I am passing that times and coming to high school. In our country national eliminations goes like that, paper based elimination at may, national OI at december, team selection contest at march/april. High s...
solved one of them like 2 hours. After that I got accepted with brute force at one of the problems

Full text and comments »

  • Vote: I like it
  • +222
  • Vote: I do not like it

142.
By macaquedev, 8 months ago, In English
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) ...
Since $n$ is small, it is enough to brute force all possible pairs $(x, y)$. The answer is the

Full text and comments »

  • Vote: I like it
  • +55
  • Vote: I do not like it

143.
By L_Wave, history, 3 years ago, In English
Calculating Riordan Array T(n,k) In O(1) Time Hi, CodeForces! I recently found a way to calculate Riordan Array $T(n,k)$ in $\Theta(1)$ time. So I'm going to share it with you :D **Note: ** We define $[P]$ as the Iverson bracket, with value $1$ if $P$ is true and $0$ if $P$ is false. #### Definition of 'Riordan Array' in this blog In this blog, Riordan array **doesn't have much to do with generating functions**. I would choose to define it as [A201780 in OEIS](https://oeis.org/A201780), or as the following formula: $$ T(n,k)=\begin{cases} 0,&k\le 0;\\ 0,&n<k;\\ 1,&n=k=1;\\ 0,&n=2,k=1;\\ 1,&n=3,k=1;\\ 2T(n-1,k)+T(n-1,k-1),&\text{otherwise}. \end{cases} $$ It is clear enough that the OEIS page gave only the $\Theta(n^2)$ method to calculate it, as above shows. #### How did I become interested in it? Recently I solved an interesting problem. In the problem it needs to calculate $T(n,k)$ in $\Theta(1)$ time, if we can calculate the binomial coefficient $\binom{x}{y}$ in $\Theta(1)$'s time. <spoiler sum...
**All the observations down are based on a brute force code's output. So you may write a `bfs` one

Full text and comments »

  • Vote: I like it
  • +89
  • Vote: I do not like it

144.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 150 English Solutions #A &mdash; 500 Yen Coins We are essentially asked whether $500K \geq X$. We can determine this using an if statement. If you'd like to be fancy, you can shorten your code using the ternary operator, printing $\texttt{500K >= X ? "Yes" : "No"}$. Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc150/submissions/9382642) --- #B &mdash; Count ABC There are several ways to do this. The first is to compute each three-letter substring of $S$, either through brute force or your language's substring computation function, then comparing them to "ABC". Another, which I implemented, is to simply iterate over each position in the string up to $N-3$, using zero-indexing, and check whether $S[i] = A$, $S[i+1] = B$, and $S[i+2] = C$. If so, we increment the answer. Either way, we can maintain a count of "ABC" substrings and return it at the end. (Of course, we theoretically could use a more complicated pattern matching algorithm, but because the str...
$, either through brute force or your language's substring computation function, then comparing them to

Full text and comments »

  • Vote: I like it
  • +25
  • Vote: I do not like it

145.
By iframe_, 23 months ago, In English
Cutting and folding trees: An unorthodox approach to pattern-matching I was shown [this JOI problem](https://oj.uz/problem/view/JOI18_snake_escaping) by [user:jasonwei08,2024-12-27] today. The problem statement boils down to: Given an array $A$ of $2^L$ integers, $1 \leq L \leq 20$, process $1 \leq Q \leq 10^6$ queries. For each query, consisting of a length-$L$ pattern of either `0`, `1`, or `?`, report the sum of all $A_j$ where the binary representation of $j$ matches the pattern. The `?` character acts as a wild card. For example, the pattern `1?` matches both `10` and `11`. --- We will start with the following brute force approach: Build a binary tree whose leaves correspond to all binary strings of length $L$, in lexicographic order. Each node's parent corresponds to the string obtained by deleting its last character, e.g. the parent of `11011` is `1101`. We allow the tree's root node to be the empty string. It can be shown that this procedure yields a perfect binary tree. We can visualize each query as a set of leaves in this tr...
We will start with the following brute force approach:

Full text and comments »

  • Vote: I like it
  • +93
  • Vote: I do not like it

146.
By Not-Afraid, history, 6 years ago, In English
Bash Script for Stress Testing[Code with explanation] Hello Codeforces community. ~~~~~ Tl;dr: The script is specifically for *Unix and can be used to stress test `C++` solutions. It can be easily modified to work with python or java. To use it in windows you can download Ubuntu terminal which is officially available on Microsoft Store and then use it or you can modify the script to work in cmd by changing the .out files to .exe and a bit of syntax for cmd. ~~~~~ **Note**: If you don't want to read this lengthy blog, just go to [this](https://github.com/bhupixb/Stress-Testing-bash-script) repo and follow the instructions of readme. <br> First let me tell you what stress testing is if you don't know, Stress testing is technique using which we can run our solution (which we think might fail/is failing) on a number of random test cases and match it's output with the output of a solution which is a brute force solution or accepted solution of someone else.<br> If you don't know why and when to use stress testing you can use [...
# run brute force solution, take input from above generated test case i.e. from input1.txt, : -b <brute-file> Specify the name of cpp file having brute force solution. [required] -m

Full text and comments »

  • Vote: I like it
  • +52
  • Vote: I do not like it

147.
By Kogut_Ivan, 11 months ago, In English
Codeforces Round 1072 (Div. 3) Editorial We hope you enjoyed the contest! Thank you for participating! This is our third official round on Codeforces, so we would be happy to hear your feedback in the comments and in the mini-survey below. <spoiler summary="How did you like the contest?"> - Excellent: - Good: - Average: - Bad: - Terrible: </spoiler> <spoiler summary="Which problems did you like (you can choose multiple)?"> - A: - B: - C: - D: - E: - F: - G: </spoiler> <spoiler summary="Which problems did you not like (you can choose multiple)?"> - A: - B: - C: - D: - E: - F: - G: </spoiler> [problem: 2184A] Idea: [user:fstilus,2026-01-12]; developer: [...
Why is brute force ineffective? How can it be improved?

Full text and comments »

  • Vote: I like it
  • +30
  • Vote: I do not like it

148.
By rabaiBomkarBittalBang, 5 years ago, In English
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...
Let’s brute force check all substrings of length <= 3 and print the

Full text and comments »

149.
By PR_0202, 6 years ago, In English
Stress testing / bug finding in you code without using Bash Many times we are stuck in a problem and don't know the edge case in which the programme fails, specially during long challenges or monthly challenges we think our solution is correct but it gives WA on submition. So, I'm sharing my idea to stress test your code with a bruteforce or an unoptimized solution without using bash. So, basically what you have to do is first write a brute force solution and put it in the "Solve" function and put the optimized ones in the second one. change the function and return value according to the question also if you want then make the test generating while loop infinite also adjust the array size according to the constraints of your bruteforce solution. I would recommend you to use **Code-blocks** or **VS Code** for this purpose. **Code begins:** ~~~~~ #include <bits/stdc++.h> using namespace std; const int N = 100005; const int MOD = 1e9 + 7; #define show(arr) { for (auto x: arr) cout << x << " "; cout << '\n'; } mt19937 ...
//write here your brute force solution

Full text and comments »

  • Vote: I like it
  • +55
  • Vote: I do not like it

150.
By Baraa-Ahmed, 10 months ago, In English
Zaglol FCDS Contest Solutions **[Zaglol Contest &mdash; FCDS level 1:](https://codeforces.me/gym/106350)** Problem [A. Zaglol welcoming](https://codeforces.me/gym/106350/problem/A): <spoiler summary="Solution"> Print **FCDS** </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; int main() { cout << "FCDS" << endl; } ~~~~~ </spoiler> Problem [B. Baby Baraa in ALBAIK](https://codeforces.me/gym/106350/problem/B): <spoiler summary="Hint"> Notice that the values of $a_i$ are bounded: $(1 \le a_i \le 100)$. </spoiler> <spoiler summary="Solution"> It is easy to see that the $O(N^2)$ brute-force approach will be too slow for the given constraints. Therefore, we need a faster way to count, for each $i$, how many indices $j > i$ satisfy $(a_i > a_j)$. Since that the values of $a_i$ are bounded: $(1 \le a_i \le 100)$, we can use a frequency array to count how many numbers smaller than a given value appear to its right. We process the array fro...
This avoids the brute force solution and works in linear time $O(n)$.

Full text and comments »

  • Vote: I like it
  • +18
  • Vote: I do not like it

151.
By Hasan0540, history, 10 years ago, In English
[ GYM Tutorial ] 2016 ACM Amman Collegiate Programming Contest ### [A. Coins](http://codeforces.me/gym/101102/problem/A) Instead of having one DP table that combines all states for both Hasan and Bahosain, and having too many parameters (and therefore, huge complexity), we can build two tables, one for each person. Let $A[0][i]$ be the number of ways in which Hasan can pay $i$ dollars using all coins from index $0$ to the end, and $B[0][i]$ similar but for Bahosain, then we can compute the final answer by using these two tables as follows: ~~~~~ for (int hasan = 0; hasan <= W; ++hasan) { int bahosain = W - hasan; if (abs(hasan - bahosain) <= K) res += A[0][hasan] * B[0][bahosain]; } ~~~~~ Building each table is a simple DP problem. Complexity: $O((N+M)*W)$ ### [B. The Little Match Girl](http://codeforces.me/gym/101102/problem/B) Instead of trying to move some sticks as the problem suggests, let's count the total number of matchsticks we have and build the maximum possible number of $N$ digits using all thes...
We will start with the brute force solution and see if it's going to work. Here are some notes:

Full text and comments »

  • Vote: I like it
  • +8
  • Vote: I do not like it

152.
By MofK, history, 3 years ago, In English
Codeforces Global Round 25 Editorial Hi, we hope you enjoyed our problems! For the playlist of songs used in the problem statements, click [this link](https://www.youtube.com/playlist?list=PLTVdHvnX6LZhAJre49E7M7tpGA30WlBM3). [problem:1951A] Author: [user:MofK,2024-04-06] <br> Prepared by [user:Kuroni,2024-04-06] <br> First solve: [user:xiachong,2024-04-06] at 00:01 <spoiler summary="Tutorial and Implementation"> [tutorial:1951A] [submission:255371605] </spoiler> <spoiler summary="Rate this problem"> Yay Meh Nay Banger song </spoiler> [problem:1951B] Author: [user:MofK,2024-04-06] <br> Prepared by [user:Kuroni,2024-04-06] <br> First solve: [user:pavement,2024-04-06] at 00:05 <spoiler summary="Hint 1"> What is the condition for your cow to win her first match? </spoiler> <spoiler summary="Hint 2"> If your cow is not already winning her first match, there are at most two candidate positions you can swap her to. </spoiler> <s...
uses partitions of at most size $2$, therefore one can "solve" the problem by brute forcing every

Full text and comments »

  • Vote: I like it
  • +55
  • Vote: I do not like it

153.
By SorahISA, 10 months ago, In English
[Tutorial] DP on Edges *This blog post is a submission for the [Codeforces Month of Blog Posts Pt. III](https://codeforces.me/blog/entry/149422) challenge. Thank you [user:cadmiumky,2026-02-12] for the initiative!* ## Introduction Problem <spoiler summary="ICPC North America Championship 2025, Problem B - Circle of Leaf"> Link: <https://qoj.ac/contest/2041/problem/11357> Given a rooted tree with $n$ nodes, construct a undirected graph as follows: - For each edge $(u, v)$ in the tree, add an edge between $u$ and $v$. - For each leaf node $u$ in the tree, add an edge between $u$ and the root. Please calculate the number of spanning trees of the resulting graph, modulo $998\,244\,353$. Note that the resulting graph may contain multiple edges between the same pair of nodes. Constraints: - $n \le 200\,000$ </spoiler> Before tackling the problem, let's first try some simple examples. The notation we use will also be introduced in the examples, so please try to understand them ...
and $3k$ edges left, and then solve the problem by brute force.

Full text and comments »

  • Vote: I like it
  • +80
  • Vote: I do not like it

154.
By MarcosK, 4 years ago, In English
2022-2023 ICPC Latin American Regional Programming Contest — Unofficial editorial Hi everyone! The [2022-2023 ICPC Latin America Regional Programming Contest](https://codeforces.me/gym/104252) was held last weekend. Given that (as far as I know) there is no official editorial for the problems, I decided to create one. Please notice that, given that these are not the official solutions, there can be typos/mistakes in the explanations. Feedback is always appreciated :) I would like to thank [user:lsantire,2023-03-22] for reviewing the editorial and providing valuable feedback. Don't hesitate to reach out to me if you have any questions/suggestions. Thank you! [problem:104252A] <spoiler summary="Hint"> Think in which case a person loses money. Remember we can choose the order in which events happen. </spoiler> <spoiler summary="Solution"> Let's fix a person $p$ and call $a$ and $b$ to the people $p$ will ask for money. It's easy to see that $p$ loses money if $a$, $b$ and $p$ are asked for money before $p$ requests $a$ or $b$ to pay. This ...
some annoying case analysis, or even in $\mathcal{O}(n^2)$ by brute force with some observations.

Full text and comments »

  • Vote: I like it
  • +120
  • Vote: I do not like it

155.
By AboAbdoMC, 3 years ago, In English
[EDITORIAL] Syrian Private Universities Collegiate Programming Contest 2023 [A &mdash; G Game](https://codeforces.me/gym/104426/problem/A) Author: [user:Blade-Master,2023-07-10] <spoiler summary="Tutorial"> </spoiler> <spoiler summary="Solution"> </spoiler> [B &mdash; Permutation Tree](https://codeforces.me/gym/104426/problem/B) Author: [user:Space-Time-,2023-07-10] <spoiler summary="Tutorial"> This problem is solved greedily. Let $v$ be the minimum unassigned node in the tree. We have to assign it the minimum possible value. This can be done by assigning each unassigned value on the simple path from the root $x$ to $v$ the minimum possible value. This can be done in $O(n)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int n , x , p [200005] , k , pr [200005]; vector < int > gr [200005]; void dfs ( int x , int pt ) { pr [x] = pt; for ( auto u : gr [x] ) { if ( u == pt ) continue; dfs ( u , x ); } } int up ( int x ) { if ( p...
We can solve this problem by brute force.

Full text and comments »

  • Vote: I like it
  • +17
  • Vote: I do not like it

156.
By oursaco, history, 3 years ago, In English
Codeforces Round 914 (Div. 2) Editorial Sorry for the weak pretests on A :(. We hope you enjoyed the round nonetheless. [problem:1904A] Idea: [user:Apple_Method,2023-12-09] <br> Preparation: [user:Apple_Method,2023-12-09]/[user:oursaco,2023-12-09] <br> Analysis: [user:lunchbox,2023-12-09] <spoiler summary="Solution"> There are at most $8$ positions of the knight that can attack a single cell. Therefore, we can find all $8$ positions that attack the king and the $8$ positions that attack the queen and count the number of positions that appear in both of these lists. </spoiler> <spoiler summary="Code"> ```c++ #include <bits/stdc++.h> using namespace std; int dx[4] = {-1, 1, -1, 1}, dy[4] = {-1, -1, 1, 1}; int main(){ int t; cin >> t; for(int i = 0; i < t; i++){ int a, b; cin >> a >> b; int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; set<pair<int, int>> st1, st2; for(int j = 0; j < 4; j++){ st1.insert({x1+dx[j]*a, y1+dy[j]*b}); ...
For $k=2$, let's brute force the first operation. If the newly created value is $v$, then it is

Full text and comments »

  • Vote: I like it
  • +135
  • Vote: I do not like it

157.
By hxu10, history, 2 years ago, In English
My Meta hacker cup experience I have participated in the Meta Hacker Cup for four consecutive years: 2021, 2022, 2023, and 2024. After receiving the T-shirt today, I would like to share my experiences and progress. **2021: A newbie want a T shirt** ![2021](https://github.com/user-attachments/assets/9abd55cc-3008-47ba-9399-a301a35bed51) This year, I was a complete newbie. The first two rounds lasted over 24 hours, which gave me more time to solve the problems, so my rank looked good. However, Round 2 was only 3 hours long, and it turned out to be a complete disaster for me. I got stuck on the first problem and doubted my solution repeatedly. Although I finally solved it 30 minutes before the contest ended, I had no time left for the other problems. In the end, I only solved one problem and ranked 2700+, which meant I didn’t even qualify for a T-shirt. I shared my result with some Meta HR representatives, but they didn’t respond. I applied to several positions at Meta, but my resume was rejected. I also...
hours considering numerous corner cases, writing a brute-force solution, and using a random generator to

Full text and comments »

  • Vote: I like it
  • +138
  • Vote: I do not like it

158.
By yse, 7 months ago, In English
Codeforces Round 1096 (Div. 3) — Editorial Thanks for participating in the contest. I hope you enjoyed the problems :) <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | H | |----------------------------------|-----|-----|------|------|------|------|------|------| | [user:Argentum47,2026-04-23] | 800 | 800 | 900 | 1200 | 1500 | 1700 | 1900 | 2200 | | [user:simplelife,2026-04-23] | 800 | 800 | 1000 | 1300 | 1500 | 1800 | 1800 | &mdash; | | [user:lina_os,2026-04-23] | 800 | 800 | 1000 | 1100 | 1400 | &mdash; | &mdash; | &mdash; | | [user:-firefly-,2026-04-23] | 800 | 800 | 900 | 1400 | 1600 | 1900 | 2000 | 2300 | | [user:Syrianooo,2026-04-23] | 800 | 800 | 900 | 1200 | 1300 | &mdash; | &mdash; | &mdash; | | [user:Mousa,2026-04-23] | 800 | 800 | 1000 | 1300 | 1600 | 2000 | 2300 | 2100 | | [user:yse,2026-04-23] | 800 | 800 | 1000 | 1200 | 1400 | 1600 | 1900 | 2100 | </spoiler> <spoiler summary="Ra...
Instead of only expanding from the $3$ possible candidates, we can brute

Full text and comments »

  • Vote: I like it
  • +84
  • Vote: I do not like it

159.
By dinohaur, history, 17 months ago, In English
CEOI 2025 discussion Since CEOI 2025 is over and the tasks and test data have been published, can we discuss the solutions here? Here are the [tasks](https://ceoi2025.utcluj.ro/category/13). Upd: you can find the tasks [here](https://codeforces.me/blog/entry/144670?#comment-1293960) (for now) Upd: https://github.com/asociatia-sepi/archive/tree/main/CEOI-2025 Upd: I was upsolving this CEOI now for practice and I decided to write some solutions because I couldn't find them. ## Boardgames ### Solution 1 This is the approach from the official editorial. The core idea relies on a **divide and conquer** strategy: 1. Initially, we invoke the function $f(1, n)$. 2. Find the position $i$ closest to the border such that $i$ and $i+1$ are not in the same connected component. 3. If the subgraph from $L$ to $R$ is connected, we can just return $1$. 4. Otherwise, we split the problem and return $f(L, i) + f(i+1, R)$. The main implementation challenge here is to efficiently maintain graph con...
))$. Carefully brute-forcing all valid prefixes that could potentially form a split can similarly be optimized to

Full text and comments »

  • Vote: I like it
  • +70
  • Vote: I do not like it

160.
By dmkozyrev, history, 3 years ago, In English
[Tutorial] Quick start in solving problems on GPU + CPU Hello, codeforces! Do you have modern GPU and CPU and want to calculate something with them, but you don't know how to do it? Dont be upset, because you can read this blog and run your first GPU program on your AMD/Intel/NVIDIA GPU. I will describe an installation process and then we will dive into the C++ code. As an example, we will calculate a lot of mazes for [Bug Game](https://codeforces.me/blog/entry/115144) in parallel. For doing this in simple way, we will use library [Boost.Compute](https://www.boost.org/doc/libs/1_80_0/libs/compute/doc/html/index.html), which is a C++ STL-style wrapper over OpenCL library. [cut] ... Installation for MacOS (Apple M1 Pro) ================== As [user:Gosunov,2023-06-10] said, `OpenCL` and `g++` are pre-installed on `MacOS`. Everything that you have to do is install `Boost` with command `brew install boost`. After this you will be able to compile your program with command `g++ -std=c++17 -O3 -I/opt/homebrew/Cellar/boost/1.81.0_1/...
code. Some genetic or randomized algorithms, or brute force need to calculate the answer for a whole

Full text and comments »

  • Vote: I like it
  • +118
  • Vote: I do not like it

161.
By jay_jayjay, history, 4 years ago, In English
Indigo Contest 2023 Unofficial Editorial As the official editorial is promised to come out later, I will write an unofficial editorial for now. Some of the solutions are from my teammate [user:tcmmichaelb139,2023-04-17] orz. Contest: https://www.hackerrank.com/indigo-coding-competition ## Easy These problems are quite trivial, so I will only provide solutions: <spoiler summary="P1"> ~~~~~ n=int(input()) arr=[] for i in range(n):arr.append(input().strip().replace('x','')) for i in range(n): cnt=arr[i].count('y') arr[i]=arr[i].replace('y','') arr[i]+=cnt*'y' arr=sorted(arr,key=lambda x:(-len(x),x)) print('\n'.join(arr)) ~~~~~ </spoiler> <spoiler summary="P2"> Michael's solution: ~~~~~ #include "bits/stdc++.h" using namespace std; string pi = "31415926535897932384626433832... (truncated copy-paste from internet)"; void solve() { string s; cin >> s; for (int i = 0; i < s.length(); i++) if (s[i] != pi[i]) { cout << i << '\n'; r...
average time is a lot less, so brute force works.

Full text and comments »

  • Vote: I like it
  • +25
  • Vote: I do not like it

162.
By aryanc403, 2 years ago, In English
Codeforces Round 973 Solution hints [problem:2013A] <spoiler summary="Idea"> In each second, we will blend $\min(x, c)$ fruits. So time taken is $\displaystyle \left \lceil \frac{n}{\min(x, c)} \right \rceil$ </spoiler> Submission &mdash; [submission:282005858] [problem:2013B] <spoiler summary="Hint 1"> $n$ is the winner. $n-1$ will lose only against $n$. </spoiler> <spoiler summary="Hint 2"> For others, if we make them first against $n-1$ and atlast we have $n-1$ and $n$ fight, their score will be added. </spoiler> <spoiler summary="Hint 3"> So the final answer will be $A_1+A_2+....+A_{n-2}+A_{n}-A{n-2}$ </spoiler> Submission &mdash; [submission:282011553] [problem:2013C] <spoiler summary="Hint 1"> Let's say we know some string $s$ is a substring of $t$. How can we extend it to find char just after this? </spoiler> <spoiler summary="Hint 2"> The idea is to query for $s0$ and $s1$; if one of them returns true, add that char to s and continue again. </spoiler> <spoiler s...
Now, we can brute force game theory problem. FindWinner(aliceIdx

Full text and comments »

  • Vote: I like it
  • +3
  • Vote: I do not like it

163.
By SoCloseButStillSoFar, 4 years ago, In English
Codeforces Round #840 (Div. 2) and Enigma 2022 — Cybros LNMIIT Editorial We hope you liked the problems! Unfortunately, problem C turned out to be harder than usual. Please read its editorial, we hope you'll find that the intended solution is not that hard. # [problem:1763A] Idea: [user:DreadArceus,2022-12-19]<br> Prepared by: [user:DreadArceus,2022-12-19] <spoiler summary="Hint 1"> Which $1$s in the binary representation cannot be changed to $0$. </spoiler> <spoiler summary="Hint 2"> Similarly, Which $0$s in the binary representation cannot be changed to $1$. </spoiler> <spoiler summary="Need more hints?"> Considering the last two hints, try to maximize the maximum element and minimize the minimum element. </spoiler> <spoiler summary="Solution"> In the minimum element, we want to make every bit $0$ when possible, it won't be possible to set a particular bit to $0$ when that bit is set in all the elements of $a$. Therefore, the minimum value we can achieve after performing the operations is the bitwise AND of all the elements of $a$...
[submission:186019483] Author: [user:satyam_343,2022-12

Full text and comments »

164.
By Endagorion, 12 years ago, In English
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...
greedy procedure or some kind of clever brute-force can be implemented to solve the problem in $O(n

Full text and comments »

  • Vote: I like it
  • +172
  • Vote: I do not like it

165.
By SPyofcode, history, 5 years ago, In English
[Variants] An interesting counting problem related to square product ## The statement: Given three integers $n, k, p$, $(1 \leq k \leq n < p)$. Count the number of array $a[]$ of size $k$ that satisfied - $1 \leq a_1 < a_2 < \dots < a_k \leq n$ - $a_i \times a_j$ is perfect square $\forall 1 \leq i < j \leq k$ Since the result can be big, output it under modulo $p$. For convenient, you can assume $p$ is a large constant prime $10^9 + 7$ **Notice that in this blog, we will solve for generalized harder variants** **For original problem you can see in this blog [[Tutorial] An interesting counting problem related to square product](https://codeforces.cc/blog/entry/96379)** --- ## Extra Tasks **These are harder variants, and generalization from the original problem. You can see more detail [here](https://codeforces.cc/blog/entry/96379)** *Marked as solved only if tested with atleast $10^6$ queries **[Solved A](https://codeforces.cc/blog/entry/964...
So instead of a brute-forces, you can fix $2$ numbers and then you factorize it to the form of

Full text and comments »

  • Vote: I like it
  • +164
  • Vote: I do not like it

166.
By Shayan, 21 month(s) ago, In English
I went from Newbie to Expert in less than 3 months & how — Text + Video **Note: This is what I did. This is what I always tell my students. This is what I’m sharing because I believe it is very helpful for people here.** **1. Are the tips I’m sharing the only way to reach Expert?** No. **2. Is it the best way to reach Expert?** Not necessarily, but I think so. **3. Can I leave hateful comments below?** Do something more valuable lol. Write another blog explaining how you did it, or even a comment works. **4. Are you actually helping or just promoting your video?** First, regardless of any benefit to me, this is valuable information for people. Second, I genuinely don’t need the promotion. 32,000 people have already watched it in a week, and this blog might add like 1,000 more, doesn’t make any noticeable difference for me. _____________________________________________________________________ **Two types of advice** I believe advice generally falls into two types. Some advice is not controversial, so everyone agrees on it. By definition...
like implementation, brute force, math, greedy, and DP. (DP is the only one that requires serious

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

167.
By low_, history, 7 years ago, In English
HCW '19 Team Round Editorial This is an editorial blog for [contest:102279]. Any further question can be asked in the comments, I'll try to answer all the questions. Please, do not private message or email me, your question could be the same as others', and I really hate to answer one question multiple times. >:( [problem:102279A] ------------------ Author: [user:low_,2019-07-22]. <spoiler summary="Tutorial"> To solve the problem, you'll only need to note that in $(N+1)$-th turn: Seo moved through exactly $(N+1)*V_s$ property, that is exactly $V_s$ full round of the board, so that he end up in $1$ afterwards. The same happens with B21 and Lowie. After that, the game keeps repeating itself. We can conclude that: if there isn't any event of one paying other in the first $3*(N+1)$ turns, it will never happen, so we can output $3000000000$. Otherwise, we can find the first event of it by brute force in $O(3*(N+1))$ time complexity. Maximum time complexity: $O(3*(N+1))$. </spoiler> [problem:102279B]...
Read the input as a string, then just use simple brute force to, This problem requires no brainstorming at all. You can just brute

Full text and comments »

  • Vote: I like it
  • +27
  • Vote: I do not like it

168.
By steveonalex, 2 years ago, In English
Convex Hull Trick, but slightly cooler? _I didn't see any documentary and blog on this topic, so I guess it's Codeforce blog time ._ [Blog in HackMD if you prefer it](https://hackmd.io/@steveonalex/SJhtx_aGJg) **Prerequisite:** - Convex Hull Trick. ## 1) The OG Convex Hull Trick: This blog is not a tutorial to Convex Hull Trick, so I would assume that you guys already know about it before reading this. However, I'll briefly recap for the sake of completeness. **Problem Statement:** Given $n$ lines of the form $y = a_i * x + b_i$ and $q$ random queries $x_j$. For each query, calculate the value $max(a_1*x_j + b_1, a_2*x_j + b_2, ..., a_n*x_j + b_n)$. - Constraint: $n, q \leq 3*10^5$, $a_i, b_i, x_j \leq 10^9$. - Time limit: 1s This is a well-known problem, and you can find tutorial for this basically everywhere. In short, we will sort all the lines in ascending order of their slope, and remove all of the redundant lines, as shown in my beautiful painting below (A line is redundant if it lies entir...
Then we will do the same thing for the second CHT i.e. brute forcing through the $k$ nearest lines

Full text and comments »

  • Vote: I like it
  • +75
  • Vote: I do not like it

169.
By Errichto, 10 years ago, In English
How to stress test two programs millions times? Help Both a participant and a contest organizer sometimes wants to stress test their solution with the brute force. Sometimes random tests are quite weak and one needs many thousands (and sometimes millions) of them to become sure about the correctness. The thing is that running a program is quite slow itself, what may hurt if the computation part is fast. On my laptop running a C++ program with empty main() one thousand times takes 1.3s, what doesn't satisfy me. How to make it faster? I recently prepared a problem with a binary grid (SRM 699, div1-hard TwoSquares) and I wanted to be very careful about the correctness. I wrote slow solutions in C++ and the intended one in Java. Only then I realized how slow usual stress testing is. If they all were in one language, I would quite easily get everything into one program with classes (structs) and I would just run it once, without any overheads. But since the languages were different, I had to rewrite one solution, what not only requ...
brute force. Sometimes random tests are quite weak and one needs many thousands (and sometimes

Full text and comments »

  • Vote: I like it
  • +58
  • Vote: I do not like it

170.
By shsh, history, 9 months ago, In English
HPI 2026 Editorial Thank you to everyone who attended this year's Harker Programming Invitational (HPI)! If you haven't already, we would really appreciate it if you filled out our [feedback form](https://forms.gle/opwQmMZPBtM7uWCt9) so we can make our contest even better next year. Also, [Novice](https://codeforces.me/gym/106410) and [Advanced](https://codeforces.me/gym/106409) problems have been uploaded to the Gym for upsolving. *Note:* Only solutions for the Advanced division are presented here, but solutions for Novice-only problems (Yash is Cross-Eyed, Repetition, Skills) can be provided upon request. ## Harker!! <spoiler summary="Solution"> Pretty straightforward: most languages have a standard library function for finding a given substring in a string, so you can just use that. </spoiler> <spoiler summary="Code (Team Aarav)"> ```python def solution(s): if "harker" in s: return 1 return 0 T = int(input()) for _ in range(T): s = input() prin...
$, then brute force all pairs.

Full text and comments »

Tutorial of HPI 2026 Advanced
Tutorial of HPI 2026 Novice
  • Vote: I like it
  • +28
  • Vote: I do not like it

171.
By Bring, history, 4 years ago, In English
Solution: CF Round #830 (Div. 2) D1&D2 Balance ##### [For better experience please click here.](https://www.cnblogs.com/BrianPeng/p/16827008.html) First CF round at Cambridge. Solved A,B,D1 in the round. Dropped from purple to blue... Still a long way to go... # Solution: CF Round #830 (Div. 2) D1&D2 Balance ## Easy Version ### Brute-force Evidently the most brute-force way is to create a set to collect the $x$ added. Then for all query with $k,$ check $k,2k,3k,\cdots$ till the first multiple of $k$ that is not contained in the set. Output it. Obviously it is doomed to TLE, especially when you are queried by the same $k$ multiple times with very large $k\text{-mex}$. ### Becoming Elegant We try to optimize the brute-force by reducing the time cost if queried by the same $k.$ As there is no remove, if you are queried by $k$ and you find the $k\text{-mex},$ it is obvious that the next time if you are queried by the same $k,$ the answer must be greater than or equal to the previous one. Therefore, we can ...
### Brute-force

Full text and comments »

  • Vote: I like it
  • +44
  • Vote: I do not like it

172.
By lucifer1004, history, 6 years ago, In English
My Editorial for Google Kick Start 2021 Round B # Google Kick Start 2021 Round B Tutorial [中文版 | Chinese version](https://cp-wiki.vercel.app/tutorial/kick-start/2021B/) Here are my solutions to Google Kick Start 2021 Round B. Some of them (C & D) are not optimal, albeit they passed all the test cases. ## Problem A &mdash; [Increasing Substring](https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435a5b/000000000077a882) We simply go ahead and try appending the current letter after the last letter. Complexity: - Time complexity is $\mathcal{O}(|S|)$. - Space complexity is $\mathcal{O}(|S|)$. <spoiler summary="Code (C++)"> ~~~~~ #include <cstdio> #include <iostream> #include <vector> using namespace std; template <typename T> void read(T &x) { x = 0; char c = getchar(); T sig = 1; for (; !isdigit(c); c = getchar()) if (c == '-') sig = -1; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= sig; } class Solution { public: void solve(i...
The official solution leverages the concept of the prime gap and is a very beautifulbrute-force

Full text and comments »

  • Vote: I like it
  • +60
  • Vote: I do not like it

173.
By fushar, 13 years ago, In English
Codeforces Round #192 Editorial So! We hope you enjoyed the round. Internally, we called this round **Trollforces**, because as you knew, most solutions should be unexpected :) Some fun fact: there are ~ 30 pictures in this round, totaling ~ 144 KB. Here is the editorial, written with mixed point of views of all writers (hence "I" may refer to any of us). --- [problem:330A] by [user:dolphinigle,2013-07-20] **Long solution:** - Once an evil strawberry, always an evil strawberry (since they can’t be eaten). - Thus, if a row cannot be eaten before any eat is performed, it can never be eaten. - Same with column. - Thus, you can know which columns and which rows you can eat. - Just try to eat them all and calculate how many cells you actually eat. **Short solution:** - A row or a column cannot be eaten if it has at least one strawberry. - A cell cannot be eaten if both its row and its column cannot be eaten -- otherwise you can eat the row/column and eat it! If there are r' rows that canno...
Actually, we can do brute force when n <= 6, but this requires a special handling: when the largest

Full text and comments »

  • Vote: I like it
  • +122
  • Vote: I do not like it

174.
By aucoder123, history, 21 month(s) ago, In English
Invitation to GoForGold Long Challenge — Feb 2025 ####Introducing the Go for Gold February Long Challenge! Competitive programmers, get ready! The Go for Gold Long Challenge is back with its second iteration, bringing another thrilling opportunity to test your problem-solving skills and climb the leaderboard on Codeforces! After the success of the first iteration, we are excited to present yet another round of engaging and challenging problems for the community. Whether you're a seasoned competitor or just starting out, this contest is designed to offer a balanced mix of difficulty levels to help everyone push their limits. **What’s Special About This Challenge?** - Handcrafted Problems: The contest is a mix of some classical educational problems picked from CF and some fresh algorithmic challenges carefully curated to test your logical thinking, algorithmic optimisation skills, and competitive programming prowess. - Diverse Difficulty Levels: Problems ranging from beginner-friendly to advanced, ensuring that everyone has s...
Apply brute force and look at pattern? , Brute force can go upto O(n!). You can use bitmasking to

Full text and comments »

  • Vote: I like it
  • +63
  • Vote: I do not like it

175.
By THE_THUNDERSTORM_BEGINS, history, 21 month(s) ago, In English
two pointers overview this blog is an animated explanation of two pointers method as two pointers is not really considered an algorithm this blog will only talk about famous problems and how they are handled. this blog is not supposed to be hard it is targeted for under 1400 rating this blog was made to summarize HCPC-2025 training for two pointers at Homs university / Syria. overview ================== ###1. check if an array is sub sequence of another array ###2. check if an array is sub array of another array ###3. number of less or equal ###4. merge two sorted arrays ###5. number of sub arrays with sum less than or equal $X$ ###6. number of sub arrays with number of distinct elements less than or equal $X$ lets start: ###1. check if an array is sub sequence of another array checking that is relatively easy (easier than checking is sub array) name the arrays $a$,$b$ we need to check if $a$ is sub sequence of $b$ keep two pointers in $a$ and $b$ pointing to the first ele...
the brute force implementation is $O(m*n)$ but $kmp$ algorithm improves this to $O(n+m)$

Full text and comments »

  • Vote: I like it
  • +35
  • Vote: I do not like it

176.
By alexwice, history, 5 years ago, In English
Edu CF Round 120 Unofficial Editorial [Construct A Rectangle](https://codeforces.me/contest/1622/problem/A) <spoiler summary="A Editorial"> Let the stick lengths be $X, Y, Z$. The broken stick $X$ either forms two parallel sides or two perpendicular sides. In the first case, $X$ is even and $Y == Z$. In the second case, $X == Y+Z$. We try all choices of $X$. [A Solution](https://codeforces.me/contest/1622/submission/140867573) </spoiler> [Berland Music](https://codeforces.me/contest/1622/problem/B) <spoiler summary="B Editorial"> Say we dislike $L$ songs &mdash; those $L$ songs must have unique ratings $q_i$ from $1$ to $L$. To minimize the sum of $\|p_i - q_i\|$, we should keep $q_i$ in the same order as $p_i$. [B Solution](https://codeforces.me/contest/1622/submission/140868181) </spoiler> [Set or Decrease](https://codeforces.me/contest/1622/problem/C) <spoiler summary="C Editorial"> Optimal strategies can be described by $(x, k)$: decrease the lowest value by $x$, then set the largest $k...
Brute forcing small values, it seems we remove at most 3 values

Full text and comments »

  • Vote: I like it
  • +32
  • Vote: I do not like it

177.
By gojira, 13 years ago, translation, In English
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 ...
As the constraints suggest, the intended solution here is brute force. Note that there are only $2

Full text and comments »

Tutorial of Rockethon 2014
  • Vote: I like it
  • +101
  • Vote: I do not like it

178.
By huzecong, 13 years ago, In English
Codeforces Round #248 Editorial If you have any questions or suggestions, or if you have a solution different to ours that you want to share with us, feel free to comment below :) **Author solutions are added.** --- ###[Div. 2 A &mdash; Kitahara Haruki's Gift](http://codeforces.me/contest/433/problem/A) Denote $G$ as the sum of the weight of the apples. If $G/100$ is not an even number, then the answer is obviously "NO". Otherwise, we need to check if there is a way of choosing apples, so that the sum of the weight of the chosen apples is exactly $\frac{G}{2}$. A simple $O(n)$ approach would be to enumerate how many 200-gram apples do we choose, and check if we can fill the rest with 100-gram apples. We can also solve this problem using a classic knapsack DP. **Solution:** [submission:6712942] --- ###[Div. 2 B &mdash; Kuriyama Mirai's Stones](http://codeforces.me/contest/433/problem/B) Sort sequence $v$ to obtain sequence $u$. Sorting can be done in $O(n\log n)$ using quicksort. Now we ar...
A brute-force idea would be to enumerate all four edges of the block, checking can be done with two, A straightforward brute-force idea would be to enumerate all numbers in the interval $[l,r]$, and

Full text and comments »

  • Vote: I like it
  • +66
  • Vote: I do not like it

179.
By kartik8800, history, 6 years ago, In English
Introduction to DP with Bitmasking Hello Codeforces! This series of videos are focused on explaining dynamic programming by illustrating the application of DP with bitmasking through the use of selected problems from platforms like Codeforces, Codechef, SPOJ, CSES and Atcoder. After going through this series, you should find yourself confident in solving problems which require the use of dp and bitmasks and also implementing them in a reasonable amount of time. I will also live code and submit the solutions to the problem on the coding platform from where the problem comes. Some Basic elements of Dynamic Programming ------------------ Some general ideas and my thoughts about DP to help you get started:<br> Part 1: [https://youtu.be/24hk2qW_BCU](https://youtu.be/24hk2qW_BCU)<br> 1. What is Divide and Conquer?<br> 2. What is Dynamic Programming?<br> 3. Types of DP problems.<br> Part 2: [https://youtu.be/yfgKw6BUZUk](https://youtu.be/yfgKw6BUZUk)<br> 1. What is a DP-state?<br> 2. Characterizing ...
bitmask dp. I will discuss the following: 1. What is the TSP? 2. Brute force solution

Full text and comments »

  • Vote: I like it
  • +148
  • Vote: I do not like it

180.
By greateric, history, 5 months ago, In English
Stresstesting script Don't worry, your regularly scheduled useless information programming will resume soon. Anyway, here is [`gtest`, my attempt at writing a script to help with stresstesting](https://github.com/greatericontop/gtest). Note that I still personally think stresstesting is slightly overrated. It is not a silver bullet, especially when some questions are unstresstestable, like some constructive problems, [problems where the solution space grows way faster than even exponentially if you're trying to brute](https://codeforces.me/contest/1747/problem/D), other cases where your brute forcer has to make some core observation that could potentially be wrong, or if your brute forcer is bugged too and misses the same edge case your fast solution does (Cirno and Number with digit 0 be like). I also think it takes a lot of time so you decide whether you want to write everything up or not. With that being said though, it should be very helpful for debugging WA2s, hopefully. The format is ~~~...
with python automatically; executables will be run by themselves) in. And code yourbrute force

Full text and comments »

  • Vote: I like it
  • +22
  • Vote: I do not like it

181.
By muratt, 11 years ago, In English
Codeforces Round #352 Editorial ###[problem:672A] This one is a simple brute force problem, we will construct our array. Adding numbers between $1$ and $370$ will be enough. After construction we just have to print $n$-th element of array. ###[problem:672B] We observe that in a good string all letters must be different, because all substrings in size 1 must be different. So if size of string is greater than $26$ then answer must be $-1$ since we only have 26 different letters. Otherwise, Let's suppose we have $k$ different letters in string sized $n$, in our string $k$ elements must be stay as before, all others must be changed. So will be ($n$ &mdash; $k$). Here is the [code](https://ideone.com/NJw7V2). ###[problem:671A] Let's solve the problem when Adil and Bera in the same coordinate with bin. Then answer will be $2\times\sum\limits_{i=1}^n distance(Bin, Bottle_i)$, let's say $T$ to this value. [cut] If Adil will take $i$-th bottle and Bera will take $j$-th bottle $(i\neqj)$, then answer ...
This one is a simple brute force problem, we will construct our array. Adding numbers between $1

Full text and comments »

  • Vote: I like it
  • +63
  • Vote: I do not like it

182.
By zenolus, history, 6 years ago, In English
UpSolve.me | Efficient Codeforces Practice ![ ](https://i.imgur.com/txXJIr0.png) Hello, Codeforces community! First of all, I would like to thank [user:MikeMirzayanov,2020-06-21] for such an awesome platform. It's been almost a year since I joined and ever since I was always in the dilemma which question to solve. It's a commonly accepted fact that one should solve the most solved questions first. Many other recommender websites out there follow the same pattern &mdash; solved count for the win. However, after some days of following it, it kinda felt repetitive. Yes, the ones that everyone can solve would be the easier ones. But how do we determine if it can teach us something new? Codeforces has the problem rating system which gives a more accurate view of which question is easy and which is not. But as with the case of solved counts, rating can't be considered as the sole differentiator. After having analyzed for some time, I found that there are three important factors that decide which problem is best suitable for ...
, you are more likely to see implementation, brute-force, or greedy problems. So, someone who is in

Full text and comments »

  • Vote: I like it
  • +349
  • Vote: I do not like it

183.
By Alex_2oo8, 13 years ago, translation, In English
Codeforces Round #206 — Editorial [problem:355A] If $d=0$, the there is the only number with $dr(x)=0 \Leftrightarrow x=0$, so, if $k=1$, the answer is $0$, otherwise &mdash; $No \, solution$. If $d>0$, then one of correct numbers is $d \times 10^{k-1}$. Time complexity: $O(1)$ + $O(k)$ for the output. [problem:355B] If we buy a ticket of the fourth type, we don't have to buy anything else, so, the answer is $min(c_4, answer \, using \, tickets \, of \, first \, three \, types)$. Now, when we don't have ticket of the fourth type, we can solve the task separately for buses and trolleys. Solving the problem only for buses: if we buy a ticket of the third type, we don't have to buy anything else, so, the answer is $min(c_3, answer \, using \, tickets \, of \, first \, two \, types)$. Without tickets of type three, we can solve the problem separately for each bus. If we buy a ticket of the second type, we will spend $c_2$ burles and if we buy $a_i$ tickets of the first type, we will spend $(a_i \t...
$m > k + 1 \Rightarrow Answer \ge k + 1$. In this case we will brute force answer from $k+1$ to $m

Full text and comments »

  • Vote: I like it
  • +24
  • Vote: I do not like it

184.
By Black_Fate, history, 4 years ago, In English
[Educational] Combinatorics Study Notes (2) 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 second blog, which is friendly to 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. ### Previous Blogs - [Combinatorics (1)](https://codeforces.me/blog/entry/110376) ### Blogs in the future If finished, I'll link them. - Combinatorics (3) - Bitmask - Probabilities ### Content 1. Quick power 2. Fermat's little th...
So multiply it with brute force is impossible, can you think of an $\mathcal O(\log b)$ solution?

Full text and comments »

  • Vote: I like it
  • +83
  • Vote: I do not like it

185.
By kartik8800, history, 6 years ago, In English
Problem Proposal with Editorial | Div2 B/C So I had proposed a problem few months back but didn't get the time to prepare an entire contest. Wanted to share the problem and it's editorial which I wrote while proposing. Came across something similar while reading and implementing a research paper. <spoiler summary="Problem statement"> There are **n** data items (d1, d2, .. , dn) and an integer **m** less than equal to **n**.<br> Next you are given a NxN matrix **SIM** such that **SIM[i][j]** = similarity between di and dj. For every data item di, Choose any **m**-sized subset **s** of the **n** items and evaluate sum of similarities between di and dj such that dj belongs to the chosen subset **s**, call this value the score for di given subset s or **d(i,s)**. Define Si = score of data item i = max d(i,S) over all possible m sized subsets S find x where x = max Si over all i (from 1 to n)<br> if there is more than 1 valid answer then minimize x. </spoiler> <spoiler summary="Constraints"> SIM[i][j] = SIM[...
Brute force : Overall complexity : n * binomial_coeff(n,m)

Full text and comments »

  • Vote: I like it
  • +12
  • Vote: I do not like it

186.
By box, history, 5 years ago, In English
box 2021 and solutions Hello! This is the editorial (and discussion post i guess) for [box 2021](https://codeforces.me/gym/103500), a collection of problems that I set and received positive feedback on and generally just problems that I wanted to share with the broader CP community. The previous installment of this series is [box 2020](https://codeforces.me/gym/103003). The contest is IOI-style with subtasks; the problems are roughly sorted by difficulty ~~but there is no difficulty gradient~~. # [problem:103500A] <spoiler summary="Hint"> Take the prefix sum of $a$, and then do "Gaussian elimination". </spoiler> <spoiler summary="Solution"> We do all calculations modulo $10^9+7$. Let the prefix sum of $a_1,a_2,\dots,a_n$ be $p_1,p_2,\dots,p_n$; that is, $p_i=\sum\limits_{j=1}^i a_i$. Then, for $i=2,3,\dots,n$, we can express the constraint given to us as $x_ip_i-y_ip_{i-1}=z_i-y_ip_n$, or $p_i=\frac{z_i-y_ip_n+y_ip_{i-1}}{x_i}$. On the other hand, if $i=1$, we instead have $x_1a_1+y_1p...
The next optimization would seem to be replacing the brute force for each universe with some magic

Full text and comments »

Tutorial of box 2021
  • Vote: I like it
  • +95
  • Vote: I do not like it

187.
By Kerpoo, history, 5 years ago, In English
Some Persian videos to learning algorithms Hi! I was teacher of some online courses for students preparing themselves for IOI. I recorded my course sessions in some video files and they can be useful for Iranian (or who knows Persian) high school and also university students. If anybody wants the videos contact me here or my Gmail with address [email protected] or telegram id @kerpoo . The first course was about **introduction to programming with C++** and the content of the course was: 1. Introduction to the general programming tools with c++ syntax (Variables, Arrays, Conditions, Loops, Functions & ...) 2. Recursive functions 3. Time and memory complexity 4. Sort algorithms and implementation of Merge-sort 5. Algorithms about Prime numbers and Eratosthenes sieve 6. Introduction to big numbers and their algorithms 7. Introduction to binary search trees (BST) 8. Working with files by fstream library 9. Introduction to important libraries and structures for competitive programming (Pair, V...
- **Brute force with bitmasks**

Full text and comments »

  • Vote: I like it
  • +28
  • Vote: I do not like it

188.
By aberter0x3f, history, 22 months ago, In English
Redefinition of "Time": a Revolutionary Evaluation System Based on WebAssembly Are you tired of the inconsistencies and unpredictability in competitive programming evaluations? Do you wish for a more stable, efficient, and fair judging system? Look no further! We are excited to unveil our innovative evaluation solution that leverages the power of WebAssembly (WASM) and the Word-RAM model to transform the way of competitive programming judgement. ## Why This Project Matters Traditional evaluation systems often suffer from instability, environmental discrepancies, and outdated performance metrics. Competitors frequently face the frustration of inconsistent results due to machine fluctuations, leading to unnecessary optimization efforts. Our project addresses these challenges head-on, ensuring a level playing field for all participants. ## Key Features of Our Solution - **Absolute Stability**: By simulating program execution, our system guarantees consistent results across different machines, eliminating the unpredictability that often plagues competitiv...
brute force solutions pass.

Full text and comments »

  • Vote: I like it
  • +94
  • Vote: I do not like it

189.
By low_, history, 8 years ago, In English
Panic relief pre-OI (and similar competition) ... There are only about 10 days left before I choke myself to death at Vietnamese OI this year.... At the moment, a part of me is really relaxed, because this year outcome won't affect my future a lot, but the other part of me is being stressful and annoying as hell, because throughout the year of 2018, I learned a lot, and obviously I cannot have the same (or even worse) than last year, right. That part of me keep pondering upon a question for the last 30 days: **"What the f--- should I do to prepare for this?"**[cut]. ![ ](https://cdn.theatlantic.com/assets/media/img/mt/2016/03/stressedout2/lead_720_405.jpg?mod=1533691810) _(Stressed out. Literally.)_ Now, I'm not a type of competitor that work my ass off every hour in every day, aiming for IOI and stuffs. Instead, I tend to spend my time on practicing less than my friends _(and more on some unrelated cause ==)_. That's one of the reason why my knowledge and skill are somewhat inadequate comparing to some other competitors in...
brute-force it to get those first sub-tasks. This is not ACM, and during the competition you should not

Full text and comments »

  • Vote: I like it
  • +60
  • Vote: I do not like it

190.
By DrunkMaster, 5 years ago, translation, In English
Editorial of the personal Olympiad for grades 6-9 Editorial of [contest:368205]. [problem:375720A] <spoiler summary="Editorial"> For tests up to 10 you can solve manually. For second group you can solve by brute force: check all possible $i$, $j$ and check condition. $O(n^2)$ For third group you can see, that for fixed $i$ $j = n - i$. $O(n)$ For full solution you can see, that for every number from $0$ to $n$ we can find pair. The answer is $n + 1$. $O(1)$. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/extc++.h> #define int int64_t using namespace std; int32_t main() { int n; scanf("%lld", &n); n++; printf("%lld", n); } ~~~~~ </spoiler> [problem:375720B] <spoiler summary="Editorial"> For the first group it was enough to note that the answer is always $k$. For the second group it was necessary to find the number of ones and twos and solve similarly to the first case. For the third group it was necessary to be able to find the minimum in the a...
For second group you can solve by brute force: check all possible $i$, $j$ and check condition. $O

Full text and comments »

  • Vote: I like it
  • +27
  • Vote: I do not like it

191.
By Spheniscine, history, 21 month(s) ago, In English
Unofficial Editorial — Dilhan's Computing Contest 1 [Partial, P1~4 + P5S1] Contest hosted on DMOJ [https://dmoj.ca/contest/dcc1](https://dmoj.ca/contest/dcc1) ### [P1 &mdash; The Cathedral of Learning](https://dmoj.ca/problem/dcc1p1) <spoiler> If $a > b$, the answer is `NO`, as Alice always goes up and Bob always goes down. Otherwise, $a \leq b$, and the answer is `YES` if and only if the parity (oddness or evenness) of $a$ and $b$ is equal (equivalently, that $b - a$ is even). This is because the difference between them reduces by $2$ each step, and if the difference is odd, they'll end up on neighboring floors and then pass and miss each other on the next step. Time complexity: $O(1)$ </spoiler> ### [P2 &mdash; Square Sum](https://dmoj.ca/problem/dcc1p2) <spoiler> Assume that $A \leq B$ (otherwise, swap them). Now let's count the valid pairs $(a, b)$ where $a + b = c^2$ for some non-negative integer $c$. Let's also define a useful function $\displaystyle P(n) = \sum_{i = 1}^{n} i^2 = \frac {n(n+1)(2n+1)} {6}$, representing the sum of th...
roots. [It can be done with either binary search, or by using floating points + smallbrute force to

Full text and comments »

  • Vote: I like it
  • +17
  • Vote: I do not like it