Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

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.

Types

Last visit:  3 years ago
Registered:  3 years ago
2.
By Proof_by_QED, history, 13 months ago, In English
Testing Round 20 [Communication Problems] Hello Codeforces. We are introducing a new type of problem which may appear in future Codeforces rounds, called Communication problems! In these problems, your program would be ran twice, with different input and output formats between the runs. All variables stored in the memory will be lost between runs. However, the information given to you on the first run may be important to you for completing the second run correctly. Therefore, one of the key challenges in these types of problems would be to find a way to use the limited amount of output you are given in the first run to communicate information to the second run. Below shows a flowchart. <center> <br/> <img src="https://i.ibb.co/JWMFpyfY/a-1.png" alt="2025-09-06-12-40-07" border="0" /> <br/> Flowchart for communication problems </center> In these problems, time and memory limits for both runs would be kept separately. For example, if a problem has a time limit of $2$ seconds, you will only get the Time Limit E...
will have fun with the new type of problem!, Hello Codeforces. We are introducing a new type of problem which may appear in future Codeforces, We are introducing a new type of problem which may appear in future Codeforces rounds, called

Full text and comments »

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

3.
By Bakry, 4 years ago, In English
Red Isn't Impossible _I waited for more than a year to write this blog._ I started CP in July 2017, I always dreamed about reaching red, and it finally happened. I didn't become red like talented contestants in 1-2 years, but it took me more than that. The start of my CP journey was average (you can see my graph); It took me more than six months to reach pupil, then another six months to get specialist, and it took me more time to achieve higher ranks. I didn't have any mentor or coach. So, I asked many stupid questions, which you can find if you read my old blogs. One of these questions is, "What's the importance of Dynamic Programming?" (I drafted this blog xD), But of course, I don't motivate people to ask these types of questions as they usually can be answered by just searching. I failed many times during my journey in CP, especially in important competitions (IOI21 and IOI22). I stopped CP many times because I was frustrated and believed I could never improve. For example, I stopped when I w...

Full text and comments »

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

4.
By NXIST_buster, history, 6 years ago, In English
Corruption, Cheating at ICPC Yinchuan This blog is about Corruption and Cheating at ICPC YinchuanRegional. ICPC Yinchuan Regional is one of the ICPC regional contests for students competing in the geographic area of Asia East Continent. I. Background: General Info ------------------ Ningxia Institute of Science of Technology, or NXIST is a higher education institute in China. Since 2019, NXIST has held two regional contests. The and both were considered by many participants as jokes, yet until today participants are unaware of the NXIST's extent of evil. Zhihu is a Chinese website similar to Quora, and I will refer to this website for information. II. Background: Before 2021 ------------------ Regional competitions in China consists of two stages: The online selection contest and the onsite regional contest. As there are many contestants in China, the online contest is considered serious and rules are usually strictly enforced, with entire universities where some participant cheats disqualified from attend...
not be a printed code leak because even with the printed code it is impossible totype "char by char, This could not be a printed code leak because even with the printed code it is impossible totype

Full text and comments »

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

5.
By -is-this-fft-, history, 5 years ago, In English
Self-deception: maybe why you're still grey after practicing every day I generally don't like to give much advice on "how to practice", but recently I have been thinking a lot about this and I realized that there is something that I believe affects a lot of people (though it is admittedly hard to tell) that barely gets talked about: self-deception. Self-deception is a devious thing. It can be very hard to detect, yet can be fatal to improvement. This blog is mainly directed to greys, greens and cyans that can't get out of these categories. Most examples are given with that in mind. That being said, I believe others have something to think about as well. This is my first blog on such "psychological issues" and I don't know if I'll ever make another one. It's certainly a difficult topic to write about because for most of the blog, the message is "your practice is not as good as you think it is" or even "you aren't as good as you think you are" which can of course be a hard thing to hear. Thus, I have to somehow be very gentle while getting the poin...
The second point is why it is fruitless to write blogs of the type "why am I not improving". No one

Full text and comments »

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

6.
By zscoder, history, 7 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 1) Hi everyone! Inspired by the recent [Codeforces Round 641](https://codeforces.me/contest/1349), I decided to write an introductory tutorial on generating functions here. I am by no means an expert in generating functions so I will write about what I currently know about them. [user:MiFaFaOvO,2020-05-15] has written a really interesting [blog](https://codeforces.me/blog/entry/76447) here on Codeforces about more advanced applications of generating functions, but I think there is no English tutorial on the basics of this topic yet (or at least on CP sites). Thus, I would like to share about this topic here. I plan to split this tutorial into two parts. The first part (this post) will be an introduction to generating functions for those who have never learned about them at all, and some standard examples and showcases of generating functions. The second part will be a collection of several applications of generating functions in CP-style problems. If you are already familiar with ge...
functions. Now, let me introduce a new type of generating functions called the **exponential, Hence, for a fixed cycle type $a = (a_1,a_2,...)$, $p(a) = [x_{1}^{a_{1}}x_{2}^{a_{2}}...]\exp\left, Let $c(a)$ denote the number of permutations of length $n = a_{1}+2a_{2}+...$ with cycletype $a, Let us return to our problem. Call a cycle type $a$ good if $a_{j}=0$ for all perfect squares $j, So far we have looked at ordinary generating functions. Now, let me introduce a newtype of, The sequence $a = (a_{1},a_{2},...)$ defined above is also called the **cycle type** of a

Full text and comments »

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

7.
By antontrygubO_o, 5 years ago, In English
Giving negative feedback to contests in comments //This is a short post motivated by the comment section of the last Div2 round (and of several rounds before) Every problemsetter tries to make his contest as good as possible, and is upset when something goes wrong. Most problemsetters don't set contests for money, the payments are not worth the time and efforts spent on coming up with problems, preparing them, and hosting the contest. The most rewarding thing in this process in not the money, it's to see contestants enjoying your problems. That's why feedback is so important. If the comment section is filled with comments praising the contest, setter will most likely want to come back with another contest, and if it's filled with hate and offenses, it's possible that setter will just give up on problemsetting and won't want to host another round. This means two things. First, if you liked the round, or some particular problem, why not to write a comment about it? I am sure that most setters would really appreciate it, a...
is another type of comments — just saying that some particular problem was bad/shitty

Full text and comments »

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

8.
By MikeMirzayanov, history, 3 years ago, In English
Filter for Past Contests Hello, Codeforces. It's scary to think about it: there are already almost 1800 rounds in the list of past contests! I started adding a filter to the table with these rounds. Right now, you can already filter by some of the types of rounds. Here's what I've supported: * Div. 1 * Div. 2 * Div. 3 * Div. 4 * Div. 1 + Div. 2 * Educational Rounds * CodeTON Rounds * Globals * Kotlin Rounds * VK Cup Rounds * Long Rounds * April Fools Of course, I might have forgotten some types of contests. Please remind me if I missed anything. We should pay attention only to types where we have conducted several contests of that type. I plan to expand this filter by adding more settings. Perhaps it would be good to filter by the condition "has at least one submission in this contest" (or those for which no submissions at all). What do you think? What else would you suggest adding? P.S. Here is how it looks on the website (some intermediate version, some options may be missing)...
have conducted several contests of that type. I plan to expand this filter by adding more settings, should pay attention only to types where we have conducted several contests of thattype.

Full text and comments »

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

9.
By KAN, 6 years ago, In English
How to set a Div. 1 or a Div. 2 round on Codeforces As you probably know, most of the rounds on Codeforces are created by active community members. We are very grateful to our talented authors from all around the world for bringing their ideas to tens of thousands of competitors, providing fun and learning experience for contestants of every expertise, from beginners to the world's top programmers. This post will cover the steps you need to take propose a round and become a problem writer on Codeforces. ## Who can be a problem author Best problems usually come from the most experienced participants. We have limited resources for rounds reviewing, so to make the process flawless for writers, starting January 1st, 2021, the following requirements for problem authors will be applied: - rating: 2100 or above, or - was a writer in the past. The restrictions may be updated in the future, the post will be updated accordingly. If your round is already in the review status, don't worry, it will be reviewed regardless of the current...
| Round Type | USDT*| |-----------|--| |Div 1 + Div 2| 1150 USDT | | Div 2 | 450 USDT |

Full text and comments »

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

10.
By HosseinYousefi, 12 years ago, In English
C++ Tricks I see lots of programmers write code like this one: ~~~~~ pair<int, int> p; vector<int> v; // ... p = make_pair(3, 4); v.push_back(4); v.push_back(5); ~~~~~ while you can just do this: ~~~~~ pair<int, int> p; vector<int> v; // ... p = {3, 4}; v = {4, 5}; ~~~~~ [cut] [This](http://codeforces.me/blog/entry/10124) is a great C++11 tutorial for those who want to know more about C++11. #### 1. Assign value by a pair of {} to a container I see lots of programmers write code like this one: ~~~~~ pair<int, int> p; // ... p = make_pair(3, 4); ~~~~~ while you can just do this: ~~~~~ pair<int, int> p; // ... p = {3, 4}; ~~~~~ even a more complex `pair` ~~~~~ pair<int, pair<char, long long> > p; // ... p = {3, {'a', 8ll}}; ~~~~~ What about `vector`, `deque`, `set` and other containers? ~~~~~ vector<int> v; v = {1, 2, 5, 2}; for (auto i: v) cout << i << ' '; cout << '\n'; // prints "1 2 5 2" deque<vector<pair<in...
function which gets 0 arguments and returns 0. I can even define a any-type sum function, First of all, you don't need to name the type you want to use. Second of all it goes forwards and, I can even define a any-type sum function:, You don't need to name the type you want to use, C++11 can infer it for you. If you need to loop

Full text and comments »

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

11.
By ATSTNG, history, 7 years ago, In English
[Tutorial] Matroid intersection in simple words **[This article is also available in [Russian](https://codeforces.me/blog/entry/69287?locale=ru)]** Hello, CodeForces. I think that matroids are beautiful and powerful concept, however, not really well known in competitive programming. I’ve discovered matroids at 2019 Petrozavodsk Winter Training Camp. There was a problem that clearly cannot be solved using usual techniques I knew, editorial for this problem was just these three words “just matroid intersection”. Back then it took me more than 2 days of upsolving to find all the information and details I need and implement solution that gets Accepted on this. And it took way longer to actually understand why does it work and exactly how does it work. (I still hesitate in some details.) Of course, it is not hard to google up all the definitions and some related articles, but in my opinion they all are focused more on mathematical part of theory, strict proofs in some not really obvious but short ways, and observing only ke...
$B$ to _any_ other valid basis of matroid $M$ regardless of its type. This property is called “strong, between two sets of edges in different parts. Orient one type of edges from left part to right, and, element of the same type, and rules will preserve. Now, we can also define rank of subset in, independent if it does not contain a cycle. This type of matroids is the greatest one to show some, . Changing the type of matroid will not help either, properties of linear combinations will preserve., This is Rado-Edmonds algorithm. As an example for specific matroid type we have Kruskal’s minimum, We can find optimized matroid-type-specific solutions:

Full text and comments »

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

12.
By Golovanov399, 7 years ago, In English
C++ tips and tricks Hello, codeforces. I would like to tell you about some tricks and constructions I use in C++. They are not hidden or anything, moreover, most of them are from stl or maybe well known among software engineers, but I often see codes where something is done by hand in, say, 5 lines, while in stl there is a function which does the same. The things below are filtered by my personal sense of non-popularity (so no `__builtin` functions) and usage frequency (so there almost surely are similar things I don't know about) and are not really sorted in any reasonable order. Let's begin. [cut] <hr> - ### `all(x)` This may be an exception to the rule of non-popularity -- this is quite widely used, but some next items will depend on `all(x)`, so I define it here. So, I talk about ```[c++] #define all(x) (x).begin(), (x).end() ``` Now sorting a vector looks like `sort(all(vec))` instead of `sort(vec.begin(), vec.end())`. However, it's not all about this define. Imagine you nee...
implementation the order of `nxt()` calls is not defined. Also you may change thetype to `long long, - ### lambda type deduction, Also you may change the type to `long long` or even make the function template, but I haven't, Indeed, in the very first version you could _actually_ explicitly specify the outputtype by a, The reason why it is called so and has an int type is that `std::multiset` and `std::multimap` also, and see that the compiler cannot deduce the type of your lambda: in one place you return `int` and, feeling that something you do in your life is not right (while you type this, you usually have time

Full text and comments »

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

13.
By maomao90, 3 years ago, In English
Editorial for Hello 2024 ### [problem:1919a] Author: [user:maomao90,2024-01-02] <spoiler summary="Hint 1"> When does the game end? </spoiler> <spoiler summary="Solution"> Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choices will still be valid. The only way that the game ends is when both players have $0$ coins. Since each operation decreases the total amount of coins by exactly $1$, the only way for Alice to win the game is if $a + b$ is odd. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if ((a + b) % 2 == 0) { cout << "Bob\n"; } else { cout << "Alice\n"; } } ...
$a$ or $b$, we can make use of one type 2 query to find the distance between one of the edges in $S_a, The original problem allowed $5n$ type 1 queries and $n$ type 2, We used $n - 2$ type 1 queries and $n - 1$ type 2 queries in total. This is because we used a

Full text and comments »

Tutorial of Hello 2024
  • Vote: I like it
  • +760
  • Vote: I do not like it

14.
By adamant, history, 18 months ago, In English
Complex FFT is not as bad as you think ... Probably. Hi everyone! As some of you _might_ already know, I don't like NTT. Primary reasons for this are: - I don't like modular arithmetic optimizations (Montgomery, etc). - I don't like NTT mods, and prefer good, old $10^9+7$. - I do like algebra of complex numbers. But, to my regret, the overwhelming mainstream in modern competitive programming is NTT. Primary reasons are: - It's allegedly faster. - It needs less memory. - It has no precision issues. - People don't like algebra of complex numbers. There is nothing I can do about the last, but today I'll address the first 3. Optimizing complex FFT was on my mind for quite some time, but I didn't really work on it _that much_ until the [blog](https://codeforces.me/blog/entry/142063) by [user:Qwerty1232,2025-04-24] on optimizing NTT has dropped, which motivated me to actually put some serious effort into this. In this blog, we will primarily focus on optimizations that are specific to complex arithmetic...
generally true, assuming $x$ and $y$ are represented exactly in the `double` type:, interpreted not as a singular data type, but rather as a pack (or "vector") of smaller, 32- or 64-bit, of type `T`, using huge pages if necessary. Note that for small allocations it's best to use small, - `__builtin_convertvector(a, type)` converts vector value $a$ of certain type into another vector, Note that direct cast from one vector type to another is essentially equivalent to, On top of it, actual SIMD type that are used in intrinsics are typically defined in compiler, The decision that I ultimately converged to is to re-define my own [complex numberstype](https, The first practical limitation we encounter is, if we use `double` type for our computations, it, and used `cp_algo::complex` as the main type for Fourier transform. Over extended

Full text and comments »

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

15.
By andreyv, 12 years ago, translation, In English
Catching silly mistakes with GCC As you know, the C++ language assumes that the programmer is always correct. Therefore C++ compilers don't add additional checks to the program, such as checks for null pointer dereference or out-of-bounds array access. This is good, because C++ programs run as fast as possible, and this is bad, because sometimes we may spend a long time debugging some silly mistake. We would want that the compiler can find such mistakes automatically. And many compilers can! In this post I will show various GCC options that do this. Previously [user:zakharvoit,2015-01-02] already wrote about this [here](/blog/entry/13875). All options that will follow should be added to the GCC command line. In various IDEs you can do it in IDE or compiler settings. Many of the options can also be used with Clang (for example, in Xcode). For MSVC++, I think, there is nothing better than Debug mode and `/W4`. [cut]   GCC warnings ------------------ Of course, the first step to debugging is to enable compi...
- `-Wformat=2` — warns if an argument type in `printf()`/`scanf()` does not correspond to the, prints x.cpp:12:14: runtime error: load of null pointer of type 'int' , выдаёт x.cpp:12:14: runtime error: load of null pointer of type 'int'

Full text and comments »

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

16.
By mohammedehab2002, 6 years ago, In English
Codeforces Round #649 (Div.2) Hi everyone! Codeforces round #649 will take place on [contest_time:1364]. It's rated for the second division, but, as usual, first division participants can take part out of competition. The problems were created by me. I'd like to thank my forever orzable coordinator [user:antontrygubO_o,2020-06-11]; my incredible army of testers [user:dorijanlendvaj,2020-06-11], [user:300iq,2020-06-11], [user:Osama_Alkhodairy,2020-06-11], [user:AmShZ,2020-06-11], [user:Taran_1407,2020-06-11], [user:TigranMec,2020-06-11], [user:_Aaryan_,2020-06-11], [user:Mohammad_Yasser,2020-06-11], [user:zoooma13,2020-06-11], [user:lavish315,2020-06-11], [user:Utkarsh.25dec,2020-06-11], [user:NOOBxCODER,2020-06-11], and [user:Laggy,2020-06-11]; and, of course, you-know-who for the amazing codeforces and polygon platforms. This time, in an effort to kill type-races and because I'm lazy, you'll be given 5 problems and 2 hours to solve them. **UPD:** the scoring distribution will be 750-1000-1500-2000-2500...
platforms. This time, in an effort to kill type-races and because I'm lazy, you'll be given 5, This time, in an effort to kill type-races and because I'm lazy, you'll be given 5 problems and 2

Full text and comments »

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

17.
By SlavicG, 5 years ago, In English
How to use Codeforces [GUIDE] I see a lot of newcomers struggling to use the website to it's fullest, so I decided to write a blog that has all important information about how to use Codeforces in a single place. I will update it with time, so feel free to write your suggestions/questions in case I missed something and I will be glad to add it to the post! I would like to thank [user:_Vanilla_,2022-02-05] and [user:mesanu,2022-02-05] for helping me write the blog, and [user:Monogon,2022-02-05], [user:down,2022-02-05] and [user:AlperenT,2022-02-05] for proofreading and giving suggestions. #### Navigating through pages ![ ](https://media.discordapp.net/attachments/705371983650619454/928235498487570442/bandicam_2022-01-05_12-36-00-134.jpg?width=991&height=110) It's possible to navigate through most pages of Codeforces using the bar on the top, I will talk about what each tab does more in depth below: #### The Help Page The help page contains the answer to a lot of questions about Codeforces, such as rati...
Div. 1 and Div. 2 rounds. The most popular type of these rounds are the "Global Rounds" which happen

Full text and comments »

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

18.
By MikeMirzayanov, 5 years ago, In English
I am Mike Mirzayanov. AMA! <img src="/predownloaded/3f/31/3f31c3ac1f7b4e53128fc9708f5736eea40d7b94.jpg" style="width:250px; margin:1em 0 0 0; float:right;"/> But why not! Many people here seem to know me. Or maybe not quite? I am ready to answer your questions. Ask me anything! I plan to spend no more than 3 hours on answers. Sorry if I can't answer all the questions. Let's more or less follow the rules from here https://www.reddit.com/r/IAmA/wiki/index Below is actually a quote from the rules. The interviewee begins the process by starting a post, describing who they are and what they do. Then commenters from across the internet leave questions and can vote on other questions according to which they would like to see answered. The interviewee can go through and reply to the questions they find interesting and easily see those questions the internet is dying to have the answer to. Because the internet is asking the questions, they're going to be a mix of serious and lighthearted, and you'll ...
it is deliberately creepy or offensive. * "I bet OP won't answer this"-type responses, which usually, . * "I bet OP won't answer this"-type responses, which usually come after the OP has finished

Full text and comments »

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

19.
By ScarletS, 5 years ago, In English
Codeforces Round #742 (Div. 2) Hey there Codeforces! [user:flamestorm,2021-09-01] and I are glad to invite you to our first-ever Codeforces round, [contest:1567], which will be held on [contest_time:1567]. **This round will be rated for participants with rating lower than 2100**. Special shoutouts to: - [user:adedalic,2021-09-01], for his fantastic coordination and translation of the round! - [user:MikeMirzayanov,2021-09-01], for creating the amazing Codeforces and Polygon platforms! - [user:dorijanlendvaj,2021-09-01], [user:awoo,2021-09-01], [user:YouKn0wWho,2021-09-01], [user:PurpleCrayon,2021-09-01], [user:shxgun,2021-09-01], [user:ijxjdjd,2021-09-01], [user:stefdasca,2021-09-01], [user:epicxtroll,2021-09-01], [user:Aaeria,2021-09-01], [user:Eyed,2021-09-01], [user:rkm62,2021-09-01], [user:Shinchan01,2021-09-02], [user:BRCode,2021-09-02], [user:namanbansal013,2021-09-05], [user:Urvuk3,2021-09-01], [user:1_2_oatmeal,2021-09-01], [user:richy6,2021-09-01], and [user:tdpencil,2021-09-01] for testing th...

Full text and comments »

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

20.
By Tony2_CF, history, 11 months ago, In English
The Time Complexity Lower Bound for Segment Tree Beats is log^2 Original Post: https://jiry-2.blog.uoj.ac/blog/1404 The following content is translated by Gemini 2.5 Pro. ## Part 1: Introduction to the Hacking Method ### How to Map the Hack Sequence to a Segment Tree First, we are given a Hack sequence of length $len$. After $O(1)$ range addition operations and $\Theta(\log len)$ global $\text{chkmax}$ operations, this sequence becomes a cyclic shift (rotation) of the original sequence. Since a cyclic shift does not affect our range addition and global $\text{chkmax}$ operations (we can simply shift the indices for the range addition accordingly), we can consider the sequence as unchanged. If we have such a sequence, let $len=n^{\frac{1}{3}}$, and place such a sequence at intervals of $n^{\frac{2}{3}}$. Each sequence corresponds exactly to a segment tree interval. A subtree of size $n^{\frac{2}{3}}$ contains exactly one such segment tree interval. For the Hack sequence, the range addition operations are performed one by one on eac...
First, we need to understand the line segments as an $f$-type node in a tree. Each $f_n$ creates an, Note that here $n_f,n_g$ is just a classification, representing a type of node. A tree can have, This is the structure of $3_f$. Each line segment represents the root of an $f$- type node. The $g

Full text and comments »

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

21.
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...
[Typecast!](https://www.programiz.com/cpp-programming/type-conversion), even if it doesn't exist. This type of error might get you some unexpected MLEs.

Full text and comments »

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

22.
By -is-this-fft-, history, 2 years ago, In English
Things you should know before you discuss cheating Cheating has been discussed a lot lately. I'm writing a blog post about it with actual data (mainly, I want to know if there is an actual increase). However, in the many discussions that have ensued both here and on Discord servers, I noticed several recurring misconceptions. I wrote a section to debunk them and it grew kind of long, long enough to be a post in itself. So while my scripts are running, we can treat this as a kind of teaser. ### Things you should know before you write a comment about cheating Vocabulary: - _To plagiarize_ [means](https://dictionary.cambridge.org/dictionary/english/plagiarize) to use someone else's work while passing it off as yours. It refers to the act itself, **not** to its detection or punishment. "jrandomcoder plagiarized all of his solutions in round 987" is a meaningful statement. "jrandomcoder cheated in round 987 but he still hasn't gotten plagiarized, I request [user:MikeMirzayanov,2024-08-16] to look into this" is not. - _Plague_ is a...
anything" type message.

Full text and comments »

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

23.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #5 (with images from now) Hello, codeforces! Because after Round #507 sad men in suits visited me in my flat, this time I won't write about any task from the future. Instead, this blog will be about my own trick. I said "my own," but probably some of you have already heard about it or even figured it out, but I've developed it by myself, so I consider it as my own. In particular, it's **GEOMETRY TIME!!!**. But please, don't escape already. I also don't like this topic so much, that's why I really like this trick. Let me tell you a story from one onsite Polish contest, which took place a few months ago. I was thinking about one of the problems, and I've figured out that I had to do some binary-search (on doubles) and then check if a set of half-planes has a non-empty intersection. The answer would tell me in which direction should I turn in the binary search. Firstly, I grabbed my head, because I've never written an intersection of half-planes. I had my acm library with [user:Errichto,2018-09-07]'s code...

Full text and comments »

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

24.
By thanhchauns2, 4 years ago, In English
Codeforces Round #812 (Div.2) Hi Codeforces! ================== [user:_dlbm17,2022-06-25], [user:Demen100ns,2022-06-25], [user:Spyofgame,2022-06-25] and I are delighted to invite you to participate in [Codeforces Round #812 (Div. 2)](https://codeforces.me/contests/1713). - Start time: [contest_time:1713] - Duration: **120 minutes**. - Number of tasks: **6**, including at least **one interactive** problem. Make sure to read [this blog](https://codeforces.me/blog/entry/45307) and familiarize yourself with these types of problem before the round! <spoiler summary="This contest is brought to you by:"> - <a href = "https://www.facebook.com/HocvienPTIT">PTIT</a>, my university. - <a href = "https://discord.gg/vKjE9xan">Code Mely</a>, a Vietnamese fanpage for Computer Science. </spoiler> <img align="right" src="https://i.ibb.co/VLCYnxH/received-1102672770650793-1.png" width="60%" height="60%"> Special thanks to: - <span>[user:errorgorn,2022-08-02] for wonderful coordination</span><span style="col...

Full text and comments »

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

25.
By Zhtluo, history, 3 years ago, In English
The Reason You are Bad at Codeforces — You are Not Russian Enough If you are triggered by this clickbaity blog title, you are probably interested in improving your Codeforces skills. Now, I will share my point of view on the differences between Codeforces and ICPC contests, and how you can, in my humble opinion, maximize your Codeforces rating gain. I mostly consider that all conceivable competitive programming problems need three aspects of skill: 1. Observation &mdash; the ability to understand the problem and come up with non-trivial properties. 2. Technique &mdash; the ability to apply a well-known algorithm or data structure to the problem. 3. Implementation &mdash; the ability to code fast and debug fast. Collaterally, I refer to these three skills as Russian-ness, Chinese-ness and American-ness, respectively, for reasons you will soon see below. ## Observation (Russian-ness) Observation means that you stare at some problem for a sufficient amount of time and you are able to reduce it to some easier problem. One good proble...
I consider this aspect of difficulty to be *Russian* because this type of problem happens more

Full text and comments »

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

26.
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: ...
Although we considered the operations for a given type of present, problem for a single type of present with value $a$.

Full text and comments »

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

27.
By rewhile, 20 months ago, In English
<h1>Mike, please stop ignoring your userbase</h1> **This blog will compile a list of codeforces issues along with all the times Mike has ignored complaints about them** ## 1. Unreasonable delay for viewing submissions [<a class="rated-user user-green">+973</a>] - [Submission pages on Codeforces often not loading](https://codeforces.me/blog/entry/134655) [<a class="rated-user user-green">+281</a>] by [user:jeroenodb,2025-04-04] on *October 2024* - [Unreasonable delay for viewing submissions](https://codeforces.me/blog/entry/135457) [<a class="rated-user user-green" title="Green 392">+392</a>] by [user:djm03178,2025-04-04] on *October 2024* - [Please, give us proper explanations about this nonsense.](https://codeforces.me/blog/entry/136830) [<a class="rated-user user-green">+300</a>] by [user:djm03178,2025-04-04] on *December 2024* No [user:MikeMirzayanov,2025-04-04] reply ## 2. Cloudflare misconfiguration [<a class="rated-user user-green">+1232</a>] Posted [CF should rename itself to Cloudflare instead of Codef...
Despite almost graduating from university, when I type `c` in browser it autocompletes to

Full text and comments »

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

28.
By SecondThread, history, 6 years ago, In English
Petition to revoke unrated account permissions to post comments/blogs Unrated Account Disaster ================== Recently there have been an obscene number of unrated accounts showing up. Several of them have inappropriate names, so I won't give examples because I want to keep this post clean, but I'm sure you have seen them in the comments. They are likely all by the same individual, possibly with a few copy-cat troublemakers as well. Recently, certain ones have begun to spam useless comments on old posts to clog up the recent actions, effectively hiding all relevant conversations except on the blog posts they spam on. For whatever reason, these are overwhelmingly on [user:Errichto,2020-07-10]'s old blog posts. Occasionally there are also a flood of obscene blog posts made by the user themselves. Here's an example of what I mean: ![ ](https://wumbogames.github.io/cfPictures/Spam.png) #### This is obnoxious and I would like to see it stop. The current solution clearly doesn't work. As soon as they get banned or muted or whatever, they c...
fairly meaningless 'How do I get better', 'please solve this problem for me', et ceteratype of

Full text and comments »

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

29.
By satyam343, 3 years ago, In English
think-cell Round 1 Hello, Codeforces! Welcome to the [contest:1930] supported by think-cell, which will start on [contest_time:1930]. It will be a combined rated round for both divisions. All problems were authored and prepared by [user:Elegia,2024-02-13] and [user:satyam343,2024-02-07]. We would like to thank: - [user:errorgorn,2024-02-13] for round coordination and help with preparation - [user:KAN,2024-02-17] for helping with the preparation of problems - [user:Alexdat2000,2024-02-13] for Russian translation - [user:GoatTamer,2024-02-17] and [user:Non-origination,2024-02-17] for discussing problems with us while our proposal was in review and testing the round. - [user:Kaitokid,2024-02-13], [user:antekb,2024-02-13], [user:vgtcross,2024-02-13], [user:riano_,2024-02-13], [user:mtw,2024-02-13], [user:AboAbdoMC,2024-02-13], [user:Vladithur,2024-02-13], [user:BERNARD,2024-02-13], [user:milind0110,2024-02-13], [user:conqueror_of_tourist,2024-02-13], [user:Um_nik,2024-02-13], [user:gamegame...

Full text and comments »

Announcement of think-cell Round 1
  • Vote: I like it
  • +798
  • Vote: I do not like it

30.
By MikeMirzayanov, 10 years ago, translation, In English
For contest writers: proposal tracking system <i>In 2021, some details (including requirements for problem writers) were changed. Read <a href="https://codeforces.me/blog/entry/85259">the link</a> for details.</i> Hello, Codeforces! New year brings changes to the Codeforces team. <a href="/blog/entry/49466">As you probably know</a> [user:GlebsHP,2017-01-04] completed his work as the chief coordinator of Codeforces. Gleb, thanks a lot! You did an excellent job and coordinated a lot of interesting rounds. You're a professional, an interesting person, you have impeccable taste to problems, and you proved to be brilliant and talented writer. Thank you that you were with us! Hope to see your tasks on Codeforces many times again! Nikolay [user:KAN,2017-01-04] Kalinin came to Gleb's place. He is also an experienced participant, Nikolay has already held several rounds as a coordinator. [user:KAN,2017-01-04] seriously engaged in programming contests since he was 12 years old. His major achievements: he won twice All-Russian Scho...
| Round Type | $ | ----------- | - | --- | | Div 1 + Div 2 | $250 + $50* | Div 2 | $100 + $50*

Full text and comments »

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

31.
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...

Full text and comments »

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

32.
By geranazavr555, 7 years ago, translation, In English
Polygon updates (June-October 2019) Hello, Codeforces! I and [user: cannor147,2019-11-07], as students of ITMO University, joined the Codeforces team in June. From June to October, we mainly dealt with the development of the Polygon platform. In this post, we would like to present to you a list of what we have done during this time. This list does not include minor bug fixes or any improvements that are invisible to users. #### PIN codes for problems and contests Sometimes very important contests and problems are being developed in Polygon. In such cases, a leader of the jury may be worried about data leaking. For example, it can be so because of the weak password of another member of the jury. PIN code is an additional factor of confirmation the access for the problem or contest and it can be set up only by the owner. It is assumed that the PIN code will be sent in another secure way. There is a link Create Pin for the owners in the contest interface: ![Create Pin in the interface](https://i.ibb.co/bgcg8C...
If a contest or a problem has the PIN code, you need to type it before continuing., When changing an issue status, type or assigned user, an auto-comment is now generated (for example

Full text and comments »

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

33.
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-...
In the future, I don't see this type of "generate $10^9$ solutions and find the right one" AI being

Full text and comments »

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

34.
By MikeMirzayanov, history, 2 years ago, In English
Testing Round 19 [unrated registration testing] Hello! We are starting to test the long-awaited feature of non-rated registration for rounds. Here’s the plan: we will first test this feature in [contest:2010]. Then, we will apply this innovation for ICPC-like rounds (Div. 4 Rounds, Div. 3 Rounds, Educational Rounds). After we have tested the feature in ICPC-like rounds, we will start using it in other types of rounds as well. Here’s how the feature works: * When you register for a round (if it is rated for you), you can choose non-rated registration if you do not expect to perform at your best (for example, if you might be interrupted during the round). * You can change your registration type (rated or non-rated) BEFORE THE ROUND STARTS. Once the round starts, you cannot change your registration type. * If you register for a round after it has started, you will automatically be registered as rated (if the round is rated for you). In other words, you will not be given the option to register as non-rated. * After the roun...
choose your registration type so that we have both rated and non-rated registrations., interrupted during the round). * You can change your registration type (rated or non-rated) BEFORE THE, ). * You can change your registration type (rated or non-rated) BEFORE THE ROUND STARTS. Once the

Full text and comments »

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

35.
By neal, 6 years ago, In English
Unofficial Editorial for Educational Round 94 (Div. 2) Haven't done one of these for a while! Here are my approaches to the problems: #### [problem:1400A] We just need to make sure our string of $n$ characters matches each of the $n$ substrings in at least one spot. The easiest way to do this is to take every other character from $s$. Code: [submission:90908018] Another fun solution: we can generate random strings and check them until we find one that matches everything. This works because the probability of failing to match any particular substring is $\frac{1}{2^n}$, so as $n$ gets bigger the probability of failing gets extremely low. Code: [submission:90999219] #### [problem:1400B] First iterate on the number of swords we will personally take. Then we should greedily take as many war axes as we can until we run out of money. At this point, our follower needs to take as many items as possible. They can do this by greedily taking whichever of swords or war axes are cheaper until they run out, followed by taking the more expensi...
affecting the result. So let's do all of the first-type operations before the second-type operations. Then, consider two options: either take all $n$ second-type operations, or use $a_m$ first-type operations, operations in any way we want without affecting the result. So let's do all of the first-type

Full text and comments »

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

36.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Data structures Today I want to introduce you some very very useful data structures. In this lecture, we are trying to improve your data structures skills, stay with us and click on **read more**. [cut] Important data structures : Trees ----- Trees are one of the most useful data structures.A tree is a connected-acyclic graph.There are too many types of trees, like : rooted trees, weighted trees, directed trees, tries, etc. Partial sum ----------- There are two types of problems solvable by partial sum. 1.Problems which you are asked to answer some queries about the sum of a part of elements (without modify queries). Solution of all of this problems are the same. You just need to know how to solve one of them. Example : You are asked some queries on an array $a_1,a_2,...a,_n$. Each query give you numbers $l$ and $r$ and you should print $a_l + a_{l+1} + ... + a_r$ . Solution : You need to build another array $s_1, s_2, ..., s_n$ which $s_i = a_1 + a_2 + ... + a_i$ ...

Full text and comments »

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

37.
By SecondThread, history, 7 years ago, In English
Why problem writers should stop saying “It is guaranteed that” Please Stop Guaranteeing Things ================== There are two common meanings for something being “guaranteed”, and often it is up to the reader to guess the author’s intended meaning. This is annoying and creates unnecessary barriers to entry. **Meaning #1:** The thing we are guaranteeing is provably true for the given input. The thing we are guaranteeing is simply true. We don’t want to provide a proof since it would be long, unnecessary, and annoying to read, and might spoil the solution, but you have our word that an answer always exists. Example: We give you two positive integers A and B (1 <= A, B <= 100). Find some positive integer C (1 <= C <= 200) such that C < A + B. **It is guaranteed that some C exists.** **Meaning #2:** The only input that is legal is input for which this is true. The thing we are guaranteeing might not always be true without this guarantee. Thankfully, we are providing this guarantee so that you only need to concern yourself with solving t...
because it is clear what they mean. The important part is that **this is a completely differenttype, [Codeforces round 633 Div1B (it's clear what the author meant, but still this type of usage)](https

Full text and comments »

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

38.
By tourist, 4 years ago, In English
Codeforces Round #844 Editorial [problem:1782A] <spoiler summary="Explanation"> [tutorial:1782A] </spoiler> <spoiler summary="Source"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int w, d, h; cin >> w >> d >> h; int a, b; cin >> a >> b; int f, g; cin >> f >> g; int ans = b + abs(a - f) + g; ans = min(ans, a + abs(b - g) + f); ans = min(ans, (d - b) + abs(a - f) + (d - g)); ans = min(ans, (w - a) + abs(b - g) + (w - f)); cout << ans + h << '\n'; } return 0; } ~~~~~ </spoiler> [problem:1782B] <spoiler summary="Explanation"> [tutorial:1782B] </spoiler> <spoiler summary="Source 1"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int n; cin >> n; vector<int> cnt(n + 1); for (int i = 0; i < n; i++) { int a; cin >> a; cnt[a] += 1; } int ans = 0; ...
Modular { public: using Type = typename decay::type; constexpr Modular, common_type::Type, long long>::type x; stream >> x; number.value = Modular, )>::type, md>>;, const Type& operator()() const { return value; } template explicit operator U, private: Type value; };, template class Modular { public: using Type = typename decay, template static Type normalize(const U& x) { Type v; if (-mod() <= x && x, template typename enable_if::Type, int>::value

Full text and comments »

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

39.
By Xellos, history, 11 years ago, In English
Codeforces Round #333 — editorial ### Hints: [div2A](#div2A): Try conversions between bases. [div2B](#div2B): Solve a simpler version of the problem where $A_{i+1} \neq A_i$ for all $i$. [div1A](#div1A): What are the shortest paths of the vehicles? what's the shorter of those paths? [div1B](#div1B): Forget about the ceiling function. Draw points $(i,A[i])$ and lines between them &mdash; what's the Lipschitz constant geometrically? [div1C](#div1C): Some dynamic programming. Definitely not for the exp. score of one person &mdash; look at fixed scores instead. [div1D](#div1D): Compute $dif(v)$ in $O(N)$ (without hashing) and then solve the problem in $O(N^2)$. You need some smart merges. [div1E](#div1E): Can you solve the problem without events of type 1 or 2? Also, how about solving it offline &mdash; as queries on subsets. ![ ](https://i.imgur.com/bnWmD60.png) ### <a name="div2A"></a>Div. 2 A: Two Bases ------------------------------------ It's easy to compare two numbers if the same bas...
over time. We'll solve it offline — each query (event of type 3) is asked about a subset of, Note that we can add exhibits this way. Thus, if there were no queries of type 2, we would be able, [div1E](#div1E): Can you solve the problem without events of type 1 or 2? Also, how about solving

Full text and comments »

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

40.
By MikeMirzayanov, 3 years ago, In English
Polygon: Warnings for Packages — Incomplete Tests + Statement/Validator Mismatches Hello, Codeforces! If you're developing problems in Polygon, you might like this image to attract attention. <center> <img src="/predownloaded/b4/b6/b4b6e46dd5811c89440ee98bce405e54e3b905c6.png"/> </center> <i>For the new members of the community, I would like to remind you that Polygon (https://polygon.codeforces.com/) is a system developed and maintained by Codeforces for preparing programming problems. It is there that authors and coordinators develop all the problems for the rounds. Moreover, I believe a significant (large?) portion of the problems for other competitions is also developed there: various stages of ICPC, national competitions of different levels, educational problems for various courses, etc. <b>In 2023, more than 50000 problems were prepared in Polygon (only those for which a package was compiled are counted)!</b></i> We often implement such improvements in Polygon that make the process of preparing a problem more reliable. These often include var...
absolutely irrelevant. In any other case, just add a test of the required type , and this will make

Full text and comments »

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

41.
By TheScrasse, history, 3 years ago, In English
Editorial of Pinely Round 3 (Div. 1 + Div. 2) The official implementations of all the problems are [here](https://drive.google.com/file/d/1q2PHS9nJt84FRwfMoiMslQULFE4dTMU4/view?usp=sharing). <spoiler summary="Timeline of the round proposal (may contain spoilers)"> (problems D', H', etc. were not used) - Feb 19, 2022: I proposed problem D' to [contest:1654], but it was not used. - Mar 13, 2023: I invented problem A. - May 16: I invented problem H'. - May 19: I realized problem G can be solved in $O(n)$ time and we used it in the Italian team selection test for IOI. - Jul 04: I opened a Div. 1 proposal containing A, D', G, H' and other problems which are not going to be used. - Aug 09: I invented problem I, with intended solution in $O(n^3)$. - Sep 27: I invented problem C. - Oct 14: [user:errorgorn,2023-12-23] replied to my contest proposal. - Nov 02: I invented problem D''. [user:errorgorn,2023-12-23] solved problem I in $O(n^2 \log n)$. - Nov 08: I invented problems E and F. I didn't propose problem F because I th...
- An element of type $\texttt{A}$ will always remain of type $\texttt{A}$. Proof: the only elements, - the values of type $\texttt{A}$ are increasing; - there are no two consecutive elements oftype, : the type of each element, the positions of the elements of type $\texttt{B}$, and the number of

Full text and comments »

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

42.
By Monogon, 4 years ago, In English
[Tutorial] Supporting Priority-Queue-like Undoing on DS _Good morning!_ In this blog, I will present an online algorithm that can perform priority-queue-like undoing on a data structure, given a few assumptions. I will also present and solve a generalization of that problem. For context, I highly recommend reading this blog that shows how to solve the easier problem of queue-like undoing. That blog gave me the inspiration for the trick I will describe here, but I will still try to write this blog so that it can be understood without it. Thank you [user:Noam527,2023-01-08] for introducing such a great trick to the competitive programming community. [[Tutorial] Supporting Queue-like Undoing on DS](https://codeforces.me/blog/entry/83467) Acknowledgment ----------------- Huge thanks go to [user:peltorator,2023-02-20] for hosting a [blog contest](https://codeforces.me/blog/entry/110840). His generous prize of $300 got many people to write blogs on new, interesting ideas, and it was one of the main reasons I wrote this blog. I'm...

Full text and comments »

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

43.
By -is-this-fft-, history, 4 years ago, In English
[Tutorial] FFT If I was a YouTuber, this would be the place where I fill the entire screen with screenshots of people asking me to make this. Anyway, not so long ago I gave a lecture on FFT and now [user:peltorator,2023-01-11] is giving away [free money](https://codeforces.me/blog/entry/110840), so let's bring this meme to completion. In this blog, I am going to cover the basic theory and (competitive programming related) applications of FFT. There is a long list of generalizations and weird applications and implementation details that make it faster. Maybe at some point I'll write about them. For now, let's stick to the basics. **The problem.** Given two arrays $a$ and $b$, both of length $n$. You want to quickly and efficiently calculate another array $c$ (of length $2n - 1$), defined by the following formula. $$c_k = \displaystyle \sum_{i + j = k} a_i \cdot b_j.$$ Solve it in $O(n \log n)$. First of all, why should you care? Because this kind of expression comes up in combinatorics a...
mentioned right at the beginning that this type of expression is common in formulas for counting, this type. , ]$, calculate $c[k] = \sum_{i - j = k} a[i] \cdot b[j]$. A sum of this type is sometimes called _cross

Full text and comments »

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

44.
By Lyde, 4 years ago, In English
Sometimes it's not their fault. Hello! It's 2023 now, and everyone is happy and hoping for a good year, which many good contests to come. So I want to say about one thing that I saw in most of the contests from last year, which I was pretty much annoyed about it and decided to speak about so that this year we will hope to have a better experience doing contests here. I have been in this community for more than 3 years now, not very long, but definitely enough to say that although the number of participants did increase, the number of users increase dramatically, but the number of people that respond to the contests positively don't. It actually did decrease though. I still remember that 500+ upvotes for a contest announcement are a normal thing back then, but I rarely see them now. And a common thing right now, every single contest that is over will have some comments criticizing it, but not in a good way at all. So I will make this quick for certain types of comments like that. I don't know if you do but I ...
or not really your type, or it's just too unbalanced or something. Seems understandable.

Full text and comments »

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

45.
By fcspartakm, history, 8 years ago, translation, In English
Polygon Improvements (May — June 2018) Hello, Codeforces. Below you can see the improvements in the system Polygon. A lot of work has been done to simplify the preparation of school tasks, which use groups and points for tests. In the General Information tab, you can enable the points option for each test. This option is enabled points for the whole problem, that is, for tests from all testsets. Let me remind you that test groups can be enabled for each testset separately on the Tests tab. #### Points for groups, points policies, dependencies Points for the test, as well as groups, can be entered in the table with the list of tests, and also specify them when creating a new test. If the group for the test appears for the first time, it will be automatically added to the list of available groups. This list is presented in the table. ![ ](https://pp.userapi.com/c846322/v846322429/70f6b/XokdENM1X6o.jpg) [cut] <br/> Here the problem developer can specify a policy for calculating points for the group, and also ...
first type of the points policy is `EACH_TEST`, in which case points will be added for each passed

Full text and comments »

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

46.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] The command line: how to read input from file without #ifdef and much more #### Introduction Instead of algorithms and math, I'll be doing something completely different here. There is something that has bothered me for a long time: people not understanding the tools they use to participate in contests and thus failing to take real advantage of them. And it all goes back to not understanding the command line. Some of you might say, "well surely, the command line is something obsolete and you're only clinging to it because you [insert ridiculous amateur-psychology here]?" No! The command line is not obsolete, and unless competitive programming becomes so mainstream that software vendors start writing professional-grade tools aimed specifically at us, it won't be. [cut] $~$ What is the command line? Any of these: ![ ](/predownloaded/bd/b6/bdb6c157b9b3ce5ae046c9064e469e0081f8c0fe.png) As you can see, it comes in many background colors and fonts, but the basic idea is always the same. It's a box you can type commands in, which it will ...
important part of the command line that we have to talk about: _scripting_. You don't have totype, same. It's a box you can type commands in, which it will then execute., that, you can type `g++` like the rest of us. In Linux and Mac, GCC is already installed (on Mac, it's, things are separate steps, and you have to run them separately. First, the compilation.Type, Now, you can type in the two numbers, press enter, and it will print their sum., Once you have got it open, type `ls` (Linux/Mac) or `dir` (Windows) and press Enter. You should, Testing interactive problems is hard. One way is to manually type inputs, which can be fine

Full text and comments »

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

47.
By Monogon, history, 6 years ago, In English
[Tutorial] Voronoi Diagram and Delaunay Triangulation in O(n log n) with Fortune's Algorithm What's a Voronoi Diagram? ------------------ Given a set $S$ of $n$ points in the 2D plane, the Voronoi diagram is a partition of the plane into regions. The region associated with a point $p\in S$ contains precisely the points $q$ such that $q$ is closer to $p$ than any other point in $S$. In other words, a point $q$ belongs to the region of its nearest neighbor. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Euclidean_Voronoi_diagram.svg/1024px-Euclidean_Voronoi_diagram.svg.png" width="300px" height="auto"/> The Voronoi diagram can be represented by the planar graph of boundaries between regions. A vertex in this graph is where three or more segments meet (or a point at infinity), and an edge is a segment connecting two of these vertices. The way the regions were defined, we see that a segment contains the points equidistant to two points in $S$, so it is part of their perpendicular bisector. Similarly, a Voronoi vertex is equidistant to three or more v...

Full text and comments »

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

48.
By Um_nik, history, 13 months ago, In English
One-letter variables Complete shitpost, don't take it seriously. We were discussing `#define int long long` and I suggested defining it to one letter if you want to save on typing so desperately. [user:jeroenodb,2025-10-11] said that those are reserved for variables, which prompted me to think, "Is there a letter I don't standardly use for some particular purpose?" Then I compiled the following list, and then I thought, "Well, I already wrote it, let's put it on cf", so here we are. ~~~~~ a - array, but also all sorts of stuff b - second array c - third array / count d - delta / divisor e - event / edge f - flag g - graph / second flag h - third iterator / third flag / height i - iterator j - second iterator k - third input size / some parameter (i know, those are all parameters, but for some reason k is parameter) l - left m - number of edges / second input size n - input size o - ??? p - permutation / position q - number of queries / query / second permutation / second position r - r...

Full text and comments »

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

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

Full text and comments »

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

50.
By zscoder, history, 7 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 2) Welcome to Part 2 of my tutorial on generating functions. The [first part](https://codeforces.me/blog/entry/77468) focused on introducing generating functions to those without any background in generating functions. In this post, I will demonstrate a few applications of generating functions in CP problems. Let us start with some relatively straightforward examples. Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually $998244353$). Also, $[n]$ denotes the set $\\{1,2,...,n\\}$. ### Blatant Applications in Counting Problems **Problem.** [AGC 005 Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices. For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T$ which contains all vertices in $S$. For all $1 \le k \le n$, find the sum of $f(S)$ over all subsets $S$ with $|S| = k$. Constraints: $n \le 2 \cdot 10^{5}$. <spoiler summary="Solution"> First, ...
Convolutions of this type appear in countless FFT problems and usually the hard part is to reduce

Full text and comments »

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

51.
By -is-this-fft-, history, 4 years ago, In English
PSA: don't use these functions unless you really, really need to When solving problems in competitive programming, it is almost never a good idea to use the following inbuilt C++ functions. You **will** be hacked or fail a pretest or worse, a systest. Why? Because they use floating-point numbers. They are designed to be used with a floating-point input and a floating-point output. The issue is that on a floating-point number, the result may not be exact. Worse, floating-point numbers may not be able to accurately encode the integer. ##### To calculate $\lfloor \frac{a}{b} \rfloor$ for positive integers $a$ and $b$: * **Don't** use `floor((double) a / (double) b)` or similar. * **Do** use `a / b`. It will round down. * **Warning:** be careful with negative numbers. The answer depends on whether we should round down or towards 0. ##### To calculate $\lceil \frac{a}{b} \rceil$ for positive integers $a$ and $b$: * **Don't** use `ceil((double) a / (double) b)` or similar. * **Do** use `(a + b - 1) / b`. * **Warning:** the same caveat ...

Full text and comments »

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

52.
By -is-this-fft-, 5 years ago, In English
[Tutorial] Proving the inverse Ackermann complexity of Union-Find #### Introduction Most of us are familiar with the union-find data structure and the two optimizations one can do on it: _union by rank_ and _path compression_. Most tutorials will introduce these methods and state that if both optimizations are used, the complexity will be $\mathcal{O}((n + m) \alpha(n))$. Here, $n$ and $m$ are the number of vertices and queries respectively. What is $\alpha$? Generally, we are told that $\alpha$ is some mysterious function that grows very slowly: $\alpha(N) < 5$ where $N$ is the number of subsets of particles in the observable universe and whatnot. What it is is usually not clarified very much. And there is typically no proof (or intuition and other such justifications) as to why the complexity is like that: usually we're told that the complexity analysis is quite long and complicated. At the time of writing, both [cp-algorithms](https://cp-algorithms.com/data_structures/disjoint_set_union.html) and [Wikipedia](https://bit.ly/3EvnzrI) are like th...
following type: > > - "Union" (or "merge" or "unite"): given two vertices $u$ and $v$, add an edge, Let's do some simple examples of this type of reasoning before we move on to the big guns.

Full text and comments »

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

53.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Everything About Segment Trees In the last lecture of **Algorithm Gym** ([Data Structures](/blog/entry/15729)), I introduced you Segment trees. In this lecture, I want to tell you more about its usages and we will solve some serious problems together. [cut] Segment tree types : Classic Segment Tree -------------------- Classic, is the way I call it. This type of segment tree, is the most simple and common type. In this kind of segment trees, for each node, we should keep some simple elements, like integers or boolians or etc. This kind of problems don't have update queries on intervals. Example 1 (Online): Problem [problem:380C] : For each node (for example $x$), we keep three integers : 1.`t[x]` = Answer for it's interval. 2. `o[x]` = The number of $($s after deleting the brackets who belong to the correct bracket sequence in this interval whit length `t[x]`. 3. `c[x]` = The number of $)$s after deleting the brackets who belong to the correct bracket sequence in this interval whi...
And now we can easily compute the answer for queries of type $C$ :, Classic, is the way I call it. This type of segment tree, is the most simple and commontype. In, Example : Problem [problem:76A], you can read my source code ([submission:8613428]) with thistype, First of all, we will read all queries, store them and for each query of type $A$, we will insert, For each query of first of type, if $u$ is in subtree of $v$, its value increasing by $x + (h_u, Function for 2nd type query :, In the last lecture, I talked about this type of segment trees, now I just want to solve an, In this type of segment tree, for each node we have a Fenwick (we may also have some other, In this type of segment tree, for each node we have a `set` or `multiset` or `hash_map` ([here, In this type of segment tree, for each node we have a disjoint set (we may also have some other, In this type of segment tree, for each node we have a trie (we may also have some other variables, In this type of segment tree, for each node we have a vector (we may also have some other variables, In this type of segment tree, for each node we have another segment tree (we may also have some, Then for all queries of type $A$, for each node $x$ containing $p$ we will run :

Full text and comments »

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

54.
By okwedook, 6 years ago, translation, In English
Codeforces Round #703 (Div. 2) Editorial [problem:1486A] <spoiler summary="Hint1"> What's the lower bound for the amount of blocks for the answer to be $\texttt{YES}$? </spoiler> <spoiler summary="Hint2"> Check the predicate for every prefix. </spoiler> <spoiler summary="Solution"> Let's consider the smallest amount of blocks we need to make the first $i$ heights ascending. As heights are non-negative and ascending the heights should look like $0, 1, 2, 3, ..., i - 1$, so the minimum sum is $\frac{(i - 1) \cdot i}{2}$. It turns out that this is the only requirement. If it's not the case for every prefix the answer is $\texttt{NO}$ because we can't make some prefix ascending. Otherwise the answer is $\texttt{YES}$ because you can move the blocks right till there is at least $i$ blocks in the $i$-th stack and this would make the heights ascending. </spoiler> Solution using C++: [submission:107892022]<br> Solution using Python: [submission:107892053] [problem:1486B] <spoiler summary="Hint1"> Is proble...
Finding the number of intersections of second type is a bit easier. We just need to calculate the

Full text and comments »

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

55.
By -is-this-fft-, history, 6 years ago, In English
How to ask for help in PM There was a blog today with a similar title, and although it was (I think, not really sure as I didn't get a good look) some kind of satire/joke blog, I wanted to post some serious advice about things I (don't) like to see when people are PMing me. However I decided that this wouldn't be in the spirit of the blog and decided to make a separate blog. And now that blog is deleted anyway. While it's not a bad thing to write messages to more experienced users, most people who write me do things that make them very difficult to deal with. These are my opinions, but somewhy I feel that many reds will agree. Some things here feel silly to write because they are so obvious. But I'm only writing them because people regularly mess them up. [cut] $~$ ####Use punctuation and spelling. There are some [very simple rules](https://codeforces.me/blog/entry/82186#comment-689836) that make your messages infinitely more readable. I find it especially strange when many of these messagers call...
and asking for "general ways to approach problems of this type" (whatever that means). By sending the

Full text and comments »

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

56.
By -is-this-fft-, history, 7 years ago, In English
[Tutorial] The DFS tree and its applications: how I found out I really didn't understand bridges #### Introduction This is a tutorial/exploration of problems that can be solved using the "DFS tree" of a graph. For a way too long time, I didn't really understand how and why the classical algorithm for finding bridges works. It felt like many tutorials didn't really explain how it works, kind of just mentioned it in passing and quickly just moved on to implementation. The day someone explained what the DFS tree is, I finally understood it properly. Before, it took me ages to implement bridge-finding properly, and I always had to look up some detail. Now I can implement it at typing speed. But more importantly, I began to see how the same techniques can be used to solve graph problems that have more or less nothing to do with bridges. The thing is, when you have a black box, you can only ever use it as a black box. But if you have a box that you understand well, you can take it into pieces, repurpose the pieces for completely different things, all without getting lost...

Full text and comments »

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

57.
By -is-this-fft-, 6 years ago, In English
[Feature request] Some suggestions for blogs I wanted to suggest some improvements for the blog system. Some of these things have probably been said before. Some of these things should be pretty easy to implement, others are harder and might require a complete rework. I tried to put the easy things first. [cut] $~$ #### Let's do something about necroposting This is probably my biggest pet peeve about Codeforces blogs. Most of the time, Recent Actions is filled with very old blogs, some of which have been brought up for pretty much no reason at all. Currently, we have [useful C++ "library](https://codeforces.me/blog/entry/8387) from 2013 in Recent Actions, where the recent comment answers an old question which has already been answered better. Similarly, there is [How to add friends?](https://codeforces.me/blog/entry/2006) which was brought up to make some joke that has already been done. The thing is though, a lot of the time these blogs are not brought up by trolls or anything like that. They are brought up by hel...
of the type "my solution prints different output on Codeforces". Almost always, the solution to that

Full text and comments »

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

58.
By zscoder, history, 10 years ago, In English
[Tutorial] Non-trivial DP Tricks and Techniques Hi everyone! Today I want to share some DP tricks and techniques that I have seen from some problems. I think this will be helpful for those who just started doing DP. Sometimes the tutorials are very brief and assumes the reader already understand the technique so it will be hard for people who are new to the technique to understand it. Note : You should know how to do basic DP before reading the post DP + Bitmasks ------------------ This is actually a very well-known technique and most people should already know this. This trick is usually used when one of the variables have very small constraints that can allow exponential solutions. The classic example is applying it to solve the Travelling Salesman Problem in $O(n^{2} \cdot 2^{n})$ time. We let $dp[i][j]$ be the minimum time needed to visit the vertices in the set denoted by $i$ and ending at vertex $j$. Note that $i$ will iterate through all possible subsets of the vertices and thus the number of states is $O(2^{n} \cdo...
jump. This type of intuition might come in handy to optimize your dp and turn the naive dp into an

Full text and comments »

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

59.
By errorgorn, 2 years ago, In English
Solving Problems with Min Cut Max Flow Duality Thanks to [user:kingmessi,2024-12-19] for pointing out several typos in this blog. This blog is adapted from a previous blog I wrote in my [personal blog](https://errorgorn.github.io/2024/11/24/Flow-Matching.html). I thought it would be good to share the relevant parts here. If you want to read my personal blog, go ahead, but I will warn you that it is a shitpost blog. The problems discussed in this blog is: - [ARC085C](https://atcoder.jp/contests/arc085/tasks/arc085_c) - [ABC225G](https://atcoder.jp/contests/abc225/tasks/abc225_g) - [ABC259G](https://atcoder.jp/contests/abc259/tasks/abc259_g) - [ABC193F](https://atcoder.jp/contests/abc193/tasks/abc193_f) - [ARC142E](https://atcoder.jp/contests/arc142/tasks/arc142_e) You can attempt these problems to see if you can figure out how to wrangle them into min-cut formulation knowing that they are min-cut. I have been told by a lot of old people that in the heydays of Topcoder it was flow meta. Those old people will obviou...
parity of $i+j$ is $0$ and $1$ respectively, then all constraints of type $C_{i,j}$ are between $X, Then we simply set $X = \{r\}$ and $Y = \{c\}$ and all the constraints of type $C_{i,j}$ are, Unfortunately, we find sets $X$ and $Y$ such that all constraints of the last type are between $X

Full text and comments »

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

60.
By duality, 3 years ago, In English
Codeforces Round #884 (Div. 1 + Div. 2) Editorial Video editorials for [B](https://www.youtube.com/watch?v=5nzUni8dFLQ), [C](https://www.youtube.com/watch?v=8mz7gnAJ5QM), and [D](https://www.youtube.com/watch?v=ahnNAwpGwHc) are available on [user:ak2006,2023-07-11]'s channel. ### [problem:1844A] <spoiler summary="Hint 1"> There exists a small $n$ where the second player can win. </spoiler> <spoiler summary="Hint 2"> If $a \ge 2$, then $n = 1$ works. </spoiler> <spoiler summary="Solution"> [tutorial:1844A] </spoiler> <spoiler summary="Implementation"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t,a,b; scanf("%d",&t); while (t--) { scanf("%d %d",&a,&b); printf("%d\n",a+b); } return 0; } ~~~~~ </spoiler> ### [problem:1844B] <spoiler summary="Hint 1"> In order for $(l,r)$ to contribute to the primality, we must have $\operatorname{MEX}(a_l,\dots,a_r) \ge 2$, so there is some value $1$ between indices $l$ and $r$. </spoiler> <spoile...
In either approach, we can associate a type to each row and column

Full text and comments »

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

61.
By Dominater069, 2 years ago, In English
How to Solve Questions [Dominater Version] Recently, I got a request asking me to write down my thought process while solving questions. So, here is the promised blog. I would like to thank [user:Iceknight1093,2024-08-30], [user:qwexd,2024-08-30], [user:Sana,2024-08-30], [user:Everule,2024-08-30] and [user:NovusStellachan,2024-08-30] for proof reading and suggesting edits in the blog. Special thanks to [user:satyam343,2024-08-30] for discussing most of the blog with me. <h3> 1. Overview </h3> The blog contains my solutions to $7$ problems in a wide range of ratings, starting from $1200$ all the way upto $2700$. Each problem has a step-by-step solution and you can notice how there are no large jumps in logic, but everything comes naturally. I do not claim that this is always possible in each problem, however I solve majority of CF problems in such a manner. There are certainly other high rated people who will have completely different methods of solving. However, this is about what works for me. There are some meta ...
Let's call an interval $P$-type if it has exactly one $1, bruteforce the prefix of $P$ type intervals and calculate value according to that., prefix of $i$ intervals being $P$-type to $(i + 1)$ intervals being $P$-type., **Claim 2** : There exists a prefix of intervals which will be $P$-type and then the suffix of, Now, it is obvious that we should select an interval to be $P$-type only if $(c - b) \ge 0, Thus, we can easily see that a prefix of intervals will have $(c - b) \ge 0$ and will be $P$-type

Full text and comments »

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

62.
By awoo, history, 7 years ago, translation, In English
Educational Codeforces Round 85 [Rated for Div. 2] Hello Codeforces! On [contest_time:1334] [contest:1334] will start. Series of Educational Rounds continue being held as [Harbour.Space University](https://harbour.space/) initiative! You can read the details about the cooperation between [Harbour.Space University](https://harbour.space/) and Codeforces in the <a href="http://codeforces.me/blog/entry/51208">blog post</a>. This round will be **rated for the participants with rating lower than 2100**. It will be held on extended ICPC rules. The penalty for each incorrect submission until the submission with a full solution is 10 minutes. After the end of the contest you will have 12 hours to hack any solution you want. You will have access to copy any solution and test it locally. You will be given **6 or 7 problems** and **2 hours** to solve them. The problems were invented and prepared by Roman [user:Roms,2020-04-09] Glazov, Adilbek [user:adedalic,2020-04-09] Dalabaev, Vladimir [user:vovuh,2020-04-09] Petrov, Ivan [us...

Full text and comments »

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

63.
By DanAlex, history, 11 years ago, In English
How to sweep like a Sir ### Cutting to the chase Clearly you don't need a PhD in Computing to sweep in the yard , but one might be useful in order to know linear and radial sweep algorithms. So , what's all about ? It's just what it sounds it is , sweeping linear ( up to down , for example ) or radial ( making a 360 degrees loop ). How this can help? [cut] Well... ### Linear sweep Suppose you a set of objects in an Euclidean plane. We need to extract information about some objects. The method of linear sweeping takes a line and moves it on a fixed direction. Usually the line taken would be vertical and the direction would be left to right or up to down. ![ ](https://upload.wikimedia.org/wikipedia/commons/2/25/Fortunes-algorithm.gif) Quite abstract for the moment , huh ? Let's go to a more specific example. #### Rectangle union area This example is well known. You have a set of rectangles with edges parallel to the OX and OY axes. What is their union area. Well , first of all , let'...

Full text and comments »

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

64.
By errorgorn, 5 years ago, In English
[Tutorial] Knapsack, Subset Sum and the (max,+) Convolution **Edit**: I have realized that this blog has been sent quite a lot on discord servers, so I am adding a content page at the start to help organize this blog better. ## Prerequisites Let us first define the classical knapsack, unbounded knapsack and subset sum problems. #### Subset Sum There are $N$ items. The $i$-th item has weight $w_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i = C$. #### Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. #### Unbounded Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a **multiset** $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. You should know how to do both versions of knapsack in $O(NC)$ and subset sum in $O(\frac{NC}{32})$ before reading this blog. In this blog post, I will just show some res...

Full text and comments »

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

65.
By tourist, 4 years ago, translation, In English
Codeforces Round #850 Editorial [problem:1786A2] Problem author: [user:KAN,2023-02-15] <spoiler summary="Explanation"> [tutorial:1786A2] </spoiler> <spoiler summary="Code by KAN"> ~~~~~ NT = int(input()) for T in range(NT): n = int(input()) answer = [0, 0, 0, 0] first_card = 1 for it in range(1, 20000): who = 0 if it % 4 == 1 or it % 4 == 0 else 1 cnt = it if n < cnt: cnt = n cnt_white = (cnt + first_card % 2) // 2 cnt_black = cnt - cnt_white answer[who * 2 + 0] += cnt_white answer[who * 2 + 1] += cnt_black first_card += cnt n -= cnt if n == 0: break assert(n == 0) print(*answer) ~~~~~ </spoiler> [problem:1786B] Problem author: [user:KAN,2023-02-15] <spoiler summary="Explanation"> [tutorial:1786B] </spoiler> <spoiler summary="Code by KAN"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int inf = 1000000000; int main() { int tt; cin >> tt; while (tt--) { int n, w, h; cin >> n >> w >> h; ...
class Modular { public: using Type = typename decay::type, )>::type, md>>;, const Type& operator()() const { return value; } template explicit operator U, private: Type value; };, template class Modular { public: using Type = typename decay, template static Type normalize(const U& x) { Type v; if (-mod() <= x && x, template typename enable_if::Type, int>::value

Full text and comments »

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

66.
By adamant, history, 4 years ago, In English
Combinatorial species: An intuition behind generating functions Hi everyone! The usage of generating functions is quite common in competitive programming these days. But it seems to happen so, that they're mostly presented as a way to simplify formal manipulation with polynomial coefficients, rather than something meaningful. But there actually is a meaning to all of this, and today I'm going to shed a light on it. Alongside the blog post we'll uncover the combinatorial meaning of - The addition $F(x)+G(x)$, - The multiplication $F(x)G(x)$, - The exponent $\exp F(x)$, - The logarithm $\log F(x)$, - The sum of the infinite geometric progression $\frac{1}{1-F(x)}=1+F(x)+F^2(x)+\dots$, - The general composition $F(G(x))$ for the generating functions $F(x)$ and $G(x)$ and the underlying structures they represent. ### Prerequisites - Basic notion of set theory (cardinality of sets, mappings, bijections, cartesian product, disjoint union, etc); - Polynomials and formal power series (representation, convolution formula, power seri...
permutations are equivalent under re-labeling if and only if they have the same [cycletype](https

Full text and comments »

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

67.
By MikeMirzayanov, 9 years ago, translation, In English
Codeforces: Thanks for the support! <img src="/predownloaded/70/a9/70a96afc574eb7a6ee37d8a1ee175f91b2b3c83a.png" style="float: right; margin: 0 1em 1em 1em"/> Hello! This blog post is about the end of the crowdfunding campaign dedicated to the 8th anniversary of Codeforces. Everything worked out. Hooray! For us, it is very important to support not only in terms of the collected budget, but as a powerful indicator that Codeforces is important to you. It was very pleasant to read words of gratitude and congratulations. Thank you! We received more than 1000 donations from community members from around the world. For 45 days we've collected more than $60000 dollars. The collected funds will allow us to continue to move forward, to please you with new contests and improvements of the system. I am happy to report that starting in May 2018, we will be able to slightly increase rewards for problem writers. |Round type|USD|Rubles| |-----------|--|---| |Div 1 + Div 2| $250+*$150=$400 | 26000 rub | | Div 2 | $1...
|Round type|USD|Rubles| |-----------|--|---| |Div 1 + Div 2| $250+*$150=$400 | 26000 rub | | Div

Full text and comments »

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

68.
By sammyuri, 6 months ago, In English
Spectral::Cup 2026 Round 2 (Codeforces Round 1100, Div. 1 + Div. 2) Editorial Thank you for participating in our round! We hope you enjoyed the problems as much as we enjoyed preparing them. <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Absolute Cinema contest - 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:2229A] Idea by: [user:Intellegent,2026-05-23] Prepared by: [user:Intellegent,2026-05-23] Editorial by: [user:reirugan,2026-05-23] <spoiler summary="Hint 1"> Let $y$ denote the final position of all of the slimes. Then it is optimal to choose $x = y$ for every operation. </spoiler> <spoiler summary="Hint 2"> Let $\mathrm{mn}$ denote the minimum value in $a$, a...
(__VA_ARGS__) #define VEC(type, name, size) vector<type> name(size); read(name), ++){ int type = 0; if (a[i] >= mid) type++; if (b[i] >= mid, if (type == 0){ if (prev != 0) zero++; prev, if (type == 1) continue;, if (type == 2){ one++; prev = 1; }

Full text and comments »

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

69.
By manish.17, 5 years ago, In English
Codeforces Round #766 (Div. 2) omg hi Codeforces! [user:ScarletS,2022-01-12], [user:flamestorm,2022-01-12], [user:fishy15,2022-01-13], [user:saarang,2022-01-12], <a class="rated-user user-orange" href="/profile/lookcook" title="Did no work and cried for name to be here">lookcook</a> and I are glad to invite you to our Codeforces round, [contest:1627], which will be held on [contest_time:1627]. **This round will be rated for participants with rating lower than 2100**. We would like to thank: - [user:Monogon,2022-01-12] senpai for excellent coordination of the contest. - [user:MikeMirzayanov,2022-01-12], for creating the amazing Codeforces and Polygon platforms! - [user:KAN,2022-01-15], for Russian translations! - [user:dorijanlendvaj,2022-01-12], [user:errorgorn,2022-01-12], [user:PurpleCrayon,2022-01-12], [user:generic_placeholder_name,2022-01-12], [user:blue,2022-01-12], [user:polarity-,2022-01-12], [user:atharv,2022-01-12], [user:epicxtroll,2022-01-12], [user:dbsic211,2022-01-12], [user:StArChAn...

Full text and comments »

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

70.
By galen_colin, 6 years ago, In English
Hybrid Tutorial #-1: Heavy-Light Decomposition **[Here](https://www.youtube.com/watch?v=_G_LMuLWMaI&list=PLDjGkpToBsYDx4GWu2u87sTqt6ICELz-T) is a playlist of all hybrid tutorials I've done.** # "Intro" _Timestamp: [00:00](https://youtu.be/_G_LMuLWMaI)_ Hi! Definitely not inspired by [this comment](https://codeforces.me/blog/entry/81086?#comment-675431), I've decided to try something that seems relatively novel &mdash; combining a blog and video tutorial into one, in a "hybrid" fashion. Both should be usable independently, but they will have the same "flow" and structure so you can reference both for concepts that are harder to grasp, and the two will supplement each other. The goal of these is to be **complete** &mdash; beneficial for both video and blog lovers, as well as full of enough information that anyone without much of an idea of what the concept is should be able to fully understand. There will be code as well, however, I very highly recommend not looking at it, but rather working out the implementation for yours...
used all over, and is essentially the data type that should be used for queries, updates, and general

Full text and comments »

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

71.
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...
Suppose that you can use $x$ operations of type $1$ and $y$ operations, You should use operations of type $2$ first, then moves of type $1, of type $2$. , Let $y$ be the number of moves of type $2$; we can try all values of $y$ ($0 \leq y \leq 30$) and

Full text and comments »

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

72.
By awoo, history, 4 years ago, translation, In English
Educational Codeforces Round 142 [Rated for Div. 2] Hello Codeforces! On [contest_time:1792] [contest:1792] will start. Series of Educational Rounds continue being held as [Harbour.Space University](https://harbour.space/) initiative! You can read the details about the cooperation between [Harbour.Space University](https://harbour.space/) and Codeforces in the <a href="http://codeforces.me/blog/entry/51208">blog post</a>. This round will be **rated for the participants with rating lower than 2100**. It will be held on extended ICPC rules. The penalty for each incorrect submission until the submission with a full solution is 10 minutes. After the end of the contest, you will have 12 hours to hack any solution you want. You will have access to copy any solution and test it locally. You will be given **6 or 7 problems** and **2 hours** to solve them. The problems were invented and prepared by Adilbek [user:adedalic,2023-01-23] Dalabaev, Vladimir [user:vovuh,2023-01-23] Petrov, Ivan [user:BledDest,2023-01-23] Androsov, Ma...

Full text and comments »

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

73.
By purplesyringa, history, 6 years ago, In English
crazySegmentTree: Segment Tree implementation with 5x faster queries than bottom-up tree Hello, Codeforces! A few days ago [user:MohammadParsaElahimanesh,2021-04-06] posted a blog titled [Can we find each Required node in segment tree in O(1)?](https://codeforces.me/blog/entry/89377) Apparently what they meant was to find each node in $\mathcal{O}(ans)$, according to [ecnerwala's explanation](https://codeforces.me/blog/entry/89377?#comment-777885). But I was too dumb to realize that and accidentally invented a parallel node resolution method instead, which speeds up segment tree a lot. A benchmark for you first, with 30 million RMQ on a 32-bit integer array of 17 million elements. It was run in custom test on Codeforces on Apr 6, 2021. - **Classic implementation from cp-algorithms:** 7.765 seconds, or 260 ns per query - **Optimized classic implementation:** (which I was taught) 4.452 seconds, or 150 ns per query (75% faster than classic) - **Bottom-up implementation:** 1.914 seconds, or 64 ns per query (133% faster than optimized) - **Novel parallel implement...
The following line sets the type of the elements. It *must* be a 32-bit integer, either signed or

Full text and comments »

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

74.
By adamant, 11 months ago, In English
Caveats of using optimize("Ofast") with target("avx2") Hi everyone! As you may know, it is often recommended to put these lines in your header: ```cpp #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2") ``` And they're usually great!<sup>[1]</sup> Well, until they aren't. For last 2-3 days I was riddled with the issue that [CP-Algorithms Library](https://lib.cp-algorithms.com) would perform very well on Library Checker, but whenever I tried to also apply it on Codeforces, it will fail to speed up the code, and sometimes would even make it much slower. As I finally figured out the cause, I'd like to write a blog about it, so that other people don't waste as much time. Mitigating these issues improved my running time on [problem:1975G] from **1530 ms** in [submission:316602668] to **203 ms** in [submission:352602775]. ##### Tl'dr See the "Takeaway" section at the bottom. [cut]<br> ##### Example problem I will reproduce the issue on a simple example: <hr> **[problem:911G]**: You are given an...
First of all, we can, again, downgrade optimization type to `O3` in **[submission:352729593]**:

Full text and comments »

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

75.
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...
each type of snake., position, and then use `_mm_and_epi32` to combine type 1 and type 2 snakes. Using `_mm_blendv_epi8, ` data type with `__m256i` data type, and rename the functions `_mm_...` with `_mm256_...` and, |$. If $k$ is positive, the snake is a type 1 snake, otherwise, it is a type 2 snake. We will define a

Full text and comments »

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

76.
By Wind_Eagle, 5 years ago, In English
Codeforces Round #741 (Div. 2) <p align="right"><small>Choose the way, five paths there for you to find<br>Turn the page, the question lies between the lines... <p align="left"> Hello, Codeforces! I hoped that once there will be my second round, and finally, here it is! I am very glad to invite you to the [Codeforces Round #741 (Div. 2)](https://codeforces.me/contest/1562), which will take place in [contest_time:1562]. <b>This round will be rated for the participants with rating lower than 100000110100 (2100).</b> My thanks to: - [user:antontrygubO_o,2021-08-24] <s>for rejecting problems A</s> his great coordination of this round! Thanks! - [user:gepardo,2021-08-24] made a lot. There wouldn't have been this contest if he didn't help me. Thanks! - [user:EIK,2021-08-24] this is the person who taught me competitive programming — my Informatics teacher. Thanks! - [user:MikeMirzayanov,2021-08-24] for Codeforces and Polygon platforms. Thanks! - You for participating in this round. Thanks! You...
on _your favourite type of problems_](https://codeforces.me/blog/entry/45307) before the round.

Full text and comments »

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

77.
By DrSwad, history, 7 years ago, In English
A Beautiful Technique for Some XOR Related Problems ## Inspiration I'm very excited about this blog, as it took me quite a lot of effort and scavenging through the internet to completely grasp the concept of this technique(That's probably because I have almost zero knowledge in Linear Algebra or I'm just plain dumb). So I feel like I genuinely conquered a challenge, and I really want to share it with someone. But there's no way my CP friends circle will believe it, they'll think I'm just trying to show off :P So here I am, sharing it on CF. I also created a [personal blog](https://drschwad.github.io/), so that if I ever feel like sharing something again(not only about CP), I can write a blog there. I also added this same post [there](https://drschwad.github.io/2019-08-06-z2-space-xor-trick/), you can read it there if you prefer dark theme. I'll be pleased to hear any thoughts on the blog or if I can improve it in some way ^\_^ ## Introduction Since it concerns Linear Algebra, there needs to be a lot of formal stuff going on ...
would fit in an integer type, since size of basis $\le d = 20$ by property $7.$, . Type $1$: Insert an element $1 \le k \le 10^9$ to the set(If it's already in the set, do nothing, type instructing you to insert numbers in the array(_without removal_, I don't know how to solve

Full text and comments »

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

78.
By errorgorn, 4 years ago, In English
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
\log n)$ where $q_1$ and $q_2$ are the number of queries of type $1$ and $2$ respectively., Of these $3$ queries, only the first query type is a sub-array query on the heavy chain, the rest

Full text and comments »

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

79.
By Igorjan94, history, 9 years ago, In English
C++17, competitive programming edition C++17 is now [available](http://codeforces.me/blog/entry/57646) on codeforces, community [wants](http://codeforces.me/blog/entry/15643?#comment-413401) new edition of [C++ tricks](http://codeforces.me/blog/entry/15643) by [user:Swift,2018-02-19], so, let's start! Disclaimer: I have done only few examples of new features, which in my opinion are related to competitive programming. Feel free to comment and provide more real-world examples or ask to elaborate some features with more examples or explanations. ### Fold expressions * I think that everybody knows, what reduce or fold means, but a c++11 example: ``` vector<int> v = {1, 3, 5, 7}; int res = accumulate(v.begin(), v.end(), 0, [](int a, int b) { return a + b; }); cout << res; // 16 ``` * In C++17 there is also folding support for a template parameters list. It has the following syntax: ``` (pack op ...) (... op pack) (pack op ... op init) (init op ... op pack) ``` * For example, implement a template...
``` int requests, type; cin >> requests; for (int q = 0; q < requests; ++q) switch (cin

Full text and comments »

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

80.
By -is-this-fft-, history, 2 years ago, In English
PSA on Meta Hacker Cup (must read if its your first time!) Meta Hacker Cup is upon us again. Along with it comes the unique format where we have to run our code on large test cases ourselves. Unfortunately, past experience shows that not everyone knows how to do this reliably. Usually, after the first round, many people lose points as a result of an unreliable workflow. This time, let's try to prevent that from happening. Sorry for the somewhat self-important title, but I really do wish that everyone understood this and that no one will fail the contest because of this. ### Don't EVER copy-paste huge files A lot of people's workflow to run a solution is the following: - Click some green button in the IDE - A box comes up, copy-paste the input into that box - The output shows up somewhere This may work well for running your solution on small sample test cases. It is **terrible** for running your solution on the huge test cases in Meta Hacker Cup. In last year's Round 1, the full test case for [problem C](https://www.facebook.com...
**Option 1.** (Linux and probably Mac OS, only if running command line) Type `ulimit -s unlimited

Full text and comments »

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

81.
By Artyom123, 5 years ago, translation, In English
Codeforces Global Round 16 Editorial We hope that you enjoyed the contest. Let's get right into the editorial: <spoiler summary="A: Median Maximization"> [problem:1566A] <spoiler summary="First solution"> <spoiler summary="Hint 1"> Which numbers smaller than the median should be taken? </spoiler> <spoiler summary="Hint 2"> Which numbers bigger than the median should be taken? </spoiler> <spoiler summary="Hint 3"> Greedy algorithm. </spoiler> <spoiler summary="Editorial"> Let's consider the array of $n$ elements in non-decreasing order. We can make numbers before the median equal to zero, after that we have $m = \lfloor {\frac{n}{2}} \rfloor + 1$ numbers, which sum should be $n$ and the minimal of them (i.e. median value) should be maximized. To do so, it is enough to make all these numbers equal $\lfloor {\frac{s}{m}} \rfloor$, and then add what's left to the last number ($s \bmod m$). It's easy to see that such array matches all the conditions and it is impossible to make median greater. </s...
To find the answer of the second type you can leave in the graph only, ) continue; dfs(to, v); if (type[to] == 1) leaves = true; } if (v != p, ); g[y].emplace_back(x); } type[0] = 0; dfs(0, 0); bool, To find the answer of the first type it is enough to maintain three minimal edges for each vertex., vector> g; vector type; // -1 -- default, 0 -- root, 1 -- leaf, 2 -- bud

Full text and comments »

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

82.
By errorgorn, 6 years ago, In English
Tutorial on Permutation Tree (析合树) So my O level Chinese exam is in 2 days so I decided to learn a data structure that I can only find [resources](https://oi-wiki.org/ds/divide-combine/) for in Chinese. I thought I might as well write a tutorial in English. This data structure is called 析合树, directly translated is cut join tree, but I think permutation tree is a better name. Honestly, after learning about it, it seems like a very niche data structure with very limited uses, but anyways here is the tutorial on it. Thanks to [user:dantoh,2020-06-16] and [user:oolimry,2020-06-16] for helping me proofread. ### Motivation Consider this [problem](https://codeforces.me/contest/526/problem/F). We are given a permutation,$P$ of length $n$. A good range is a contiguous subsequence such that $\max\limits_{l \leq i \leq r} P_i - \min\limits_{l \leq i \leq r} P_i = r-l$. This can be thought of the number of contiguous subsequence such that when we sort the numbers in this subsequence, we get contiguous values. Count the...
process until we cannot do any more operations of type 1 or 2. 4. Finally, push the currently

Full text and comments »

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

83.
By alexlikemath007, 4 years ago, In English
A proper tutorial for one of the craziest 3D-geometry problems Warning: This problem is like the warden of competitive programming. It is a force of nature &mdash; like a hurricane, and when you see a hurricane you don't fight it, you run. It is a big bad boss with a bunch of hitpoints, and deals big damage to your sanity. But when you kill it, it doesn't drop much loot, experience, or educational value compared to other problems. It would be wiser to go and solve some problems and learn how to use binary search. The problem: https://codeforces.me/gym/102452/problem/F It's tutorial says: Since n is small, $O(n^2)$ simulation is OK. Advanced 3-D geometry methods are highly required. The tutorial doesn't describe what the advanced 3-D geometry methods are. So, I have written this blog to remedy that gap. <spoiler summary="Chapter 1. Prologue"> You should create a `point` struct this makes things a bit easier. It has an `double x`, `double y`, `double z` coordinate. This point will be immensely useful, as we can define a line segment...
- `int t` (type), - `rotation r` (rotation), - a `point c` (center), - a `double s` (size).

Full text and comments »

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

84.
By pseudocoder10, 6 years ago, In English
Lockout Bot for codeforces Hello everyone, I'm sure many of you have been watching and enjoying the recent [lockout streams](https://www.youtube.com/watch?v=bBNIIg8REUU&feature=youtu.be) organized by [user:ecnerwala,2020-06-08] and [user:scott_wu,2020-06-08] and would be wanting to compete with your friends in a similar format. I have made a discord bot that does exactly the same. The source code for the bot can be found [here](https://github.com/pseudocoder10/Lockout-Bot). The bot gives a set of 5 problems with ratings from [x, x+400], where x is chosen by you and the point distribution is [100, 500]. The first person to solve a problem gets the points for it. The match ends when someone has >= 800 points or 45 minutes have been elapsed. The bot automatically updates the status when someone solves a problem but you can also do it manually. To invite the bot to your discord server, click [here](https://discord.com/oauth2/authorize?client_id=669978762120790045&permissions=0&scope=bot). If you don't wanna ...
First you will have to link your codeforces handle with your discord id. To do thattype `.handle, To accept a challenge, simply type `.match accept` and the bot will chose 5 random unsolved

Full text and comments »

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

85.
By animeshf, history, 11 years ago, In English
Mo's Algorithm on Trees [Tutorial] Introduction ------------ Mo's Algorithm has become pretty popular in the past few years and is now considered as a pretty standard technique in the world of Competitive Programming. This blog will describe a method to generalize Mo's algorithm to maintain information about paths between nodes in a tree. Prerequisites ------------- Mo's Algorithm &mdash; If you do not know this yet, read this amazing [article](http://blog.anudeep2011.com/mos-algorithm/) before continuing with this blog. Preorder Traversal or DFS Order of the Tree. Problem 1 &mdash; Handling Subtree Queries ------------------------------------------ Consider the following problem. You will be given a rooted Tree $T$ of $N$ nodes where each node is associated with a value $A[node]$. You need to handle $Q$ queries, each comprising one integer $u$. In each query you must report the number of distinct values in the subtree rooted at $u$. In other words, if you store all the values in the subtree rooted...
order works brilliantly to handle any type path queries and works well with Mo's algo. We can use a

Full text and comments »

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

86.
By errorgorn, history, 5 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...
We claim that in the optimal answer all characters of some type will appear consecutively.

Full text and comments »

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

87.
By adamant, history, 4 years ago, In English
Arrow product: How to enumerate directed graphs Hi everyone! In this blog, I would like to present a somewhat novel concept in competitive programming, which is, while being relatively simple, allows us to enumerate directed graphs with specific type of strongly connected components. This allows us to easily and uniformly compute generating functions e.g. for acyclic digraphs or strongly connected digraphs. The formalism introduced here is also very intuitive at that. I initially wanted to make a problem based on the content of this blog to appear in today's round, but after some discussions we decided to exclude it, as the contest already had a sufficient amount of difficult problems. You may try the original problem **[problem:441297A]** via the [invitation link](https://codeforces.me/contestInvitation/4d42a205a747b194397bbabd35ab2e81f9793447). #### Prerequisites You are expected to be familiar with exponential generating functions, and the [exponential formula](https://en.wikipedia.org/wiki/Exponential_formula) for c...
picking an element of type $A$ on $i$ "atoms" and an element of type $B$ on $j$ atoms, we connect each, #### Enumerating digraphs with given type of SCCs, 1. We either draw, or do not draw a (directed) edge from the vertices of an object oftype $A$ to

Full text and comments »

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

88.
By smax, 3 years ago, In English
[Tutorial] Simulating Cost Flow You can also read this on my blog: https://mzhang2021.github.io/cp-blog/simulating-cost-flow/ Thanks to [user:gabrielwu,2023-07-19] for proofreading. --- This post assumes knowledge of [min/max cost flow](https://en.wikipedia.org/wiki/Minimum-cost_flow_problem) and a rough understanding of the high-level methods for solving (successive shortest path and cycle canceling). Knowledge of specific algorithms and implementation details are not expected. Also solutions to some problems will use [Aliens trick](https://web.archive.org/web/20210511092429/http://www.serbanology.com/). --- The cost flow problem is a well-known problem in literature that a whole slew of competitive programming problems can be formulated as. Unfortunately, competitive programming problems typically have constraints set too high for directly running even the most state of the art cost flow algorithm. However, in certain problems the flow network will have a very specific setup that allows us to figure ...

Full text and comments »

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

89.
By BlueSmoke, 7 years ago, In English
Codeforces Round #641 Editorial You can view Chinese editorial here: https://www.luogu.com.cn/blog/Caro23333/codeforces-round-641-zhong-wen-ti-xie Div2.A Problem and editorial by [user:ProgSlacking,2020-05-12] <spoiler summary="Editorial"> [tutorial:1350A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; int main() { int T; cin >> T; while(T--) { int n,k; cin >> n >> k; if(n%2==0) { cout << n+2*k << endl; continue; } int p = 0; for(int i = n; i>=2; i--) if(n%i==0) p = i; cout << n+p+2*(k-1) << endl; } return 0; } ~~~~~ </spoiler> Div2.B Problem and editorial by [user:ProgSlacking,2020-05-12] <spoiler summary="Editorial"> [tutorial:1350B] </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; con...
#define mp make_pair #define pb push_back template TYPE> inline void chkmax( TYPE &x, int n,m,cnt; pii a[MAXN]; bool avis[MAXN]; struct Range { int l,r,type; ll val; Range

Full text and comments »

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

90.
By SanguineChameleon, 19 months ago, In English
Neowise Labs Contest 1 (Codeforces Round 1018, Div. 1 + Div. 2) Editorial [Sorry about problem H.](https://codeforces.me/blog/entry/142069) Thank you for understanding, and we hope you enjoyed the rest of the problems :D --- <h3>[problem:2096A]</h3> Idea: [user:SanguineChameleon,2025-04-20] <br> <spoiler summary="Step 1"> Create your own test cases and solve them! What can you observe? </spoiler> <spoiler summary="Step 2"> What is the length of the $n$-th stick? <spoiler summary="Answer"> - If $s_{n - 1} = \texttt{<}$, then $a_n = 1$, because the $n$-th stick must be shorter than all the other sticks. - If $s_{n - 1} = \texttt{>}$, then $a_n = n$, because the $n$-th stick must be longer than all the other sticks. </spoiler> </spoiler> <spoiler summary="Step 3"> Can we do something similar for the remaining sticks? <spoiler summary="Answer"> Yes! Remove the $n$-th stick, and then solve for the remaining $n - 1$ sticks. We can make similar observations about the $(n - 1)$-th stick. Then, remove the $(n - 1)$-th st...
we should choose the type with more gloves., $. Then we need at least $d$ operations of type A or type C., Consider how each type of operation changes the value of $b$:, Then, we perform $\frac{x - d}{2}$ operations of type B or type D to reduce the number of

Full text and comments »

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

91.
By sdnr1, history, 8 years ago, In English
[Tutorial] Searching Binary Indexed Tree in O(log(N)) using Binary Lifting **NOTE** : Knowledge of Binary Indexed Trees is a prerequisite. ## Problem Statement Assume we need to solve the following problem. We have an array, $A$ of length $N$ with only non-negative values. We want to perform the following operations on this array: 1. Update value at a given position 2. Compute prefix sum of $A$ upto $i, i \leq N$ 3. Search for a prefix sum (something like a `lower_bound` in the prefix sums array of $A$) [cut] <br> ## Basic Solution Seeing such a problem we might think of using a Binary Indexed Tree (BIT) and implementing a binary search for type $3$ operation. Its easy to see that binary search is possible here because prefix sums array is monotonic (only non-negative values in $A$). The only issue with this is that binary search in a BIT has time complexity of $O(log^2(N))$ (other operations can be done in $O(log(N))$). Even though this is naive, here is how to do it: <spoiler summary="Implementation"> `int sum(pos)` -> comput...
search for type $3$ operation. Its easy to see that binary search is possible here because prefix

Full text and comments »

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

92.
By Noam527, 6 years ago, In English
[Tutorial] Supporting Queue-like Undoing on DS In many data structures, the operation of "undo" on the last update can be implemented easily: we can (usually) maintain a stack of the updates, where each update on the stack holds the memory cells it changed, and their original values. To undo an operation, just revert all changes from the top update on the stack. To maintain good complexity, we require the updates to operate in non-amortized time. I've seen this being used multiple times on DSU (without path compression). If we imagine the updates as a sequence, then we can push an update to the end, and pop an update from the end by undo. Then, this sequence is a stack of updates. Here we discuss the idea of having a queue of updates: we can add a new update, or undo the oldest update still active. Specifically, this blogpost attempts to solve the following problem: Given a data structure that can support some updates, some queries and an "undo" operation (each with their own time complexity), how can we create a data structu...
$ or $B$). Let $x_i$ denote the fixing cost of $O_i$: if $O_i$ is of type $B$, then $x_i = 0$ as there

Full text and comments »

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

93.
By Errichto, 7 years ago, In English
Randomized algorithms lecture, part 1 & 2 You can watch the lecture on Youtube: https://youtu.be/0r2D32esF3Y. I will do a second part soon. Some problems are quite vague, it's a nature of this topic. 1. Warm-up: You toss a coin till you get tails. How many tosses there will be, on average? 2. **X or smaller** &mdash; There is a hidden number $X$. An interactor repeatedly gives you a number, either $X$ or something smaller than $X$. All numbers are positive integers. When can you stop and say that you are (almost) certain what is the value of $X$? 3. **Line through N/4 points** &mdash; Given $N \leq 10^5$ points, find a line that passes through the maximum number of points. It's guaranteed that the answer is at least $N / 4$. 4. **GCD** ([problem:364D]) &mdash; given a set of $N \leq 10^6$ numbers, each up to $10^{12}$, find the maximum possible number that is a divisor of at least half of given numbers. 5. **ACTG prefix** &mdash; Guess a hidden string $S$ with characters A, C, T, G. You can choose some string and ask if...
. **Birthday paradox** — How many encounters before we see the same type of Pokemon twice? 3. **Hash

Full text and comments »

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

94.
By purplesyringa, history, 2 years ago, In English
Please improve QoL for blogs I'm pretty sure I've spent more time writing blogs than contests on Codeforces. Over time, I've found plenty of rough edges. So this is a plea to the Codeforces team to fix them. I'm effectively going to say "please redo everything" over dozens of paragraphs, but I'll hopefully make the steps to the solution tangible and clear. If this is deemed way too ambitious, few improvements are better than none. [cut] <!-- --> ## Publication time So I write a post in the Codeforces UI, save a draft, update it a few times, think it's ready, and publish it. I open my brand new post and see: > ### Totally not a useless post > By [user:purplesyringa,2024-09-24], history, 3 days ago, In English Okay, wait, "3 days ago"? Oh, right, that's when I saved the first draft. Now people open the post, see "3 days ago", see 0 upvotes, and what do they think? That's right, they think it's garbage because no one's voted positive, so they skip the article. Maybe not everyone's like tha...

Full text and comments »

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

95.
By adamant, history, 3 years ago, In English
Efficient linear algebra for dummies Hi everyone! Some time ago I started developing a linear algebra library for Library Checker, and it turned out to be much fun. I'd like to write this blog to outline how one can implement a linalg library with a very good Library Checker performance, while also avoiding highly technical low-level details that are common in other similar blogs. Instead, we will learn a few high level ideas that will let us write a code that the compiler will then optimize using all these fancy techniques _in our stead_. Huge thanks to ~ToxicPie9,2024-05-08 and [user:magnus.hegdahl,2024-05-08] for explaining me some of the optimizations used here! You may also look into ~sslotin,2024-05-08's [entry](https://codeforces.me/blog/entry/101655) about how it can be sped up even further with more advanced and low-level techniques. ### Tl'dr. In this blog, I present my [matrix library](https://cp-algorithms.github.io/cp-algorithms-aux/cp-algo/linalg/matrix.hpp), which maintains a simple and elegant...
operations independent from the implementation of the underlying storage type (e.g. floating-point

Full text and comments »

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

96.
By sevlll777, history, 5 years ago, translation, In English
Codeforces Round #770 (Div. 2) editorial Thank you for participating, we hope you enjoyed the problems! We kindly ask you to rate each of the round's problems in the corresponding spoiler in order to improve the quality of future contests. You can also check video editorials of problems B and C on [user:ak2006,2022-02-06] [Youtube channel](https://www.youtube.com/channel/UCnZ5rC2_JY0EuYMGMiAbISg). All problems were prepared by [user:Alexdat2000,2022-02-02] with the help of coauthors. [Why didn't AI participate](https://codeforces.me/blog/entry/99579?#comment-884764) [problem:1634A]<br> Idea: [user:sevlll777,2022-02-02] <div class="spoiler"> <b class="spoiler-title">Hint 1</b> <div class="spoiler-content" style="display: none;"> What property will the string have after the first operation (regardless of the type of operation)? </div></div> <div class="spoiler"> <b class="spoiler-title">Hint 2</b> <div class="spoiler-content" style="display: none;"> What happens if you apply an operation to a palindrome? ...
="display: none;"> What property will the string have after the first operation (regardless of thetype of

Full text and comments »

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

97.
By adamant, history, 4 years ago, In English
Osijek Competitive Programming Camp 2023 winter Hi everyone! <center><a href="https://ocpc.mathos.unios.hr/index.php"><img src="https://ocpc.mathos.unios.hr/images/ocpc.svg" height="100px"></a></center> I am happy to announce the [Osijek Competitive Programming Camp](https://ocpc.mathos.unios.hr) that is scheduled to happen on **18-26 February 2023** in Osijek, Croatia. The camp is hosted by the [Department of Mathematics at J. J. Strossmayer University of Osijek](https://www.mathos.unios.hr/index.php/en/) and is brought to you by the organizing team of [user:adamant,2022-12-21] (that's me!), [user:-is-this-fft-,2023-01-06], [user:mblazev,2023-01-06], [user:Tomx,2023-01-06] and [user:antontrygubO_o,2023-01-05]. The camp is inspired by various competitive programming camps that we attended during our active years in ICPC, and is aimed to help college students prepare for ICPC regional contests and finals. The camp will consist of 7 ICPC-style contests and 2 days off. Up until now, most top competitive programming training...

Full text and comments »

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

98.
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...
#define vv(type,name,n,...) \ vector<type>> name(n,vector<type>(__VA_ARGS__)) #define, , std::make_unsigned, std::common_type>::type, template using to_unsigned_t = typename to_unsigned::type;

Full text and comments »

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

99.
By dacin21, history, 8 years ago, In English
On the mathematics behind rolling hashes and anti-hash tests This blog assumes the reader is familiar with the basic concept of rolling hashes. There are some math-heavy parts, but one can get most of the ideas without understanding every detail. The main focus of this blog is on how to choose the rolling-hash parameters to avoid getting hacked and on how to hack codes with poorly chosen parameters. # Designing hard-to-hack rolling hashes ## Recap on rolling hashes and collisions Recall that a rolling hash has two parameters $(p, a)$ where $p$ is the modulo and $0 \leq a < p$ the base. (We'll see that $p$ should be a big prime and $a$ larger than the size $\left|\Sigma\right|$ of the alphabet.) The hash value of a string $S = s_0 \dots s_{n-1}$ is given by $$ h(S) := \left(\sum\limits_{i=0}^{n-1} a^{n-1-i} s_i\right) \mod p $$ For now, lets consider the simple problem of: given two strings $S, T$ of equal length, decide whether they're equal by comparing their hash values $h(S), h(T)$. Our algorithm declares $S$ and $T$ t...
This section applies more generally to any type of randomized algorithm in an environment where

Full text and comments »

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

100.
By Endagorion, 12 years ago, In English
Codeforces Round #295 Editorial (now with bonuses!) We would like to thank the testers of this round's and Winter Computer Camp olympiad's problems: [user:alger95,2015-03-02], [user:thefacetakt,2015-03-02], [user:adamant,2015-03-02], [user:dragonic,2015-03-02], [user:Who179,2015-03-02], [user:ASverdlov,2015-03-02]. Make sure to comment if you find any mistakes. **UPD**: I've just remembered to put up the usual challenges for the problems. So, here they go. [problem:520A] Idea: [user:Endagorion,2015-03-02] Preparation: [user:Endagorion,2015-03-02] To check that every letter is present in the string we can just make a boolean array of size 26 and for every letter set the corresponding variable to TRUE. In the end check that there are 26 TRUEs. That is an $O(n)$ solution. Also don't forget to change all letters to lowercase (or all to uppercase). To make all the letters lowercase, one could use standard functions, like `tolower` in Python. Also, it is known that the letters from `a` to `z` have consecutive ASCII numbe...
Suppose that at some point we perform two operations of type 1 and then one operation oftype 2, Suppose the only type of upgrades we have is multiplication. It doesn't even matter for the answer

Full text and comments »

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

101.
By djm03178, 2 years ago, In English
Everything about Codeforces scoring system This is a tutorial to how Codeforces scoring system works and some basic strategies about it. I will only explain about rated rounds here, but note that there are other types of scoring in unrated contests. Please do share this blog when you see questions about it. Scoring types ------------------ There are two different types of scoring system: - Standard (Div. 1 / Div. 2, Div. 1 + Div. 2) - Extended ICPC (Educational, Div. 3, Div. 4) The standard (this is not a formal name, but I don't know if one exists) scoring is Codeforces' own scoring system where each participant's rank is determined solely by their **final score**. On the other hand, extended ICPC literally uses the ICPC rule for calculating ranks, using **number of solved problems & penalty**, with slight modifications. Standard ------------------ Contests using this scoring system have pre-determined initial scores on each problem. By initial it means you get that score when you solve it in the $0$-th min...

Full text and comments »

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

102.
By E869120, 9 years ago, In English
[Tutorial] A Way to Practice Competitive Programming : From rating 1000 to 2000 Dear Codeforces Community.<br /> <br /> Today I want to share some ways to practice competitive programming and getting rating. I think this is helpful for those who is practicing competitive programming hardly but rating is sluggish. (By the way, on July 17th, I have a project of competitive programming said CombNaf in Japan. I did a lecture about this. Great thanks to the CombNaf's organizer is [user:Nafmo2,2017-07-17].)<br /> <br /> I will write this by **4 steps**: rating **<font color="grey">1000</font> --> <font color="green">1250</font>**, **<font color="green">1250</font> --> <font color="aqua">1500</font>**, **<font color="aqua">1500</font> --> <font color="blue">1750</font>**, **<font color="blue">1750</font> --> <font color="purple">2000</font>**, in Codeforces Rating System.<br /> <br /> Before writing about each step, I wrote it as premise: You don't have to do this way. This is just a way to practice. Ways to practice is different among people, so I think this may n...

Full text and comments »

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

103.
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...
, interesting idea, not too focus on a specific type of problem, easy to solve but still require thinking a bit

Full text and comments »

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

104.
By Errichto, 7 years ago, In English
Bitwise operations for beginners You can watch my Youtube video ([link](https://www.youtube.com/watch?v=xXKL9YBWgCY&list=PLl0KD3g-oDOHpWRyyGBUJ9jmul0lUOD80)) with the same content as this blog. Anyway, enjoy. ### Introduction Let's learn bitwise operations that are useful in Competitive Programming. Prerequisite is knowing the binary system. For example, the following must be clear for you already. $$13 = 1 \cdot 8 + 1 \cdot 4 + 0 \cdot 2 + 1 \cdot 1 = 1101_{(2)} = 00001101_{(2)}$$ Keep in mind that we can pad a number with leading zeros to get the length equal to the size of our type size. For example, `char` has $8$ bits and `int` has $32$. ### Bitwise AND, OR, XOR You likely already know basic logical operations like AND and OR. Using `if(condition1 && condition2)` checks if both conditions are true, while OR (`c1 || c2`) requires at least one condition to be true. Same can be done bit-per-bit with whole numbers, and it's called bitwise operations. You must know bitwise AND, OR and XOR, typed r...
type size. For example, `char` has $8$ bits and `int` has $32$.

Full text and comments »

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

105.
By purplesyringa, history, 4 years ago, In English
Fixing the contest management mess ...or "How legacy systems fight obstacles no sane person would introduce in the first place". Hello, Codeforces! I am sure that those of you who tried to host their own programming competitions or write their own utilities for contest management are aware of the state of affairs regarding contest hosting. There are lots of incompatible formats, no one knows exactly how stuff ought to work, Polygon is full of nondescript and seemingly contradictory options, ej-polygon never seems to work quite correctly, modifications have to be applied to jury archives to make them work on your particular installation, non-trivial problem types require constant maintenance and hacks, *ad infinitum*. Personally, I stumbled upon all these problems when I tried to get my own judge system working and suddenly discovered that the difficult part is not judging complex problems, but handling artificial complexity introduced by legacy software and standards. So here I am, attempting to solve these pro...

Full text and comments »

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

106.
By satyam343, 4 years ago, In English
Codeforces Round #838 (Div. 2) Hello, Codeforces! [user:amurto,2022-12-13] and I are glad to invite everyone to participate in [contest:1762], which will be held on [contest_time:1762]. This Round will be rated for participants with rating strictly **lower than 2100**. Participants from the first division are also welcomed to take part in the competition but it will be unrated for them. You will be given **7 problems** and **2 hours and 30 minutes** to solve them. One of the problems will be **interactive**. Make sure to read [this blog](https://codeforces.me/blog/entry/45307) and familiarize yourself with these types of problems before the round! We would like to thank: - [user:errorgorn,2022-12-13] for amazing coordination and help with the problem preparation. - [user:KAN,2022-12-13] for translation of the statements into Russian - [user:TheScrasse,2022-12-13] for providing suggestions which helped us to improve one problem. - [user:GoatTamer,2022-12-13] for discussing problems with us whil...

Full text and comments »

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

107.
By Ahmadsm2005, history, 5 years ago, In English
Competitive Programming and MBTI personality types Hello, I have searched for a correlation between MBTI personality types and CPers but I haven't found an answer so, I am gathering statistics to see what are the most common personality types from CPers. You can divide personality types into 16 categories which makes up 4 letters(I/E,S/N,F/T,P/J). As a reference, here is the percentage of each personality type world-wide: ![ ](https://www.careerplanner.com/Images/social/TypeInPopulation-500w.png) For you to know which personality type you are, try the test [here](https://www.truity.com/test/type-finder-personality-test-new). It takes around 20 minutes to complete it. If you already know it, you can skip this step. Finally, fill [this form](https://forms.gle/NqsjjybrYSpMr3jw8) and please be honest in your answers. You will only be asked to pick your personality type corresponding with a rating range. I will share statistics within a few days. Note: Each letter corresponds to what you mostly are more. Example: I: Introve...
). As a reference, here is the percentage of each personality type world-wide: ![ ](https, . You will only be asked to pick your personality type corresponding with a rating range., For you to know which personality type you are, try the test [here](https://www.truity.com/test

Full text and comments »

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

108.
By ACGN, history, 2 years ago, In English
Codeforces Round 987 (Div. 2) Editorial <spoiler summary="A little backstory about the round (ACGN)">The Highschool CPers (HSCP) Discord server was created in April 2022 by [user:pwned,2024-11-14], which over time grew into a close-knit community of highschool competitive programmers. I joined in the same month of its creation, and in the next month I approached [user:pwned,2024-11-14] about the possibility of setting a contest. Thus the HSCP round concept was born. Over the next month or so, the initial problems were born; the current problems A and F were produced in June-July 2022. We had several problem ideas by then, enough to set a div.2 round. However, as I was going to be busy in my 5th year of high school, and may not be that responsive to coordinators, the contest was in the ownership of [user:pwned,2024-11-14], who needed to wait until he reached master in order to propose the set on Codeforces. However, this step took almost 1.5 years as he would stay at candidate master for 57 consecutive contests, eve...
able to find them from the pairs of type (1) and (2), since we have already found the ones intype, If we have two queries such that one query is type 4 and another is type 5, then we can use one

Full text and comments »

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

109.
By djm03178, history, 3 years ago, In English
A Type of Tests That Might Be Effective for Many Multi-Test Problems I've always loved hacking in CF rounds, especially for open hacking and uphacking. Recently, I've been focusing on hacking for TLE because there are plenty of solutions that can pass every single randomly generated tests but can still have broken worst case time complexity and the tests for that can only be found under deep investigation on the code. One of the findings that I saw during hacking in recent rounds, is that there is a fairly common mistake that many people make but most problems don't have tests against it. The conditions for such mistakes are: 1. The problem must be a multi-test problem (around $10^4$ or more if possible). 2. The constraint on the $n$ variable of a single test should be as large as the constraint on the sum of $n$ in all tests. 3. The solution has both of these slow aspects described below but none of them are _that_ slow to get TLE when only one of them is attacked. Condition #1 and #2 are very common in recent rounds so it's not hard to find...
A Type of Tests That Might Be Effective for Many Multi-Test Problems, it is something that future writers should consider: **Add several tests of suchtype for such

Full text and comments »

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

110.
By BledDest, 12 months ago, In English
About ER185, problem D Judging by the comments in the ER announcement, people seriously disliked problem D (to say the least). I want to explain why it exists. But first, I have to admit that I made two serious mistakes when setting the problem. My first mistake is actually putting it into a 2-hour solo round; in its current state, it is much more suitable for a longer contest with a team of three people, where you can actually get some help in debugging the code or verifying your solution logic. The second mistake will be explained a bit later, but I want to say that I understand why people think this is a terrible problem. I am sorry if this problem made the contest much worse for you. However, I am also asking that you consider my point of view. You don't have to agree with it, but I don't want anyone to view me as some insane author who's setting a problem just to watch everyone get furious while implementing it. This is definitely an implementation-heavy problem. But I think that implementation...
intersect. I dislike the first type, but I think that problems of the second type can be very interesting

Full text and comments »

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

111.
By adamant, history, 4 years ago, In English
Duality in linear programming. Part 1 — definition and construction Hi everyone! Previously I [wrote](https://codeforces.me/blog/entry/98334) about theoretical grounds of "aliens trick". Specifically, I introduced the concept of the Lagrangian duality and explained its connection with the trick. Today I want to elaborate a bit more on the concept of dual problems and their applications to linear programming as well as to common problems in competitive programming. I initially wanted to also write about some applications in competitive programming problems, but given that the introduction is already quite lengthy, I decided to leave it for another blog, while using most common and well-known theoretical examples here, focusing more on how to construct and interpret dual problems to begin with, rather than how to use it in contests. I think, it is a crucial first step towards using the duality in actual programming challenges. #### Prerequisites It is highly recommended to have some general understanding of basic mathematical optimization...
is generated by $\leq$-type constraint.

Full text and comments »

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

112.
By adamant, 3 years ago, In English
Osijek Competitive Programming Camp, Winter 2024 Hi everyone! <center><a href="https://ocpc.mathos.unios.hr"><img src="https://ocpc.mathos.unios.hr/images/ocpc.svg" height="100px"></a> <a href="https://icpc.foundation/"><img src="https://ocpc.mathos.unios.hr/images/ICPC.svg" height="100px"></a></center> <center> <b>Sponsored by</b><br> <a href="https://www.janestreet.com/join-jane-street/open-roles/?type=students-and-new-grads&location=london"> <img src="/predownloaded/ee/f2/eef26616a3661c658d1545f18ed21fabb14d5871.svg" height="50px" style="margin: 5px 5px 5px 5px;"> </a> <a href="https://pinely.com/"> <img src="/predownloaded/0a/0f/0a0f3f67435d1f6e467bc7203d4a2090ba8f92cc.svg" height="50px" style="margin: 5px 5px 5px 5px;"> </a> </center> After successful camps last year ([winter wrap](https://codeforces.me/blog/entry/113438), [fall wrap](https://codeforces.me/blog/entry/121684)), we are happy to announce that Osijek camp will be returning on **17.-25. February 2024** &mdash; just in time to prepare for the Wor...

Full text and comments »

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

113.
By thenymphsofdelphi, 4 years ago, In English
Codeforces Round #873 (Div. 1 & 2) Editorial ## [problem:1828A] Idea: [user:thenymphsofdelphi,2023-05-14] <br> Preparation: [user:Mike4235,2023-05-14] <spoiler summary="Hint 1"> Remember the sum of the first $n$ positive integers? </spoiler> <spoiler summary="Hint 2"> Every positive integer is divisible by $1$. </spoiler> <spoiler summary="Solution"> Consider the array $a = \left[1, 2, \ldots, n\right]$ that satisfies the second condition. It has the sum of $1 + 2 + \dots + n = \frac{n(n+1)}{2}$. One solution is to notice that if we double every element $(a=\left[2, 4, 6, \ldots, 2n\right])$, the sum becomes $\frac{n(n+1)}{2} \times 2 = n(n + 1)$, which is divisible by $n$. Another solution is to increase the value of $a_1$ until the sum becomes divisible by $n$. This works because every integer is divisible by $1$, and we only need to increase $a_1$ by at most $n$. Time complexity: $\mathcal{O}(n)$ </spoiler> <spoiler summary="Implementation 1"> ```c++ #include <bits/stdc++.h> using namespace s...
copium(int curr, int maxx, int type): curr(curr), maxx(max(maxx, curr)), type( type) {} };, if (imax - jmax == j - i) type = 0; else if (imax + i - j == rig[jmax] - 1) type = 1, if (jmin - imin == j - i) type = 0; else if (imin + j - i == lef[jmin] + 1) type = 1, if (type == 2) lmax[j] = copium(1, lmax[i].maxx, type); else if (lmax[i].type == 0, if (type == 2) lmin[j] = copium(1, lmin[i].maxx, type); else if (lmin[i].type == 0, struct copium { int curr, maxx, type;

Full text and comments »

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

114.
By ToxicPie9, 4 years ago, In English
[Tutorial/Parody Post] Common Mistakes in Competitive Programming and How to Avoid Them Yesterday [user:YouKn0wWho,2023-01-11] posted a [blog](https://codeforces.me/blog/entry/111217) explaining common mistakes in competitive programming and how to avoid them. I was greatly inspired by that post so I decided to make my own. I have compiled some of the mistakes that I didn't make in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in Rust as it is the most beloved language for CP. #### Mistake 1 Check out the following code: <spoiler summary="Code"> ``` fn main() { let x: i32 = 1_000_000_000; let y: i32 = 1_000_000_000; println!("{}", x * y); } ``` </spoiler> The output should be $10^{18}$. But if you run the code, you will get a different output. Why? <spoiler summary="Reason"> Because it won't even compile....
$10^9 \times 10^9$ does not fit inside the `i32` type which can only hold numbers up to $2^{31}-1

Full text and comments »

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

115.
By errorgorn, 4 years ago, In English
Catalan Numbers and Generating Uniform Balanced Bracket Sequences Hi everyone! Today [user:nor,2022-05-27] sir and I would like to talk about generating uniform bracket sequences. Over the past few years when preparing test cases, I have had to generate a uniform bracket sequence a few times. Unfortunately I could not figure out how, so I would like to write a blog about this now. Hopefully this blog would be useful to future problem setters :) Scroll down to the end of the blog to copy our generators. First, let's define some things. A bracket sequence is a string with $n$ $\texttt{(}$ s and $n$ $\texttt{)}$ s. A **balanced** brackets sequence is a bracket sequence with the additional constraint that it becomes a valid arithmetic expression when we add some $\texttt{1}$ s and $\texttt{+}$ s. Let $p$ be the prefix sum array of a bracket sequence (we assign $1$ to $\texttt{(}$ and $-1$ to $\texttt{)}$ and take the prefix sum). For example, if our bracket sequence is $\texttt{())()((())}$, then $p=[1,0,-1,0,-1,0,1,2,1,0]$. An alternate way to thi...
{((}\ldots\texttt{(}$ and $\texttt{)}$. We have $n$ cards of the first type and $m-n+1$ cards of the

Full text and comments »

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

116.
By BledDest, 3 weeks ago, In English
Educational Codeforces Round 196 — Editorial [problem:2283A] <spoiler summary="Tutorial"> [tutorial:2283A] </spoiler> <spoiler summary="Solution"> ~~~~~ t = int(input()) for i in range(t): l, r = map(int, input().split()) if r < 0 or l > 0: print(r - l) else: m = min(r, -l) print(max(0, r - l - 2 * m - 1)) ~~~~~ </spoiler> [problem:2283B] <spoiler summary="Tutorial"> [tutorial:2283B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for(int i = 0; i < n; i++) cin >> a[i]; int ans = 1; for(int i = 0; i < n; i++) { int cur = 0; for(int j = 0; j < n; j++) if(a[j] % a[i] == 0) cur++; ans = max(ans, cur); } cout << n - ans << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; for(int i = 0; i < ...
struct event { int moment; int type; int idx; event(int moment = 0, int type

Full text and comments »

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

117.
By adamant, history, 3 years ago, In English
OCPC 2024 Winter — wrap Hi everyone! <center><a href="https://ocpc.mathos.unios.hr"><img src="https://ocpc.mathos.unios.hr/images/ocpc.svg" height="100px"></a> <a href="https://icpc.foundation/"><img src="https://ocpc.mathos.unios.hr/images/ICPC.svg" height="100px"></a></center> <center> <b>Sponsored by</b><br> <a href="https://www.janestreet.com/join-jane-street/open-roles/?type=students-and-new-grads&location=london"> <img src="/predownloaded/ee/f2/eef26616a3661c658d1545f18ed21fabb14d5871.svg" height="50px" style="margin: 5px 5px 5px 5px;"></a> <a href="https://pinely.com/"> <img src="/predownloaded/0a/0f/0a0f3f67435d1f6e467bc7203d4a2090ba8f92cc.svg" height="50px" style="margin: 5px 5px 5px 5px;"></a> </center> Yesterday marked the conclusion of the third [Osijek camp](https://ocpc.mathos.unios.hr) (also see the [announcement](https://codeforces.me/blog/entry/124573) on Codeforces). Similar to the last time, the camp was organized by Tähvend Uustalu ([user:-is-this-fft-,2024-02-26]) and m...

Full text and comments »

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

118.
By awoo, history, 2 years ago, translation, In English
Educational Codeforces Round 166 Editorial [problem:1976A] Idea: [user:BledDest,2024-05-31] <spoiler summary="Tutorial"> [tutorial:1976A] </spoiler> <spoiler summary="Solution (awoo)"> ~~~~~ for _ in range(int(input())): n = int(input()) s = input() print("YES" if list(s) == sorted(s) else "NO") ~~~~~ </spoiler> [problem:1976B] Idea: [user:BledDest,2024-05-31] <spoiler summary="Tutorial"> [tutorial:1976B] </spoiler> <spoiler summary="Solution (Neon)"> ~~~~~ #include <bits/stdc++.h> using namespace std; using li = long long; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<li> a(n), b(n + 1); for (auto& x : a) cin >> x; for (auto& x : b) cin >> x; li sum = 0, ext = 1e18; for (int i = 0; i < n; ++i) { sum += abs(a[i] - b[i]); ext = min(ext, abs(a[i] - b[n])); ext = min(ext, abs(b[i] - b[n])); if (min(a[i], b[i]) <= b[n] && b[n] <= max(a[i], b[i])) ext = 0; } cout << s...

Full text and comments »

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

119.
By TheScrasse, 14 months ago, In English
Editorial of Codeforces Round 1053 (Div. 1, Div. 2) [problem:2151A] Author: [user:TheScrasse,2025-09-21]<br> Preparation: [user:TheScrasse,2025-09-21] <spoiler summary="Hint 1"> There are two types of subarrays. </spoiler> <spoiler summary="Hint 2"> If there exists $a_i \geq a_{i+1}$, how many times can the subarray appear? </spoiler> <spoiler summary="Solution"> - If there exists an $i$ such that $a_i \geq a_{i+1}$, we have $a_i = k$ for some $k$, $a_{i+1} = 1$. The subarray $[k, 1]$ appears only once on the blackboard (when James writes $1, \ldots, k$ and then $1, \ldots, k+1$). Since $a_1, a_2, \ldots, a_m$ contains $[k, 1]$, it must appear at most once as well, but the statement guarantees that it appears at least once, so the answer is $1$. - Otherwise, the array $a_1, a_2, \ldots, a_m$ can be rewritten as $l, l+1, \ldots, r$, and it appears when James writes $1, \ldots, r$, then when James writes $1, \ldots, r+1$, ..., then when James writes $1, \ldots, n$ (so $n-r+1$ times in total). Complexity: $O(n)$ </...
We then optimize this with storing a segment tree over the states $j$. The first type of transition

Full text and comments »

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

120.
By Ashishgup, history, 8 years ago, In English
CodeChef — ICPC: How hard is it to set a balanced contest? Due to my dislike of CodeChef discuss, I choose to discuss/rant about this topic here on Codeforces. Although non-Indian participants may not relate to the ICPC situation, I'm sure the CookOffs and Lunchtimes are a common issue. First of all, why is the difficulty gradient so fucked up every single time? ([Contest Link](https://www.codechef.com/ACMIND18)). Be it ICPC, or CookOffs, or LunchTimes, the same thing is seen over and over again. Scoreboard for reference: ![ ](https://i.gyazo.com/495d549bc79f3ca5d1cda359e26490ef.png) Secondly, why does online ICPC selection have only 5 questions for 3 hours? Not to mention, 3 of them are pretty hard, and the difficulty drop is huge, so it does not help filter out deserving teams from undeserving ones. Is ICPC selection supposed to be based on a speed typing test? In unbalanced contests like this, it almost always happens that some undeserving teams qualify. Every penalty matters a lot too. For instance, we failed to qualify for ...

Full text and comments »

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

121.
By PersistentLife, history, 3 months ago, In English
As an CNOI Gold Medalist: How I Train CNOI Gold Medal Winning Competitive Programmers UPD: [Curated Problem Set #1](Thhttps://codeforces.me/blog/entry/156427) is released. Please join our Discord server to receive the latest updates: https://discord.gg/DsHSfmVgG UPD: Curated problem set #1 (both normal and advanced) **for subscribers** is ready! Feel free to join our Discord server and subscribe! This post is about: 1. The Main Two Abilities You Need in Competitive Programming 2. How to Choose Problems of an Appropriate Difficulty 3. How Should You Work on a Problem 4. When You Should Learn New Knowledge (Like New Algorithms) 5. How to Train Before an Important Contest 6. Free Content, Personalized Subscription Services, and Potential Opportunity for One-to-One Coaching 7. Survey About the Services I won a gold medal at NOI 2024 in my second year of high school and was admitted to the Turing Class at Peking University. After securing my admission, I continued pursuing competitive programming: I began studying new material at university in advance whi...
No matter what type of problem appears in a contest, both thinking ability and coding ability are

Full text and comments »

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

122.
By zscoder, history, 10 years ago, In English
Codeforces Round #372 Editorial We hope everyone enjoyed the problems. Here is the editorial for the problems. I tried to make it more detailed but there might be some parts that might not be explained clearly. [Div. 2 A &mdash; Crazy Computer](http://codeforces.me/contest/716/problem/A) ------------------ Prerequisites : None This is a straightforward implementation problem. Iterate through the times in order, keeping track of when is the last time a word is typed, keeping a counter for the number of words appearing on the screen. Increment the counter by $1$ whenever you process a new time. Whenever the difference between the time for two consecutive words is greater than $c$, reset the counter to $0$. After that, increment it by $1$. Time Complexity : $O(n)$, since the times are already sorted. <spoiler summary="Code (O(n))"> ~~~~~ #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #def...
cycle. First, we investigate what happens when $d = 0$. Note that we cannot have a B-type and C, number of A-type, B-type, C-type, D-type edges respectively. Find the number of ways to create $k, Now, if $d \ge 1$, we can fix one of the D-type edges as the front of the cycle. This helps a lot

Full text and comments »

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

123.
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...
for(auto t: eff) { int i = t.second >> 1, type = t.second & 1; if(type == 0, for(auto t: vec) { int i = t.second >> 1, type = t.second & 1; if(type == 0

Full text and comments »

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

124.
By ouuan, history, 7 years ago, In English
One thing you should know about comparators — Strict Weak Ordering Is "In C++, comparator should return false if its arguments are equal." [all you should know about comparators in C++](https://codeforces.me/blog/entry/70237)? **Definitely NOT.** ### What's the requirement of the custom comparator in STL? It should be a *Strict Weak Ordering*. In other words, let the comparator be $f$, and $f(x, y)=true$ means $x< y$, then: 1. $f(x, x)$ must be false (Irreflexivity) 2. If $f(x, y)$ is true, then $f(y, x)$ must be false. (Antisymmetry) 3. If $f(x, y)=true$ and $f(y, z)=true$, then $f(x, z)$ must be true. (Transitivity) 4. If $f(x, y)=false$, $f(y, x)=false$, $f(y, z)=false$ and $f(z, y)=false$, then $f(x, z)=false$ and $f(z, x)=false$. (Transitivity of equivalence) In fact, *Antisymmetry* can be deduced by *Irreflexivity* and *Transitivity*, so we can ignore it. Here are some examples that these rules aren't satisfied: | Comparator | Irreflexivity | Transitivity | Transitivity of equivalence | Example | | :----------: | ...
nothing about the type provided by the user, except the comparator, which means "<".

Full text and comments »

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

125.
By adamant, history, 4 years ago, In English
A bit more of general ideas Hi everyone! Here's another collection of [little tricks](https://codeforces.me/blog/entry/100910) and [general ideas](https://codeforces.me/blog/entry/48417) that might make your life better (or maybe worse). Most of them are somewhat well-known, but perhaps would still be useful to someone. [cut]<hr> 1<!---->. **Evaluating polynomial modulo small prime $p$**. Given a polynomial $q(x)$, it may be evaluated in all possible $a \in \mathbb Z_p$ in $O(p \log p)$. To do this, compute $q(0)$ separately and use [chirp Z-transform](https://codeforces.me/blog/entry/83532) to compute $q(g^0), q(g^1), \dots, q(g^{p-2})$, where $g$ is a primitive root modulo $p$. _This method can be used to solve [problem:1054H]._ 2<!---->. **Generalized Euler theorem**. Let $a$ be a number, not necessarily co-prime with $m$, and $k > \log_2 m$. Then $$ a^k \equiv a^{\phi(m) + k \mod \phi(m)} \pmod m, $$ where $\phi(m)$ is Euler's totient. This follows from the Chinese remainder theor...
11. **Knapsack with repetitions**. You have $n$ item types, there are $a_i$ items oftype $i

Full text and comments »

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

126.
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...
Denote number of earned coins as $X$, and number of earned coins from selling items oftype $i$ as

Full text and comments »

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

127.
By unreal.eugene, 5 years ago, In English
Polygon Updates (June — August 2021) Hello, Codeforces. I and [user:DK318,2021-08-19] joined the Codeforces team in June. These three months we mainly dealt with the development of the Polygon platform. In this post, we would like to present to you a list of what we have done during this time. Most of the changes were made to attain easier problem creation. This list does not include minor bug fixes or any improvements that are invisible to users. #### Tables support when rendering statements in HTML Now it's possible to insert the most basic tables in your HTML statements. For example, you can show the scoring system of your problem or insert several images side by side. Only column text alignment and border specification are supported now. <img src="/predownloaded/4a/4a/4a4a6c726e96df40929803a1276a448947d6ebed.png" style="width: 800px; margin-left: auto; margin-right: auto; display: block"/> #### A brief manual for writing statements We bet a lot of users who wrote statements were confused by the fact ...
solution type 'Do not run' for outdated solutions. It can't be selected in invocations and won't be

Full text and comments »

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

128.
By pani.natalia, 6 years ago, In English
700 contests. ruban's interview Please meet my today's guest Anatoly [user:ruban,2021-05-17], PhD in Physics and Mathematics, who yesterday participated in his 700th contest on Codeforces. ![ ](/predownloaded/7c/d8/7cd88780306e8b25e1ac72a6e7b5b2b47914f0d0.jpg) [cut] _._ _-Hello Anatoly_ -Hello Natalia _-Were you surprised by my message that you had taken more contests on Codeforces than anybody else?_ -No, I wasn’t. I knew it for sure. There have been only several occasions when I missed rounds because of high rating, I think, not many than 20-30. _-Do you feel something special about contests with the round number like 500th, 600th or this one 700th?_ -No, I wouldn't pay any attention if there were no interview. _-How did you start on Codeforces?_ -Since 2001 (long before Codeforces) I have coached the competitive programming team of [SibSUTIS](https://sibsutis.ru/en/) &mdash; Siberian State University of Telecommunications and Information Science and created problems for All...
_-What type of contest problems do you like more?_ -My favorite topics are geometry, physics and

Full text and comments »

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

129.
By panipuri8, history, 8 years ago, In English
Presenting to you the biggest cheat on Codeforces! Hello all, I was recently intrigued by this account &mdash; [user:Ali_Pi,2018-08-02] because of the notorious similarity of username with this account &mdash; [user:Ali.Pi,2018-08-02].. A short note on [user:Ali.Pi,2018-08-02] &mdash; he has copy pasted thousands of problems' codes in the practice section, and climbed to the top of standings page [ [LINK](http://codeforces.me/problemset/standings) ] sometime last year. He had even beat the chinese bots to climb to the top! Talk about being jobless. He used to do virtual contests on every random contest &mdash; and copy past every problem's code and be #1 when you open the standing page. For what joy? We will have to ask him for the answer. Coming back to the [user:Ali_Pi,2018-08-02] account &mdash; his recent contest on CF &mdash; Codeforces Round #500 (Div. 1) based on EJOI &mdash; he had solved three problems &mdash; [ [Submission for problem A](http://codeforces.me/contest/1012/submission/40945262) ] [ [Submission for...

Full text and comments »

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

130.
By MohammadParsaElahimanesh, 4 years ago, In English
Codeforces Global Round 23 Editorial Hi Codeforces, I've tried my best to make a different editorial, I wish you enjoy it ... [problem:1746A] problem author: [user:MohammadParsaElahimanesh,2022-10-15], [user:AmirrzwM,2022-10-15] <spoiler summary="step by step solution"> step 1: It's obvious that the answer is "NO" if $a_{i} = 0$ for all $1 \le i \le n$. step 2: Lets prove that the answer is "YES" if $a_{i} = 1$ for at least one $1 \le i \le n$. step 3: If size of $a$ is equal to $k$, just use second type operation once and we are done. step 4: Otherwise (if $|a| > k$), there will be three cases: (assume that $a_{j} = 1$) - if $j > 2$, you can use first type operation on first and second element and decrease size of $a$ by 1. - else if $j < |a|-1$, you can use first type operation on last and second to last element and decrease size of $a$ by 1. - else, it can be shown easily that $|a| = 3$ and $k = 2$ so you can use second type operation twice and turn $a$ into a single $1$. In ...
- Increase the usefulness of all tasks of the first type by $x$, the second type ~--- by $y$, and

Full text and comments »

131.
By AlFlen, 5 years ago, translation, In English
Codeforces Round #750 (Div.2) Editorial [problem:1582A] Idea: [user:74TrAkToR,2021-10-24] <spoiler summary="Tutorial"> [tutorial:1582A] </spoiler> <spoiler summary="Solution (74TrAkToR)"> ~~~ #include<bits/stdc++.h> using namespace std; main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t, a, b, c; cin >> t; while (t--) { cin >> a >> b >> c; cout << (a + c) % 2 << '\n'; } return 0; } ~~~ </spoiler> [problem:1582B] Idea: [user:AlFlen,2021-10-24] <spoiler summary="Tutorial"> [tutorial:1582B] </spoiler> <spoiler summary="Solution (74TrAkToR)"> ~~~ #include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t, n, x; cin >> t; while (t--) { cin >> n; int cnt0 = 0, cnt1 = 0; for (int i = 1; i <= n; ++i) { cin >> x; if (x == 0) cnt0++; ...
char type; for (int i = 1; i <= n; ++i) { cin >> type; if (type == '*') add

Full text and comments »

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

132.
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_...
#define vv(type,name,n,...) \ vector<type>> name(n,vector<type>(__VA_ARGS__)) #define

Full text and comments »

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

133.
By unreal.eugene, 5 years ago, In English
Polygon's New Feature: Resolving Conflicts (finally!) Hello Codeforces! I and [user:DK318,2021-07-09], as students of ITMO University, joined the Codeforces team in June. Last month we mainly dealt with the development of the Polygon platform and were focused on one significant feature lots of people dreamed of. Have you ever made some changes to the problem, and at the same time another person changed the same file? I believe most of you did and disliked this situation. If you wanted to resolve the conflict, you needed to download an archive containing all your changes and repeat them all in the newest revision of the problem. This was very confusing and time-consuming, wasn't it? And now we present probably the most anticipated feature of Polygon since its creation: **a web interface for resolving conflicts**. [cut]<br> When the conflict occurs, the link 'Resolve Conflicts' will appear on the sidebar accessing the page, where you can merge different versions. If it is impossible to load into the problem, the same button will...
it. This type of conflict may potentially affect the whole repository, so the only solution to this

Full text and comments »

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

134.
By bitset, 3 years ago, In English
[Bugged] Dynamic Bitsets in GCC **UPD1: The bug has been [fixed](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115399). I'll update the blog again when the fix is on Codeforces.** **UPD: Unfortunately, left / right shift is bugged and doesn't clear bits [properly](https://codeforces.me/blog/entry/129454?#comment-1157481). It should be fine for other operations, but use it at your own risk.** <spoiler summary="Original Blog"> Hello sirs, you might know that Boost has a dynamically sized bitset class, but did you know that GCC also has one? Turns out it's included in the tr2 folder. You can simply include the `<tr2/dynamic_bitset>` header, and use it as `std::tr2::dynamic_bitset`. **Yes, it works on Codeforces.** Here's a code example to count triangles in a graph ([abc258_g](https://atcoder.jp/contests/abc258/tasks/abc258_g)): <spoiler summary="Code"> ```cpp #include <bits/stdc++.h> I wonder if it's possible to get GCC to fix it... using namespace std; #include <tr2/dynamic_bitset> using namespa...
specify the word type and allocator as template arguments.

Full text and comments »

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

135.
By defnotmee, 2 years ago, In English
Catching the Mole (Psychotic_D cheating accusation) Hello codeforces! You guys must have seen the recent blog accusing international master [user:Psychotic_D,2024-07-23] of cheating in the most recent div2 round: [Codeforces Round 960 (Div. 2)](https://codeforces.me/contest/1990). This is due to the fact that the author, [user:wuhudsm,2024-07-23] is [user:Psychotic_D,2024-07-23]'s friend and that [user:Psychotic_D,2024-07-23] had a ridiculous performance, winning the amongst official participants. ![ ](https://i.imgur.com/tLslIlv.png) They are both big members of [TheForces](https://theforces.netlify.app/), raising suspicions of whether there was some collusions between the two. At first i thought it was nonsense since the evidence was lacking, but after a bit of my own investigation I've compiled the most interesting pieces of evidence of why i believe [user:Psychotic_D,2024-07-23] (along with some accomplices from TheForces) is in fact a cheater. Case #1: Introduction ------------------ I first learned about the sub...
] was probably too scared of causing some type of issue by changing that constant, not knowing why

Full text and comments »

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

136.
By Franklyn_W, history, 5 years ago, In English
When Dreams Come True: The only solve on N at ICPC WF 2020. _Addendum: This is mostly about the story behind our solution to N. To see more about the math, see [here](https://codeforces.me/blog/ekzhang)_ When I was younger, fairytales always captivated me, with their nice and clean stories. All through my life I've liked the idea of having a fairytale ending to a life arc, but I was frequently disappointed. Many times after an unsuccessful experience, one simply gets more unsucessful experiences and then time runs out... At ICPC recently, I was lucky enough to finally attain my fairytale ending to my competitive programming career. I figured I would tell the fairytale, to close a career that started about 6 years ago. On my World Finals team, my role is to help the team get hard math problems, as I haven't actively processed algorithms in years. So imagine my delight when my teammate ([user:ekzhang,2021-10-06]) points out that problem N reduces to finding a vector so that the (l2)-norm of x is r, and $Ax = b$ for a matrix $A$ and vect...

Full text and comments »

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

137.
By purplesyringa, history, 2 years ago, In English
AI might erase CP, but not us I haven't slept for 20 hours and I can't fall asleep. I've been reading others' topics on AI, and I had a sort of epiphany. These ideas have been brewing inside me for many years, and I thought it might be time to share them with the community. --- There were times when I was a "competitive programmer" at the core. I spent many years doing that exclusively. I've never been to IOI, but I like to think that I've reached some good heights. Two years ago, I stopped writing online competitions. I've written a few offline competitions after that, but eventually, I decided to stop that too. Yet somehow Codeforces still attracts me. I don't want to solve problems, but I keep typing codeforces.com into the address bar. *Why?* Just yesterday, I didn't have an answer. --- Imagine a layperson asking you what competitive programming is. What are you going to say? My answer has always been "Oh, we solve interesting algorithmic problems with time constraints and other limits". Many ...

Full text and comments »

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

138.
By sum, history, 3 years ago, In English
Editorial for Codeforces Round #919 (Div. 2) ##Information about the round <spoiler summary="Rating predictions (inspired by BucketPotato's editorial)"> | Person | A | B | C | D | E | F1 | F2 | |--------------------------------------------|------|------|------|------|------|------|------| | [user:sum,2024-01-13] | 800 | 1300 | 1500 | 1900 | 2000 | 2200 | 2900 | | [user:oursaco,2024-01-13] | 800 | 1100 | 1300 | 1600 | 1800 | 2100 | 3100 | | [user:omeganot,2024-01-13] | 900 | 1000 | 1400 | 1700 | 1900 | 2200 | 2800 | | [user:sriniv,2024-01-13] | | | | 1900 | 2000 | 1900 | | | [user:apple_method,2024-01-13] | 1000 | 1200 | 1400 | 1900 | 1600 | | | | [user:awesomeguy856,2024-01-13] | 800 | 1100 | 1400 | 1800 | 1900 | 2000 | 2800 | | [user:nonrice,2024-01-13] | 900 | 1000 | 1400 | 1750 | | | | | [user:null_aw...
Notice that after $\log{(\max{k})}$ operations of the second type, the, ```cpp #include

Full text and comments »

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

139.
By galen_colin, 3 years ago, In English
WF23 Luxor _(Long blog ahead. Reader discretion advised.)_ I feel we have a rather interesting WF story (note: we did the 47th finals, as the University of Maryland, <b><i>as 2 people</i></b>... explained below), so I figured I'd tell it. Exposition ---------- It actually starts way before WF, too. Our teams were decided on (some form of) merit based on an internal qualifier. My team for the regional and NAC (North America superregional) ended up as {me, [user:Navick,2024-04-24], [user:mr.banana,2024-04-24]}. We did [fairly](https://nasouth22d1.kattis.com/contests/nasouth22d1/standings) [well](https://nac.icpc.global/wp-content/uploads/2023/06/NAC23-scoreboard.pdf) in those. However, for WF, my two teammates only had single-entry visas for the US, meaning that if they left, they couldn't come back into our country. So they couldn't really go with me... Luckily, in such situations, ICPC lets you just replace your teammates. So we held another internal qualifier, and ended up with two ...

Full text and comments »

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

140.
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...
first type of operation to put the divider wherever we want. Then, using the secondtype of operation

Full text and comments »

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

141.
By Golovanov399, 5 years ago, In English
A tool for testing interactive problems Hello, codeforces! I have created a tool for testing interactive problems. If you do not know what it is, I recommend you to read [Interactive Problems Guide](https://codeforces.me/blog/entry/45307) before/instead of reading this blog. It is important to understand that this tool does **not** help, in any way, to solve interactive (and all other types of) problems, where by "solve" I mean "come up with the solution". Today's June Lunchtime introduced an interactive problem called [XOR, The Detective](https://www.codechef.com/LTIME109A/problems/XORDETECTIVE), where I used my tool and it helped me to debug my solution, so I would like to use this chance to show the tool in work. With all of this out of the way, let's begin. Debugging interactive solutions in general ================== I can't say about everyone, but for me personally debugging a solution to an interactive problem is much harder than to a non-interactive one. First of all, basic testing on samples is already no...
); } ++q; while (q--) { string type; cin >> type; if (type == "?") { int x = nxt

Full text and comments »

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

142.
By dannyboy20031204, history, 5 years ago, In English
Codeforces Round #772 Editorial [problem:1635A] <spoiler summary="Tutorial"> [tutorial:1635A] </spoiler> <spoiler summary="Solution"> ``` #include <bits/stdc++.h> using namespace std; int main () { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; int ans = 0; for (int i = 0, x; i < n; ++i) { cin >> x; ans |= x; } cout << ans << endl; } } ``` </spoiler> [problem:1635B] <spoiler summary="Tutorial"> [tutorial:1635B] </spoiler> <spoiler summary="Solution"> ``` #include <bits/stdc++.h> using namespace std; int main () { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector <int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int ans = 0; for (int i = 1; i + 1 < n; ++i) { if (a[i] > a[i -...
struct edge { int type, u, v; };

Full text and comments »

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

143.
By Vladithur, history, 5 years ago, In English
Editorial of Codeforces Round #769 You can also find video editorials for problems B-D on [user:ak2006,2022-01-30]'s [Youtube channel](https://www.youtube.com/channel/UCnZ5rC2_JY0EuYMGMiAbISg)! ####[1632A &mdash; ABC](https://codeforces.me/contest/1632/problem/A) <spoiler summary="Hint 1">Only a few strings have the answer "YES".</spoiler> <spoiler summary="Hint 2"> For $n \ge 3$, the answer is "NO". </spoiler> <spoiler summary="Solution"> Let $n \ge 3$ and the resulting string be $a$. For there to be no palindromes of length greater than $1$, at least all of these inequalities must be true: $a_1 \neq a_2$, $a_2 \neq a_3$, and $a_1 \neq a_3$. Since our string is binary, this is impossible, so the answer is "NO". For $n \le 2$, there are 4 strings that have the answer "YES": $0$, $1$, $01$, and $10$; as well as 2 strings that have the answer "NO": $00$ and $11$. Time complexity: $O(n)$ </spoiler> <spoiler summary="Solution codes"> - [C++ code](https://codeforces.me/problemset/submission/1632...
It is optimal to add edges of type $(1, v)$.

Full text and comments »

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

144.
By Kostroma, 8 years ago, In English
AIM Tech Round 5 Editorial Thanks [user:bmerry,2018-08-28] for posting his solutions, we gently took some of them as a base for editorial. [tutorial: 1028A] Problem author: [user:VadymKa,2018-08-28] Problem developers: [user:AlexDmitriev,2018-08-28], [user:malcolm,2018-08-28] <spoiler summary="Code"> ~~~~~ static class SquareInside { final int inf = (int) 1e9; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(), m = in.readInt(); char[][] s = new char[n][]; for (int i = 0; i < n; i++) { s[i] = in.readWord().toCharArray(); } int minX = inf, maxX = -inf, minY = inf, maxY = -inf; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (s[i][j] == 'B') { minX = Math.min(minX, i); minY = Math.min(minY, j); maxX = Math.max(maxX, i); ...
struct Query { Type type; Point pt; int dist_id; void scan() { int type1; cin

Full text and comments »

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

145.
By Al.Cash, 10 years ago, In English
Geometry: 2D points and lines [Tutorial] I get an impression that a lot of coders struggle with geometric problems and prefer to avoid them. That's not much of a surprise, considering that I couldn't find a good writing explaining the basics and giving useful advice how to proceed. Moreover, some resources obfuscate this beautiful area to the point it's despised by the readers. I'll try to change that, but first I'll mention some of the better resources: [geomalgorithms.com](http://geomalgorithms.com/points_and_vectors.html) This is where you can start if you don't have a basic notion of a vector. Also there are more detailed explanations for some examples I'll list, but I dislike the implementations. [This post in Russian](http://codeforces.me/blog/entry/6642) has a link to the code that's most similar to mine, with some comments (unfortunately, also is Russian)[cut]. ### Point structure and operations Without further ado, I'll start with my code for the `Point` structure. Explanations are below, so don't rush t...
coordinates are integer, the output may be real. To enforce the correct type conversion, the output, ` and `y` with obvious meaning, some utility methods including type conversion and basic vector

Full text and comments »

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

146.
By RDDCCD, history, 4 years ago, In English
Editorial of CodeTON Round 4 (Div. 1 + Div. 2, Rated, Prizes!) [A. Beautiful Sequence](https://codeforces.me/contest/1810/problem/A) <spoiler summary="Hint"> What is the necessary and sufficient condition? </spoiler> <spoiler summary="Tutorial"> The necessary and sufficient condition for a beautiful sequence is that there exist one $i$, such that $a_{i} \le i$. Just check the sequence for the condition. </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int a[100005]; void solve() { int n; scanf("%d",&n); for(int i =1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= n;i++) { if(a[i] <= i) { puts("YES"); return; } } puts("NO"); } int main() { int t;scanf("%d",&t); while(t--) solve(); } ~~~~~ </spoiler> [B. Candies](https://codeforces.me/contest/1810/problem/B) <spoiler summary="Hint"> How the binary representation changes after an operation? </spoiler> <spoiler summary="Tutorial"...
Then, for each query of type $2$, we just calculate the number of days we need for $L_{min}$ and

Full text and comments »

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

147.
By zscoder, history, 10 years ago, In English
Tinkoff Challenge — Final Round Editorial <spoiler summary="Bank Robbery"> Author : [user:zscoder,2017-05-13] This is a simple implementation problem. We iterate through all banknotes one by one and check if Oleg can take each of them. If a banknote is at position $x$, then Oleg can take it if and only if $b < x < c$. This can be checked in $O(1)$ time. Thus, the total complexity is $O(n)$. Note that the information on the starting position of Oleg is useless here. <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define mp make_pair #define pb push_back #define fbo find_by_order #define ook order_of_key typedef long long ll; typedef pair<ll,ll> ii; typedef vector<ll> vi; typedef long double ld; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; typedef set<int>::iterator sit; typedef...
void dfs(int u, int p, bool type) { if(type) chain.pb(u); else chain.push_front(u); int c=0

Full text and comments »

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

148.
By TheScrasse, 12 months ago, In English
Codeforces Round 1066 (Div. 1 + Div. 2) Editorial [problem:2157A] Author: [user:TheScrasse,2025-11-22]<br> Preparation: [user:TheScrasse,2025-11-22] <spoiler summary="Hint 1"> Each value $x$ is independent of the others; only its own frequency matters. </spoiler> <spoiler summary="Hint 2"> In a balanced array, value $x$ must appear either $0$ times or **exactly** $x$ times. </spoiler> <spoiler summary="Solution"> - Each value $x$ is independent of the others; only its own frequency matters. In particular, for each value, find its frequency $f[x]$. - In a balanced array, value $x$ must appear either $0$ times or **exactly** $x$ times. Specifically, if it appears $< x$ times at the beginning, you have to delete all its occurrences, otherwise you should keep $x$ occurrences. Specifically, for each $x$, add $f[x]$ to the answer if $f[x] < x$, else add $f[x] - x$. Complexity: $O(n)$ time. Slower solutions (e.g., $O(n^2)$) are allowed. </spoiler> <spoiler summary = "Code"> [submission:350380351] </spoiler> [...

Full text and comments »

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

149.
By P_Nyagolov, history, 8 years ago, In English
Crazy Typer — Now Much Better Hello everybody, So 4 months ago I wrote a [blog](https://codeforces.me/blog/entry/61573) about an online game I created. The game was basically you trying to type words moving in linear trajectories on the screen with different speeds for one minute. Your score was, and still is, the number of characters in all words you managed to type correctly while still on the screen. A lot of time has passed, during which I have learned some more thing, and now I would like to introduce you to the new version of it. ![ ](http://store.picbg.net/pubpic/C0/63/deda9e7fbeafc063.png) The website address is the same &mdash; http://crazytyper.cf. The first thing you will be asked to do is to pick a nickname which you will be able to change at any moment by clicking on the "Edit nickname" label which will appear in the upper left corner. The game now has two modes &mdash; standard and survival. You will notice that I added leaderboards showing the top 5 results for the last 24 hours for each...
seconds and again try to type the words you see. For each word you type correctly, you get a 1-second, ; you try to type words for a minute and you get a score equal to the total number of characters in

Full text and comments »

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

150.
By AkiLotus, history, 8 years ago, In English
Codeforces Round #554 (Div. 2) Editorial [problem:1152A] ------------------ Author: [user:xuanquang1999,2019-04-24] Development: [user:xuanquang1999,2019-04-24], [user:Akikaze,2019-04-24], [user:GreenGrape,2019-04-24] Theme development: [user:Akikaze,2019-04-24], [user:GreenGrape,2019-04-24] Editorialist: [user:xuanquang1999,2019-04-24] <spoiler summary="Tutorial"> [tutorial:1152A] </spoiler> <spoiler summary="Solution (xuanquang1999)"> Submission link: [submission:53259456] <spoiler summary="Source code in plain text"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(int argc, char* argv[]) { int n, m; scanf("%d%d", &n, &m); vector<int> a(n), b(m); for(int i = 0; i < n; ++i) scanf("%d", &a[i]); for(int i = 0; i < m; ++i) scanf("%d", &b[i]); int c0 = 0, c1 = 0; for(int i = 0; i < n; ++i) if (a[i]%2 == 0) ++c0; else ++c1; int k0 = 0, k1 = 0; for(int i = 0; i < m; ++i...
RALL(data) data.rbegin(),data.rend() #define TYPEMAX(type) std::numeric_limits< type>::max

Full text and comments »

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

151.
By awoo, history, 4 years ago, translation, In English
Educational Codeforces Round 141 [Rated for Div. 2] Hello Codeforces! On [contest_time:1783] [contest:1783] will start. Series of Educational Rounds continue being held as [Harbour.Space University](https://harbour.space/) initiative! You can read the details about the cooperation between [Harbour.Space University](https://harbour.space/) and Codeforces in the <a href="http://codeforces.me/blog/entry/51208">blog post</a>. This round will be **rated for the participants with rating lower than 2100**. It will be held on extended ICPC rules. The penalty for each incorrect submission until the submission with a full solution is 10 minutes. After the end of the contest, you will have 12 hours to hack any solution you want. You will have access to copy any solution and test it locally. You will be given **6 or 7 problems** and **2 hours** to solve them. The problems were invented and prepared by Adilbek [user:adedalic,2023-01-07] Dalabaev, Vladimir [user:vovuh,2023-01-07] Petrov, Ivan [user:BledDest,2023-01-07] Androsov, Ma...

Full text and comments »

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

152.
By dreamoon_love_AA, 12 years ago, In English
Codeforces Round #292 Editorial Thanks to [user:johnathan79717,2015-03-10] fo polish my words. #### [515-A Drazil and Date](http://codeforces.me/problemset/problem/515/A) If Drazil chooses the shortest path from (0,0) to (a,b), it takes $|a| + |b|$ steps. So we know that all numbers less than $|a| + |b|$ are impossible to be the number of steps that Drazil took. Now consider when the number of steps is not less than $|a| + |b|$. When Drazil arrives at $(a,b)$, he can take two more steps such as $(a,b)$ -> $(a,b+1)$ -> $(a,b)$ to remain at the same position. So we know that for all $s$ such that $s \geq |a| + |b|$ and $(s - (|a| + |b|)) \% 2 = 0$, there exists a way for Drazil to get to $(a,b)$ in exactly $s$ steps. The last part we should prove is that it's impossible for Drazil to arrive at (a,b) in exactly $s$ steps when $(s - (|a| + |b|)) \% 2 = 1$. We can color all positions $(x,y)$ where $(x+y) \% 2 = 0$ as white and color other points as black. After each step, the color of the p...
1. Points connected by the second type of edges. 2. Points connected to important points in 1., by

Full text and comments »

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

153.
By Wandoka, history, 2 years ago, In English
How optimal is your CP setup? Click here and find it out! Recently I thought a lot about optimizing my setup. I don't think it is an important aspect of cp, as it barely affects the performance, but it is fun to think about nonetheless. In this blog, you will be able to determine whether you have an optimal setup or not. I will list the criteria and points you get for satisfying each one of them. In the end, I do the breakdown for different point ranges. I won't include things like **having a monitor** or **having an internet connection**, but I will be including basically everything else that comes to my mind. If you see something missing from the list, let me know in the comments, I will probably update my list then. This blog is mainly made for laughs, but if you are new, you will probably learn something new, even though **it won't help you to increase your rating**. ### You can compile and run your code. - $0$ points: I don't know how to run my code before submitting - $10$ points: I compile my code b...

Full text and comments »

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

154.
By AkiLotus, 8 years ago, In English
Codeforces Round #538 (Div. 2) Editorial *Model solutions are now available.* *[user:GreenGrape,2019-02-10] and I will write more about problem F, including an alternative data structures (still quite tight on time limit) ;)* [problem:1114A] ------------------ Author: [user:Akikaze,2019-02-10], [user:GreenGrape,2019-02-10] Development: [user:Akikaze,2019-02-10], [user:GreenGrape,2019-02-10], [user:neko_nyaa,2019-02-10] Editorialist: [user:Akikaze,2019-02-10] <spoiler summary="Tutorial"> First of all, we can see the grape preference is hierarchically inclusive: the grapes' types Andrew enjoys are some of those that Dmitry does, and Dmitry's favorites are included in Michal's. Let's distribute the grapes to satisfy Andrew first, then to Dmitry, then Michal. If any of the following criteria is not satisfied (which means one of our friends is not happy), then we can immediately say that no distributions are available: - Andrew must have at least $a$ green grapes. So we need, $x \le a$. - Dmitry can ha...
RALL(data) data.rbegin(),data.rend() #define TYPEMAX(type) std::numeric_limits< type>::max

Full text and comments »

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

155.
By orz, history, 3 years ago, In English
ICPC World Finals in Luxor & Upcoming Interview with Shayan Good evening everyone! TL;DR: I am in Luxor preparing for ICPC WF and making some photos, and also I was offered to (and I will) give an interview to [user:Shayan,2024-04-16], please send your questions. [cut]<div></div> [As you may know](https://codeforces.me/blog/entry/109940), in December 2022 I qualified for ICPC WF 2023 from St Petersburg State University, which (together with ICPC WF 2022) [takes place](https://docs.icpc.global/wf-schedule/) April 14-19, 2024 in Luxor. I've been in Luxor for three days now. Our team still experiences a little jet lag, which means that I sleep not only at night, but also for about three hours during the day. I hope it goes away soon. The community of programmers I interacted with five years ago is now scattered all over the world, but big onsite events like ICPC can bring us all together for a short while. So today I had the pleasure of meeting a bunch of wonderful people, but unfortunately I forgot to take photos with almost all o...
/XCOm7ZIU25k.jpg?size=2560x1920&quality=95&sign=464c9c171b4e5069fd10048f4609f46b& type=album) ![orz, /hJYOXsMCg4o.jpg?size=1620x2160&quality=95&sign=f817796689a80395bb0b5bb8223295fd& type=album) , =1280x720&quality=95&sign=cb699a82eb316ddea1a802ee138beaab&type=album), =1280x960&quality=95&sign=1b1c07af1e5b18ae14cd73c750926cdc&type=album), =1280x960&quality=95&sign=5be67505c23a616bc15805484a7ae731&type=album), =1280x960&quality=95&sign=65cd96093f2b64e056ab0d98348124ac&type=album), =1620x2160&quality=95&sign=1ae404324e668ba28209f6625a619f7f&type=album), =1620x2160&quality=95&sign=3d49c7132c80e4394b876cd9bc8e9d4d&type=album), =1620x2160&quality=95&sign=74a48c1d10a9287136de54c9dd965b54&type=album), =1620x2160&quality=95&sign=89310a6840df5f0bd62e5c0f83c69c38&type=album), =1620x2160&quality=95&sign=98ff7afa5c2136d147eb5e3754a68a43&type=album), =1620x2160&quality=95&sign=af244b280e34612be194249a65b37d7e&type=album), =1620x2160&quality=95&sign=b816691b9ca72fc02be91b7eeb7b5e94&type=album), =1620x2160&quality=95&sign=cdc531953eae1acb1b6534ac8525c4e7&type=album), =1620x2160&quality=95&sign=d6a449dd24731df0ba76ad18d0a5bbd2&type=album), =1620x2160&quality=95&sign=db7962c0df4f8f16f10c697fbc5da606&type=album), =1620x2160&quality=95&sign=e76c0e5101f7a846d623ff9f072c3b86&type=album), =960x1280&quality=95&sign=81c468bd03071b69c135dc6732601684&type=album), =960x1280&quality=95&sign=95c951b33f651c13ea13e00046438e91&type=album)

Full text and comments »

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

156.
By wuhudsm, history, 2 years ago, In English
Codeforces Round 960 (Div. 2) Editorial Thank you for participation and we hope you enjoy this round :) Additionally, we sincerely invite you to join the unofficial round of TheForces Community tomorrow. Compete alongside many high-rated participants and earn your own rating in a our own rating system([TheForces Rating System](https://theforces.netlify.app/ratings))! For more details, pls read https://codeforces.me/blog/entry/131733. #### [A &mdash; Submission Bait](https://codeforces.me/contest/1990/problem/A) <spoiler summary="hint1"> For Alice, what if choosing the maximum value doesn't work? </spoiler> <spoiler summary="hint2"> Consider parity. </spoiler> <spoiler summary="solution 1"> Case $1$: When all values appear an even number of times, Alice will lose. This is because no matter which number Alice chooses, Bob can mimic Alice's move. Case $2$: When at least one value appears an odd number of times, Alice will win. Alice only needs to choose the maximum value that appears an odd number ...
#define vv(type,name,n,...) \ vector<type>> name(n,vector<type>(__VA_ARGS__)) #define

Full text and comments »

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

157.
By dolphingarlic, history, 6 years ago, In English
What to do at the IOI after you (inevitably) solve everything With IOI just around the corner, [some](https://codeforces.me/profile/tmwilliamlin168) [of](https://codeforces.me/profile/300iq) [you](https://codeforces.me/profile/saba2000) may be wondering: **"what should I do after I AK after 3 hours?"** In this post, I'll share some activities that you can do to pass the time! (Note that some of these may not be applicable for an online IOI) ## Level 1 &mdash; Built-in software on your computer The most obvious thing you can do is use the built-in stuff. I'm talking about playing Minesweeper, reading the C++ documentation, or anything similar. While Minesweeper is quite fun and the C++ documentation is... interesting, Minesweeper quickly becomes boring and you'll look like a huge nerd if you read the documentation (and you don't want that, do you?) That's why I'll only recommend this if you're a noob and only AK in 4 hours. ## Level 2 &mdash; Creating software So you've beaten Minesweeper 10 times already and read throug...

Full text and comments »

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

158.
By awoo, history, 3 years ago, translation, In English
Educational Codeforces Round 161 Editorial [problem:1922A] Idea: [user:Roms,2024-01-19] <spoiler summary="Tutorial"> [tutorial:1922A] </spoiler> <spoiler summary="Solution (awoo)"> ~~~~~ for _ in range(int(input())): n = int(input()) a = input() b = input() c = input() print("YES" if any([a[i] != c[i] and b[i] != c[i] for i in range(n)]) else "NO") ~~~~~ </spoiler> [problem:1922B] Idea: [user:Roms,2024-01-19] <spoiler summary="Tutorial"> [tutorial:1922B] </spoiler> <spoiler summary="Solution (Roms)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int t; int main() { cin >> t; for (int tc = 0; tc < t; ++tc) { int n; cin >> n; map<int, int> numOfLens; for (int i = 0; i < n; ++i){ int x; cin >> x; ++numOfLens[x]; } long long res = 0; int sum = 0; for (auto it : numOfLens) { long long cnt = it.second; if(cnt >= 3) ...
vector l(n), r(n); for (int i = 1; i < n; ++i) r[i] = r[i - 1] + (type

Full text and comments »

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

159.
By dXqwq, 18 months ago, In English
The 7th Turing Cup Tournament # 2025 · The 7th Turing Cup Tournament The Turing Cup is an invitational competition that is organized by one of the most successful informatics competition teams in China, the XinYouDui and partner with X-Camp Academy. ## Timeline | Event | Time (UTC+8) | |----------------------|-----------------------------------------| | Registration Time | May 06, 2025, 06:00 PM &mdash; May 25, 2025, 12:29 PM | | Opening Ceremony | May 25, 2025, 07:50 AM &mdash; 08:30 AM | | Contest Time | May 25, 2025, 08:30 AM &mdash; 12:30 PM | --- ## Contest Details ### Staff - Writers: [user:dXqwq,2025-05-22], [user:Flamire,2025-05-22], [user:myee,2025-05-22], [user:orzdevinwang,2025-05-22], [user:zhaohaikun,2025-05-22] - Testers: [user:dspt,2025-05-22], [user:emptyhope,2025-05-22], [user:jqdai0815,2025-05-22], [user:Kubic,2025-05-22], [user:le0n,2025-05-22], [user:zhaohiakun,2025-05-22] ### Features - **High Contest Q...
### Contest Format - **Type**: Online - **Time**: - BJT: May 25, 8:30 AM — 12:30 PM

Full text and comments »

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

160.
By Gellyfish, 18 months ago, In English
Codeforces Round 1028 (Div.1, Div.2) Editorial You could tell people didn't seem to like the match very much. I'm sorry I screwed up again ¯\\_(ツ)_/¯ If you're interested, I'd like to share some thoughts I have about this contest. <spoiler summary="sad story"> This time I've been trying my best to make the problems use more varied algorithms instead of just dp problems, but sadly [problem:2115C] was much harder than expected. But it seems like people are complaining more about the narrow time limit, centered on [problem:2116C] and [problem:2115C]. No one realized this before the contest, because none of the tester's code is get TLE except the wrong time complexity. I actually don't see a problem with the Time Limit of [problem:2116C]. Some of you may be puzzled, but let me try to explain this: - The intended solution is $O(\sum n \max(a) + \max(a)^2)$ and does not contain $\log \max(a)$. Computing $\gcd(x, y)$ is not $O(1)$, if you don't preprocess, then it's not unusual to actually get a TLE. - I believe the v...
- Type 1 and 2 operations can be handled directly by pushing into the appropriate segment’s queue, 1. Type 1 (Insert): We split the balanced tree into two parts. Let the root of the first part

Full text and comments »

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

161.
By adamant, 13 years ago, translation, In English
C++ STL: Policy based data structures Hi everyone! After a relatively long lull, I decided that <s>my contribution growing too slowly</s> the hour has come to please you with another article in the blog _:)_ 2 months ago user [user:Perlik,2014-03-19] wrote an [article] (/blog/entry/10355), in which he described a very interesting STL implemented data structure that allows you to quickly perform various operations with substrings. Some time after I tested it on various tasks and, unfortunately, tend to get a negative result &mdash; rope was too slow, especially when it came to working with individual elements. For some time, I forgot about that article. Increasingly, however, I was faced with problems in which it was necessary to implement set with the ability to know ordinal number of item and also to get item by its ordinal number (ie, order statistic in the set). And then I remembered that in the comments to that article, someone mentioned about the mysterious data structure order statistics tree, which supports th...
can be `set`, for this you just need to specify the second argument template type as `null_type` ( in, ~~~~~ template< typename Key, // Key type typename Mapped, // Mapped-policy

Full text and comments »

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

162.
By soullless, history, 20 months ago, translation, In English
Mass cheating using AI My friend [user:away_in_the_heavens,2025-03-29] sent me a screenshot that left me completely shocked. I have never seen anything like this on the platform before: ![ ](https://ltdfoto.ru/images/2025/03/29/asdasdasd.jpg) The image shows the standings of today’s round. For comparison, here's what standings typically looked like across 100 previous contests: ![ ](https://ltdfoto.ru/images/2025/03/29/tgtgtt.png) Of course, incidents of unfair play have happened before. However, judging by today’s round, the number of cheaters has increased **tenfold, if not a hundredfold**. And the reason is clear — the appearance of tools like ChatGPT o1 or ChatGPT mini-high-3, which are apparently capable of solving problems up to ~3000 rating in just a few minutes. As a result, the round turns into a minigame for cheaters: who can type faster or debug ChatGPT's solution more efficiently. In my opinion, the current state of affairs calls for action. Perhaps it's time to reconside...
As a result, the round turns into a minigame for cheaters: who can type faster or debug ChatGPT's

Full text and comments »

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

163.
By TheScrasse, history, 2 years ago, In English
Editorial of Codeforces Round 975 (Div. 1, Div. 2) All the Polygon materials (including the official implementations of all the problems) are [here](https://drive.google.com/file/d/1zWk5N_iF3TWbzzab5IAIza78_FohSZtP/view?usp=sharing). [problem:2019A] Author: [user:TheScrasse,2024-09-27]<br> Preparation: [user:TheScrasse,2024-09-27] <spoiler summary="Hint 1"> Can you reach the score $\max(a) + \lceil n/2 \rceil$? </spoiler> <spoiler summary="Hint 2"> Can you reach the score $\max(a) + \lceil n/2 \rceil - 1$? </spoiler> <spoiler summary="Solution"> The maximum red element is $\leq \max(a)$, and the maximum number of red elements is $\lceil n/2 \rceil$. Can you reach the score $\max(a) + \lceil n/2 \rceil$? - If $n$ is even, you always can, by either choosing all the elements in even positions or all the elements in odd positions (at least one of these choices contains $\max(a)$). - If $n$ is odd, you can if and only if there is one occurrence of $\max(a)$ in an odd position. Otherwise, you can choose even position...
most $1$ card of each type, so there are at most $m/s$ cards of each type in total. - If the two

Full text and comments »

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

164.
By maomao90, 4 years ago, In English
[Tutorial] Intuition on Slope Trick # Introduction As mentioned in my previous blog, I will be writing a tutorial about slope trick. Since there are already many blogs that goes through the concept of slope trick, my blog will focus more on the intuition behind coming up with the slope trick algorithm. Hence, if you do not know slope trick yet, I suggest that you read other slope trick blogs such as https://codeforces.me/blog/entry/47821 and https://codeforces.me/blog/entry/77298 before reading my blog. In the future explanation on the example problems, I will assume that the reader already knows the big idea behind slope trick but do not know how to motivate the solution. Great thanks to [user:errorgorn,2022-06-25] for proofreading and writing the section on convex convolution and merchant otter. # When to use slope trick? Most of the time, slope trick can be used to optimise dp functions in the form of $dp_{i, j} = \min(dp_{i - 1, j - 1}, dp_{i - 1, j} + A_i)$ or dp functions containing costs with abs...
However, there is another type of slope trick where instead of storing points where the gradient of

Full text and comments »

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

165.
By Qwerty1232, 19 months ago, In English
Making NTT convolution 10x faster with avx2 > Text is also available on [github pages](https://piskareviv.github.io/blog_aux_ntt_1/) (formatting may look a bit cleaner there) > Thanks [user:alexxela12345,2025-05-05] for reviewing this blog Hello everyone! I want to share some of my thoughts and experiments on vectorizing NTT. I prefer NTT to real-valued FFT because of the imprecision of the latter. I use `avx2` because it is the most advanced vector extension supported by the majority of modern online judges (including Codeforces), as of 2024. And I have no idea how many bugs (already found two) and how much UB my code contains, at least it passes some kind of tests. ### Benchmark info All the benchmarks are performed on my `Ubuntu 22` `Intel i5-1135g7` laptop. I execute `cpupower frequency-set -d 3.0ghz -u 3.0ghz` before benchmarks to (attempt to) fix CPU frequency for better accuracy. Code is available at [github](https://github.com/piskareviv/blog_aux_ntt_1). You can try running all the benchmarks o...
= _mm256_mul_epu32(a_sh, b_sh); return reduce(x0246, x1357); } ``` (type casts are omitted)

Full text and comments »

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

166.
By orz, history, 5 years ago, translation, In English
Fast modular multiplication Consider the following problem: given three integers $x$, $y$ и $m$, $0 \leqslant x,y < m < 2^{32}$, calculate $xy\bmod m$. The easy way is just to multiply these numbers and apply the modulo operation: ~~~~~ uint32_t prod(const uint32_t x, const uint32_t y, const uint32_t m) { return x * y % m; } ~~~~~ As you might have guessed, this solution is wrong. The thing is that an overflow is possible in such a procedure: the operation `x * y` is performed in the type` uint32_t`, and in fact the intermediate result of this operation will not be $xy$, but $xy\bmod2^{32}$. If after that we take the result modulo $m$, it may differ from the correct one: $$ \left(xy\bmod2^{32}\right)\bmod m\ne xy\bmod m. $$ The way out is simple — you need to multiply in a larger type: ~~~~~ uint64_t prod_uint64(const uint64_t x, const uint64_t y, const uint64_t m) { return x * y % m; } ~~~~~ If you do this, then, since $xy<2^{64}$, this product will definitely not overflow, and after tak...
possible in such a procedure: the operation `x * y` is performed in the type` uint32_t`, and in fact the

Full text and comments »

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

167.
By MikeMirzayanov, 8 years ago, translation, In English
Codeforces and Polygon: Improvements [March 2019] Hi Codeforces! Here are some recent improvements here and in Polygon. ### Weak and Leaked Passwords We often hear about password leaks from various services. Considering that having common passwords is a common (but insecure) practice, we've improved Codeforces and Polygon to identify weak or leaked passwords. If on the top of the website you see a message that your password is not secure, then just change it immediately. ### Type of the round when creating a contest proposal This item improves our work with the writers. When creating a contest proposal, please indicate the type of a round. Leave the field empty only if you don't know the type of the round (it is strange). ### Calendar We've fixed errors when synchronizing official Codeforces rounds with [the calendar](/calendar). Now everything should be correct. ### I trust this user Currently, Codeforces provides a mature infrastructure for organizing contests, olympiads and trainings. With the help of ...
### Type of the round when creating a contest proposal, type of a round. Leave the field empty only if you don't know the type of the round (it is strange).

Full text and comments »

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

168.
By KAN, 10 years ago, In English
Codeforces Round #397 by Kaspersky Lab and Barcelona Bootcamp (Div. 1 + Div. 2 combined) Hi Codeforces! The [contest:765] is going to be held [tomorrow at 8:05 UTC](https://www.timeanddate.com/worldclock/fixedtime.html?msg=Codeforces+Round+%23397+by+Kaspersky+Lab+and+Barcelona+Bootcamp&iso=20170214T1105&p1=166)! This round is organized in collaboration with [Hello Barcelona ACM ICPC Bootcamp 2017](http://in.harbour.space/icpc/) and supported by Kaspersky Lab. <center> <img src="http://d9hhrg4mnvzow.cloudfront.net/in.harbour.space/icpc/085e8ffa-hellobcn-logoonly-200_02r02r02r02r000000.png"> <img src="http://d9hhrg4mnvzow.cloudfront.net/in.harbour.space/icpc/4c9339cb-kaspersky-lab-logo-svg_05k01905k019000000.png"> </center> Over 100 students from 17 countries and more than 25 universities such as Cornell University, University College London, École Normale Supérieure, University of Tokyo, Saint-Petersburg State University and Moscow Institute of Physics and Technology gathered in Barcelona to train together for the ACM ICPC Finals. For eight days students...
.1856150424643276.1073741834.1558338911091097&type=1&l=c6353c3838) and [here](https://www.facebook.com/media/set/?set=a

Full text and comments »

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

169.
By adamant, 5 months ago, In English
OCPC 2026 Summer Hi everyone! <center><a href="https://ocpc.camp"><img src="https://ocpc.camp/images/ocpc_light.svg?nocache" height="80px"></a> <a href="https://icpc.foundation/"><img src="https://ocpc.camp/images/ICPC.svg?nocache" height="80px"></a></center> The [OCPC](https://ocpc.camp/) (Osijek Competitive Programming Camp), an [award-winning](https://www.linkedin.com/feed/update/urn:li:activity:7368330111089131522/) camp for university students preparing for ICPC and other coding competitions, is back this **Summer 2026** — this time with **two onsite editions**: - **Hong Kong** — **8–16 August 2026**, hosted at the City University of Hong Kong. - **Iași, Romania** — **12–20 September 2026**, hosted at Alexandru Ioan Cuza University of Iași. Both editions are organized by us together with local hosts at each site, and use the **same contest set** — so you take part in **one** of them. As a rough guide, the **Iași** edition is most convenient for teams based in Europe, and **Hong Kong*...

Full text and comments »

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

170.
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...

Full text and comments »

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

171.
By Errichto, 10 years ago, In English
Codeforces Round #356 — Editorial # [problem:680A] Iterate over all pairs and triples of numbers, and for each of them check if all two/three numbers are equal. If yes then consider the sum of remaining numbers as the answer (the final answer will be the minimum of considered sums). Below you can see two ways to implement the solution. <spoiler summary="code1"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t[5]; int s = 0; for(int i = 0; i < 5; ++i) { scanf("%d", &t[i]); s += t[i]; } int best = s; // discard 2 cards for(int a = 0; a < 5; ++a) for(int b = a + 1; b < 5; ++b) if(t[a] == t[b]) best = min(best, s - 2 * t[a]); // or discard 3 cards for(int a = 0; a < 5; ++a) for(int b = a + 1; b < 5; ++b) for(int c = b + 1; c < 5; ++c) if(t[a] == t[b] && t[a] == t[c]) best = min(best, s - 3 * t[a]); printf("%d\n", best); return 0; } ~~~~~ </spoiler> <spoiler summary=...
type) { vector w; for(int x = (pot + i) / 2; x >= 1; x /= 2) w.push_back(x); reverse

Full text and comments »

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

172.
By Nickolas, 7 years ago, In English
Announcement: Microsoft Q# Coding Contest – Summer 2020 Microsoft's Quantum team is excited to announce the Q# Coding Contest – Summer 2020, the third in the series of Q# contests! In this contest you can put your quantum programming skills to the test, solving quantum computing tasks in Q#. The winners (as well as some lucky participants) will receive a Microsoft Quantum T-shirt! Quantum computing is a radically different computing paradigm compared to classical computing. Indeed, it is so different that some tasks that are believed to be classically intractable (such as factoring integers or simulating physical systems) can be performed efficiently on a quantum computer. In December 2017 Microsoft introduced the [Quantum Development Kit](https://docs.microsoft.com/quantum) which includes the Q# programming language. In summer of 2018 we hosted the [first quantum programming contest](https://codeforces.me/blog/entry/60209), which included problems on introductory topics in quantum computing: superposition, measurement, quantum oracl...

Full text and comments »

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

173.
By installb, history, 14 months ago, In English
Codeforces Round 1048 (Div. 1, Div. 2) Editorial [2139A &mdash; Maple and Multiplication](https://codeforces.me/contest/2139/problem/A) Idea: [user:installb,2025-09-08] Preparation: [user:installb,2025-09-08],[user:2014CAIS01,2025-09-08] <spoiler summary="Solution"> If $a=b$ we need $0$ steps. If $a$ can be divided by $b$, we only need $1$ step, which is to multiply $b$ by $\frac{a}{b}$. Same for the case when $b$ can be divided by $a$. Otherwise, we need at most $2$ steps. As both $a$ and $b$ are positive integers, we can first multiply $a$ by $b$ and then multiply $b$ by the original value of $a$. Both number will be equal to $a\times b$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; int solve(){ int a,b; cin >> a >> b; if(a == b) return 0; if(a % b == 0 || b % a == 0) return 1; return 2; } int main(){ ios::sync_with_stdio(false); int TC; cin >> TC; while(TC --){ cout <<...
After one operation of type $1$, Vanilla's number of cakes will definitely be at least half of the

Full text and comments »

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

174.
By PvPro, history, 4 months ago, In English
Randomized HLD : Smashing Growing Trees Online Hello Codeforces! A few months ago, I wrote a blog post about [Random heavy light decomposition](https://codeforces.me/blog/entry/151250). Today, I want to discuss a powerful extension of this idea. How do you usually solve problems where a tree grows online? That is, you process queries that attach a new vertex to the tree, while simultaneously answering queries on paths (e.g., finding the minimum on a path). Let's try to solve this using Heavy-Light Decomposition (HLD). ### The Flaw of Naive HLD At first glance, one might try a naive approach: when a new vertex is added, simply extend the existing HLD path into it. However, this creates a major vulnerability. Consider the following case: ![ ](/predownloaded/6a/5c/6a5c8984f327bc2a5710055cf6f289b80178e939.png) Imagine we repeatedly attach new vertices to form a long path. We extend the HLD path into each of them. But then, we attach a new vertex directly to the root, and subsequently attach all future vertice...

Full text and comments »

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

175.
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 ...

Full text and comments »

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