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

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

Results

1.
By Rhodoks, history, 4 years ago, In English
Codeforces Round #810 Editorial Sorry for the late editorial. May this editorial help you. If you have questions, feel free to ask. [problem:1711A] <spoiler summary="hint1."> The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). </spoiler> <spoiler summary="solution"> Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$. </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; } ~~~~~ </spoiler> [problem:1711B] <spoiler summary="hint1."> See the party as a graph. </spoiler> <spoiler summary="hint2."> Divide the vertices into two categories according to their degrees' parity. </spoiler> <spoiler summary="solution"> Let's consider ...
interval in the order of its length (small to large) and add the edge one by one. Initially, the

Full text and comments »

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

2.
By zscoder, history, 6 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...
assume the partition sets are labelled from $1$ to $k$. Then, $a_{i}$ denotes the size of the $i$-thset, in order. Adding them up, you get an “infinite polynomial” which somewhat encodes the sequence. The

Full text and comments »

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

3.
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...
ascending weight 2. Start with empty set $S$ 3. Iterate elements of ground set in sortedorder, at, elements of ground set in sorted order, at each step include current element into $S$ if it does not make

Full text and comments »

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

4.
By parveen1981, history, 5 years ago, In English
I compiled a list of almost all useful blogs ever published on Codeforces [update: till 09.06.2021] <h3 style="color:red">If there are any blogs that I have missed, please tell in the comment section. Thank you.</h3> # Mathematics Stuff - [Number Theory in Competitive Programming [Tutorial]](https://codeforces.me/blog/entry/46620) - [Number of points on Convex hull with lattice points](https://codeforces.me/blog/entry/62183) - [FFT, big modulos, precision errors.](https://codeforces.me/blog/entry/48465) - [Number of ways between two vertices](https://codeforces.me/blog/entry/19078) - [Mathematics For Competitive Programming](https://codeforces.me/blog/entry/76938) - [FFT and NTT](https://codeforces.me/blog/entry/19862) - [Burnside Lemma](https://codeforces.me/blog/entry/51272) - [Number of positive integral solutions of equation 1/x+1/y=1/n!](https://codeforces.me/blog/entry/76836) - [On burnside (again)](https://codeforces.me/blog/entry/64860) - [Simple but often unknown theorems/lemmas/formula? Do you know?](https://codeforces.me/blog/entry/55912) - [Probabili...
in O(log M) time](https://codeforces.me/blog/entry/90690) - [About ordered set ](https, linear function in O(log M) time](https://codeforces.me/blog/entry/90690) - [Aboutordered set](https

Full text and comments »

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

5.
By rng_58, history, 6 years ago, In English
AtCoder Library Recently, the number of algorithms and data structures we use in competitive programming are rapidly growing. It's a nice thing: by using more algorithms, the variety of possible problems gets wider, and we can enjoy more problems. On the other hand, before reaching adhoc, thinking-oriented part of this competition, we have to spend more and more time to learn algorithms. Sometimes a problem asks matching on general graphs; you have to find a paper describing it, read it, and implement its really complicated algorithm. Or sometimes you have to spend time tuning your library by a constant factor. Or sometimes you use multiple pre-written codes together, the variable names collide, and get annoyed. Until now, I basically rejected all problems that require pre-written codes of complicated algorithms because I don't like these things. For example, we never used segment trees with lazy propagation in our contests. However this way we can't use otherwise interesting problems and it ...
that solved this issue: C++ STL's set. It actually hides a monstrous data structure inside, but thanks

Full text and comments »

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

6.
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...
things I don't know about) and are not really sorted in any reasonable order. Let's begin. [cut], Of course, if you need to do something with the element, if it is present in the set (for example

Full text and comments »

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

7.
By scott_wu, history, 7 years ago, In English
New contest format?! Stream feat. tourist, Um_nik Hey all! We've created a new 1v1 programming contest format: **Lockout**. Like in most contests, each round has a set of problems and contestants work to solve them as quickly as they can. In Lockout, however, contestants compete head-to-head and only the first contestant to solve each problem gets the points. Contestants can work on problems in any order, so speed and strategy are crucial to avoid getting sniped! The head-to-head action also makes the contest much more exciting for viewers. We ran the first edition of Lockout at TCO Finals last month as a double-elimination bracket [tournament](https://challonge.com/lockout0). All of the finalists who were available competed (and even some of the problem writers) and we got to see a lot of exciting back-and-forth matches! As you can see though, there's still one set left to play. So we'll be streaming **Grand Finals of Lockout 0 featuring [user:tourist,2019-12-28] vs. [user:Um_nik,2019-12-28]** at [9:30 AM PST](https://www.timea...
has a set of problems and contestants work to solve them as quickly as they can. In Lockout, however, , each round has a set of problems and contestants work to solve them as quickly as they can. In

Full text and comments »

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

8.
By tourist, 9 years ago, In English
My strategy at AtCoder & CS Academy There's been much controversy lately about the late submission strategy not penalized by scoring systems of AtCoder and CS Academy. Most of the relevant discussion happened earlier at http://codeforces.me/blog/entry/53431 and http://codeforces.me/blog/entry/53449. I have a lot of thoughts on the topic, so I've decided to share them in a separate blog post. I really like the strategic part of programming competitions. Of course, problem solving is more important. But every contest consists of multiple problems, so there has to be a way of comparing participants which performed better at different problems. There's a huge variety of scoring rules, and I find it truly amusing. The "submit after solving all problems" strategy looks widely attributed to me now, mostly due to [user:Petr,2017-07-24]'s remarks regarding my participation in AtCoder contests. In my opinion, it's wrong for multiple reasons. A closer five-word description of my strategy is "implement after solvin...
minute. 3. Start thinking about problems in random order, frequently jumping from one problem to, thinking about problems in random order, frequently jumping from one problem to another. 4. Strive to

Full text and comments »

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

9.
By neal, 8 years ago, In English
Blowing up unordered_map, and how to stop getting hacked on it C++ has always had the convenient data structures `std::set` and `std::map`, which are tree data structures whose operations take $O(\log n)$ time. With C++11, we finally received a hash set and hash map in `std::unordered_set` and `std::unordered_map`. Unfortunately, I've seen a lot of people on Codeforces get hacked or fail system tests when using these. In this post I'll explain how it's possible to break these data structures and what you can do in order to continue using your favorite hash maps without worrying about being hacked [cut] . So how are they hackable? We always assume hash maps are $O(1)$ per operation (insert, erase, access, etc.). But this depends on a key assumption, which is that each item _only runs into $O(1)$ collisions on average_. If our input data is completely random, this is a reasonable assumption. But this is no longer a safe bet when the input isn't random, especially so if someone is adversarially designing inputs to our code (a.k.a. hacking ph...
the map in order to get $n^2$ blow-up. Not all of the primes work though, due to the resizing policy, C++ has always had the convenient data structures `std::set` and `std::map`, which are tree data

Full text and comments »

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

10.
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...
time needed to visit the vertices in the set denoted by $i$ and ending at vertex $j$. Note that $i, $ be the set of blocked cells. We add the ending cell to $S$ for convenience. We sort $S$ in, First, note that the order doesn't matter so we can sort the $a_{i}$ in non-decreasingorder. Now

Full text and comments »

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

11.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] Collection of little techniques #### Introduction There are a number of "small" algorithms and facts that come up again and again in problems. I feel like there I have had to explain them many times, partly because there are no blogs about them. On the other hand, writing a blog about them is also weird because there is not that much to be said. To settle these things "once and for all", I decided to write my own list about about common "small tricks" that don't really warrant a full tutorial because they can be adequately explained in a paragraph or two and there often isn't really anything to add except for padding. This blog is partly inspired by [user:adamant,2022-03-15]'s [blog](48417) from a few years ago. At first, I wanted to mimic adamant's blog structure exactly, but I found myself wanting to write longer paragraphs and using just bolded sentences as section headers got messy. Still, each section is short enough that it would not make much sense to write separate blogs about each of these things. A...
`set` of all integers up to $n$ that are **not** represented in the active segment, and an, attempt at solving might go like this. As always, we maintain an active segment. We keep a `set, $. Because the vertices are in the DFS order, the vertices in the subtree of $u$ must form a contiguous

Full text and comments »

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

12.
By platelet, 3 years ago, In English
CodeTON Round 5 Editorial ### [problem:1842A] <spoiler summary="Tutorial"> Let's view it as when monsters $x$ and $y$ fight, their health changes into $\max(x-y,0)$ and $\max(y-x,0)$ respectively. So any monster with $0$ health is considered dead. Therefore, a player loses when the health of his monsters are all $0$. Notice that $\max(x-y,0)=x-\min(x,y)$ and $\max(y-x,0)=y-\min(x,y)$. Therefore, after each step, the sum of the health of monsters decrease by the same amount for both players. Therefore, we only need to know $\sum a_i$ and $\sum b_i$ to determine who wins. If $\sum a_i > \sum b_i$, Tsondu wins. Else if $\sum a_i < \sum b_i$, Tenzing wins. Else, it is a draw. </spoiler> <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int T; cin >> T; while (T--) { int n, m, a[50], b[50]; long long sumA = 0, sumB = 0; cin >> n >> m; for (int i = 0; i < n;...
To be more specific, we can add vertices in increasing order of their distances from $1$. The time

Full text and comments »

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

13.
By MikeMirzayanov, 6 years ago, In English
Codeforces: Results of 2020 [list some changes and improvements] Hello, Codeforces! I understand that 2021 has been going on for a long time, but here I have picked up a subset of some of the improvements that the Codeforces team made in 2020. Soon I will publish numbers (no, charts) with statistics for 2020. In the meantime, I bring to your attention a list of changes and improvements. By the way, this is a decent list. This is about half to a quarter of all changes. It's just that other changes are more often somewhere in the internals of the system and are not visible to users. Please read this list. Each item is the effort of someone from the team. Thanks to [user:geranazavr555,2021-03-14], [user:kuviman,2021-03-14] and [user:cannor147,2021-03-14] for their efforts. You've made our platform better! Well, by the way, I don't quit programming and many improvements were made by me. The items on the list are written in a concise and informal form, many of the items I just copied from commit messages from git. If you want more details &mdash...
(including a personal list of exclusions) * Now you can set end time instead of duration while, filter of gym contests (including a personal list of exclusions) * Now you can set end time instead

Full text and comments »

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

14.
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...
maintain a set data structure of the updates, ordered by priority. (Such as `std::set` in C++). When, to the stack of updates we also maintain a set data structure of the updates, ordered by priority, $ priorities. We can push them in the same order that they originally appeared on the stack, for example, **, meaning that if we apply a set of updates and then a query, the answer to the query will be the, }\rceil$ highest priority updates are on top of the stack in increasing order. Let $U$ be theset of

Full text and comments »

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

15.
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...
worsen the time complexity. In order to efficiently determine the exhibits in someset $\bigcap_{i = a, In order to efficiently determine the exhibits in some set $\bigcap_{i = a}^{b} S_i$, we can

Full text and comments »

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

16.
By MikeMirzayanov, history, 11 years ago, translation, In English
New: Educational Rounds on Codeforces! Hi everybody! First, I invite you to take part in an official [contest:597]. The fact is, the Codeforces team has made numerous changes to the platform (details are below), and we want to be sure that the basic functionality remained unchanged. This round will have a shortened duration of 1.5 hours, consist of 3 (maybe 4) problems that you might have already seen before. Its purpose is to test the system on the one hand, and on the other hand &mdash; to brighten up a Wednesday evening. Of course, the round will be unrated. Now the main thing. This coming Friday (yes, the 13th of November) Codeforces starts another line of rounds. We called them Educational Rounds. Using my students at the Saratov State University Programmings Competitions Training Center as an example, I regularly notice that even those who have a considerable progress in the results on the rounds often have narrow purview in terms of standard topics and ideas, they are not familiar with many well-known problems ...
also exercises can be used; * Useful, even well-known ideas will be reused in order to introduce them, -known ideas will be reused in order to introduce them to a wide range of participants; * Often the

Full text and comments »

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

17.
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 | | :----------: | ...
. In fact, the best query complexity for sorting a poset (partially ordered set ) is $O(n(w+\log n, In fact, the best query complexity for sorting a poset (partially ordered set) is $O(n(w+\log n

Full text and comments »

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

18.
By jiangly, 4 years ago, In English
1st Universal Cup Announcement Hello everyone, we are happy to announce that the 1st Universal Cup is started officially. Universal Cup is a non-profit organization dedicated to providing training for competitive programming teams. Our website is [https://ucup.ac/](https://ucup.ac/) (in English and Chinese). In recent years, Chinese problem-setter teams have created a great number of high-quality contests. We have reached an agreement with most of these setters, that they agree to provide contest materials to Universal Cup for hosting mirror contests before publishing the set in public. We believe that such an arrangement can provide good opportunities to teams who want to do better in the future competing. Every year, with the permission of the problem setter team and without involving copyright disputes, the Universal Cup will hold mirror contests for some undisclosed competition sets. It is expected to hold at least 10 contests a year. We will simulate the actual situation in the competition, using the ...
Universal Cup for hosting mirror contests before publishing the set in public. We believe that such an

Full text and comments »

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

19.
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...
- **Set species** is defined as $E(A) = \\{A\\}$, combinatorial structure is a set of $|A, /Symbolic_method_%28combinatorics%29#The_multiset/set_operator_MSET/SET). **OGF forordered trees and, At last, another tree species is constructed on each set from $\pi$ and then the _sequence_ species, which corresponds to the ordinary product of _singleton_ species and the _sequence ofordered

Full text and comments »

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

20.
By MinakoKojima, history, 11 years ago, In English
My sad story Teams advancing to 2016 WF Phuket in Asia have been announced recently. This announcement is undisputedly tantamount to a death sentence for me. I am the one waiting anxiously, refresh Dr. Hwang's blog everyday. But it seems that for years, our training was meaningless. I think many of us dedicate our passion to programming contests because we see them transparent, fair and without any corruption. And I also believe that as contestants, what we should do is only focus on the practice. And I thought those political business should never come to bother me one day. But sadly, it is my team who is going to become one of the sacrifices of a succession of the dissension. What happened so far ------------------ The quarrel between the Asia director and the local community is [a long story](http://blog.sina.com.cn/s/blog_b946da100101q21y.html) to tell. But it has never been as serious as it was in the past season. Now reflecting on this, I know on the surface everything is going okay...
any opposition, you are directly set yourself to the hard mode. In quicksort, there is a strategy, directly set yourself to the hard mode. In quicksort, there is a strategy called “[killer adversary

Full text and comments »

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

21.
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 ...
gondolas in a line and read the children in this order, then that will be an order for the children

Full text and comments »

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

22.
By adamant, 13 years ago, translation, In English
About ordered set Hi everyone! I think many of you know about such data type as set. It must support such operations like: * Insert an element into set; * Check if the set contain some element; * Delete element from set. If we talk about ordered set, then elements (what a surprise!) must be kept in some order. As I think, there is also very important next operations: * Find the k-th element in a set; * Find the order of element in a set. Most of all, for the implementation of such functional some may use binary balanced trees (AVL- tree , red-black tree , cartesian tree , etc). However, in this article I would like to talk about some of the features in the implementation of an ordered set with other structures. In particular, I'll show the implementation with the segment tree and with the Binary Indexed Tree (Fenwick tree). But I just want to note that it only allows you to build the set of natural numbers. For all other types of elements such methods will not work :( The basic id...
About ordered set, element from set. If we talk about ordered set, then elements (what a surprise!) must be kept in some, in the array be the value of element in the set and let the value in the cell be the amount of, of the features in the implementation of an ordered set with other structures. In particular, I'll, * Find the k-th element in a set; * Find the order of element in a set., * Insert an element into set; * Check if the set contain some element; * Delete element from, * Limited functionality (supports only integers in the set); * In its simplest form takes $O(C, Hi everyone! I think many of you know about such data type as set. It must support such operations, If we talk about ordered set, then elements (what a surprise!) must be kept in someorder. As I

Full text and comments »

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

23.
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...
A data structure this won't work on is, for example, a segment tree with the update of "set in

Full text and comments »

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

24.
By pajenegod, 3 years ago, In English
Shallowest Decomposition Tree Hi Codeforces! Today I want to tell you about a really cool and relatively unknown technique that is reminiscent of Centroid decomposition, but at the same time is also completely different. The most common and well known decomposition tree algorithm out there is the centroid decomposition algorithm (running in $O(n \log n)$). It is a standard algorithm that is commonly used to solve tons of different kind of divide and conquer problems on trees. However, it turns out that there exists another closely related decomposition tree algorithm, that is in a sense optimal, and can be implemented to run in $O(n)$ time in around $30$ lines of code. I have chosen to call it the _Shallowest Decomposition Tree_. This blog will be all about the shallowest decomposition tree. Something I want to remark on before we start is that I did not invent this. However, very few people know about it. So I decided to make this blog in order to teach people about this super cool and relatively unknown tec...
$, then set of labels in `forbidden(v) + 1` which are smaller than $u$'s label corresponds to a (Case 1

Full text and comments »

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

25.
By Errichto, 8 years ago, In English
Sums and Expected Value — part 2 ### Instruction I recommend this blog also for red users. Read the theory and problems below, try to solve them. For solutions and extra insight/tips, watch my stream on Monday or watch the video later. If you aren't familiar with EV or summing problems, see part 1 first: [http://codeforces.me/blog/entry/62690] (http://codeforces.me/blog/entry/62690). I will stream a lecture on Monday at [14:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?msg=EV+lecture+2&iso=20181029T14&p1=262) &mdash; [https://www.youtube.com/watch?v=HDk6zQw0Rdo](https://www.youtube.com/watch?v=HDk6zQw0Rdo) (also [Twitch](https://www.twitch.tv/errichto)). I will go through theory and problems from this blog. ### Expected Value theory, part 2 We roll a 6-sided die. Remember, EV of square of the number of pips is something different than square of EV: $$E(X^2) = \frac{1+4+9+16+25+36}{6} = 15.166666\ldots$$ $$E(X)^2 = (\frac{1+2+3+4+5+6}{6})^2 = 3.5^2 = 12.25$$ Two events are ...
**ordered pairs** of elements in the set. So we iterate over pairs and for each we compute the, The square of the size of a set is equal to the number of **ordered pairs** of elements in theset

Full text and comments »

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

26.
By adamant, history, 2 years ago, In English
Fenwick bitset _Okay guys, I know it sounds like [Top 10 optimizations 2017- (collectors edition)](https://codeforces.me/blog/entry/53168) but hear me out_ Hi everyone! Recently, a problem **[ordered set](https://judge.yosupo.jp/problem/ordered_set)** has been added to Library Checker. Essentially, the problem asks you to maintain a set $\\{a_1,\dots,a_n\\}$ that supports the following operations: 1. Insert an element; 2. Erase an element; 3. Find the $k$-th smallest element; 4. Find the order index of an element; 5. Find lower bound of an element; 6. Find pre-upper bound of an element. Of course, all these [can be done](https://judge.yosupo.jp/submission/248515) with GNU policy-based data structures (pbds) in $O(\log n)$ per query, which leads to the shortest code. At the same time, it has a huge constant factor in practice, so a natural question arises. What would be the fastest way to solve this? One of my [earliest blogs](https://codeforces.me/blog/entry/11275) already addre...
://codeforces.com/blog/entry/53168) but hear me out_ Hi everyone! Recently, a problem **[ordered set, P.P.S. Are there any more efficient yet simple structures for Ordered Set problem?, Recently, a problem **[ordered set ](https://judge.yosupo.jp/problem/ordered_set)** has been added

Full text and comments »

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

27.
By humbertoyusta, history, 5 years ago, In English
[Tutorial] Dp with connected components, a simple way to understand it. Inspired by [Tutorial Non-trivial DP Tricks and Techniques, by zscoder](https://codeforces.me/blog/entry/47764), This is actually a well known DP trick, and has appeared in some problems, but I have not found a detailed tutorial to easily understand it from scratch, me and some friends had troubles to learn this trick, so I will try to explain in a simple and detailed way. #### What is dp with connected components: The main idea of this trick is building permutations inserting the elements in increasing order, and storing as a state of the dynamic programming the number of chunks or components that represents some prefix of elements (i.e elements $1, 2, ... i$), and the transitions are about how inserting the next element ($i + 1$), will affect this chunks or components. (note that these are the values of the elements, not their position in the permutation) This trick can be useful to count the number of permutations with some characteristics or constraints and to find permut...
an ordered set, the order of elements matters, not just their values, set $(a, b)$ $\neq$set $(b, a, elements $1, 2, 3, ..., i$ by value, not by position) of any permutation $p$ is always anordered set of, size $n$ corresponds to a ordered set of components, and, since for a fixed permutation, in each, two components, $(2)$ and $(3, 1)$, their ordered set is $( (2) , (3, 1) )$ and will be counted in, Here in an ordered set, the order of elements matters, not just their values, set $(a, b)$ $\neq, So for any case we can obtain a new ordered set from the previous one by adding $i$.

Full text and comments »

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

28.
By -is-this-fft-, history, 3 years ago, In English
[Tutorial] The residual graph and working with the set of all minimum cuts I have previously written about flows in these blogs: [1](https://codeforces.me/blog/entry/104960), [2](https://codeforces.me/blog/entry/105330), [3](https://codeforces.me/blog/entry/105658). Minimum cuts are a very fascinating topic for me. There are a lot of maximum flow problems where there's a fairly simple chain of reductions leading to "you should use flow", but there are also a lot of flow problems where flow comes apparently out of nowhere. Particularly fascinating are those where it's more convenient to think in terms of minimum cut: they work, because minimum cut allows you to model partitioning a set in two, with some additional implication-like constraints. Here are a couple of problems with that nature: - [ARC085E \- MUL](https://atcoder.jp/contests/arc085/tasks/arc085_c) (this reduction is almost standard these days) - [ARC142E \- Pairing Wizards](https://atcoder.jp/contests/arc142/tasks/arc142_e) - [problem:104925D] There are also flow problems on graphs ...
[Tutorial] The residual graph and working with the set of all minimum cuts, - Set $C = \varnothing$. - Assign an "indeterminate" value to, model partitioning a set in two, with some additional implication-like constraints. Here are a, - Set $C = \varnothing$. (The set of the edges in the cut) - For each edge $e$, in increasing, - Set $C = \varnothing$. - Assign an "indeterminate" value to each vertex. - Assign 1 to $s$, do

Full text and comments »

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

29.
By AksLolCoding, history, 13 months ago, In English
Essential Tips for AI in Competitive Programming With the rise of AI in competitive programming, this blog aims to assist AI with essential tips to make it's submissions valid and acceptable on programming sites such as Codeforces. Following these is also essential for AI to blend in with human participants. This blog does NOT attempt to sabotage AI in any way. Feel free post more essential AI programming tips in the comments. 1. Use long variable names. Because AI can code extremely fast, these long variable names save time in the long term since they make code easier to adjust and debug. 2. Comment code thoroughly with long detailed and grammatically correct sentences. This makes code cleaner to read and more humanoid. Even if it doesn't seem necessary, such as after `i++`, it is still important to comment this code. 3. Always check if input variables such as `n` are positive. Many problems will have edge case tests where input variables are negative, even if the constraints say they are greater than or equal to $0$. This is n...
`unordered_set` whenever possible and avoid `set` and `map` at all costs. It is well known that the unordered, possible and avoid `set` and `map` at all costs. It is well known that the unordered versions are both

Full text and comments »

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

30.
By neal, 6 years ago, In English
Unofficial Editorial for Educational Round 95 (Div. 2) Here are my approaches to the problems today: #### [problem:1418A] Since the second trade is the only way to get coal, we clearly need to perform the second trade $k$ times. So how many times do we need to do the first trade? We can see that in order to end up with enough sticks and coal by the end, we need to obtain $ky + k$ sticks ($ky$ to convert to coal and $k$ to save as sticks). Since the first trade really just gives us $x - 1$ new sticks each time, we'll need to make $\displaystyle \left \lceil \frac{ky + k - 1}{x - 1} \right \rceil$ first trades ([reference to floor and ceiling functions](https://en.wikipedia.org/wiki/Floor_and_ceiling_functions) for anyone unfamiliar). For implementation details, note that for positive integers $a$ and $b$, $\displaystyle \left \lceil \frac{a}{b} \right \rceil = \left \lfloor \frac{a + b - 1}{b} \right \rfloor$. Code: [submission:92851684] #### [problem:1418B] We can think about the problem as follows: we want to order the $a_i$ to...
In order to do this and handle queries, we can store all of the positions in a set and all of the

Full text and comments »

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

31.
By Endagorion, 12 years ago, translation, In English
Codeforces Round #283: editorial (with bonuses!) Each problem comes with a challenge &mdash; a bonus task somehow related to the problem; you may tackle at the challenges for fun and practice, also feel free to discuss them at the comments. =) [problem:496A] For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^2)$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the difference between the neighbours of the removed element (whatever is larger); thus, the difficulty for every option of removing an element can be found in $O(1)$, for the total complexity of $O(n)$. Any of these solutions (or even less efficient ones) could pass the tests. **Challenge**: suppose we now have to remove exactly $k$ arbitrary elements (but the first and the last elements have to stay in their places). How small the maximal difference between adjacen...
maintain a set of actors which have already occured in the order; if we meet an entry for an actor, add, ); process all the enitities in this order. We maintain a set of actors which have already occured

Full text and comments »

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

32.
By FieryPhoenix, 7 years ago, In English
Codeforces Round #638 (Div. 2) Editorial [problem:1348A] <spoiler summary="Tutorial"> [tutorial:1348A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int N; cin>>N; //note: 1<<X means 2^X //we put largest coin in first pile int sum1=(1<<N), sum2=0; //we put n/2-1 smallest coins in first pile for (int i=1;i<N/2;i++) sum1+=(1<<i); //we put remaining n/2 coins in second pile for (int i=N/2;i<N;i++) sum2+=(1<<i); cout<<sum1-sum2<<endl; } int main(){ int t; cin>>t; while (t--) solve(); } ~~~~~ </spoiler> [problem:1348B] <spoiler summary="Tutorial"> [tutorial:1348B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int N,K; cin>>N>>K; set<int>s; for (int i=0;i<N;i++){ int a; cin>>a; s.insert(a); } //if more than K distinct numbers, print -1 if (s.size()>K){ cout<<-1<<endl; return; ...
; from[label2[*it]]=node; dfs(label2[*it]); } //removes visited nodes from set while

Full text and comments »

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

33.
By Endagorion, 12 years ago, In English
Codeforces Round #300 (with prizes!) Hello, Codeforces! [On Sunday, April 26th at 19:00 MSK](http://www.timeanddate.com/worldclock/fixedtime.html?day=26&month=4&year=2015&hour=19&min=0&sec=0&p1=166) the 300'th regular Codeforces Round will take place. I would like to congratulate all Codeforces members and administration on this remarkable milestone. The platform has grown hugely in size and quality since its foundation, has hosted lots of exciting competitions, and has been providing the opportunity to everyone to hone their problem solving and algorithmic mastery. For this we thank the Codeforces platform creator [user:MikeMirzayanov,2015-04-24] and all the Codeforces crew. Keep up the incredible job, guys! That being said, I'm excited to announce that the problems on the jubilee three-hundredth Codeforces Round will be set by me, Mikhail Tikhomirov ([user:Endagorion,2015-04-24]). You may remember the past rounds with my problems: [#99](http://codeforces.me/contests/138,139), [#109](http://codeforces.me/contest...
will be set by me, Mikhail Tikhomirov ([user:Endagorion,2015-04-24]). You may remember the past

Full text and comments »

Announcement of Codeforces Round 300
  • Vote: I like it
  • +1212
  • Vote: I do not like it

34.
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...
colored into state $2$ from top to bottom, and it must follow the order of color, delete, color, delete

Full text and comments »

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

35.
By humbertoyusta, history, 6 years ago, In English
XOR Hashing [TUTORIAL] This is a well known technique, but I couldn't find almost any detailed tutorial, so I'll try to help with this one. ####Motivational Problem: You have an array $A$ and $Q$ queries, which are, say if the subarray from $l$ to $r$, ($A[l]$, $A[l+1]$, $...$, $A[r]$) forms a permutation. ####Some basic observations: Only the set of elements matters, the order is irrelevant. You want to know if each element is exactly once. ####Solution: Assign a random number $randval[i]$ to each number $i$, now we can say that if the XOR of the subarray ( $randval[A[l]]$ xor $randval[A[l+1]]$ xor $...$ xor $randval[A[r]]$ ) is equal to the xor of any permutation of size $r - l + 1$ (for example $1$, $2$, $3$, ... ,$r-l+1$, which hash is $randval[1]$ xor $randval[2]$ xor $...$ xor $randval[r-l+1]$ ) the subarray is a permutation. ####Some Insights: With the XOR we have some issues, we are counting if the number of occurrences of each element is even or odd, not the real number o...
Only the set of elements matters, the order is irrelevant.

Full text and comments »

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

36.
By Endagorion, history, 9 years ago, In English
Yandex.Algorithm 2017, third elimination round: editorial (with challenges, bells and whistles) This time I've decided to play with spoilers to faciliate the presentation as some of the guys here did before. Tell me what you think about this write-up! #### Problem A. Shifts Topics: dynamic programming. Summary: the first "hard" problem of the contest. Knowing your basic DP problems helps a lot, but coming up with the precisely correct solution may take a lot of persistence. Solution: Suppose that we are allowed to make left circular shifts as well as right ones. <spoiler summary="Can you solve the problem in this case?"> First of all, making a shift is effectively moving a character to a different position in the string. Clearly, moving a character more than once makes no sense since we could have just moved it to its final destination instead without wasting any operations. Also, it obvious that the number of occurences of each character should be the same in both strings since it is preserved by shifts. Now, consider the characters that are *not* moved by ...
choosing an equal sub(multi)set in $A$ and arranging them in the required order while staying to the, relative order since we are not allowed to move them around. Hence, they have to form a [common

Full text and comments »

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

37.
By Okrut, history, 6 years ago, In English
Codeforces Round #647 Editorial [problem:1362A] Author: [user:Anadi, 2020-06-04] <spoiler summary="Tutorial"> [tutorial:1362A] </spoiler> <spoiler summary="Solution"> ``` #include <bits/stdc++.h> using namespace std; typedef long long LL; LL getR(LL a){ while(a % 2 == 0) a /= 2; return a; } void solve(){ LL a, b; scanf("%lld %lld", &a, &b); if(a > b) swap(a, b); LL r = getR(a); if(getR(b) != r){ puts("-1"); return; } int ans = 0; b /= a; while(b >= 8) b /= 8, ++ans; if(b > 1) ++ans; printf("%d\n", ans); } int main(){ int quest; scanf("%d", &quest); while(quest--) solve(); return 0; } ``` </spoiler> [problem:1362B] Authors: [user:Anadi, 2020-06-04] and [user:Okrut, 2020-06-04] <spoiler summary="Tutorial"> [tutorial:1362B] </spoiler> <spoiler summary="Solution"> ``` //O(n * maxA) solution #include <bits/stdc++.h> using namespace std; const int N = 1025; int n; int in[N]; bool is[N]; bool ch...
//get elements from ordered set for(auto v: ret -> right -> S) ret -> S.insert(v);

Full text and comments »

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

38.
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...
,r)$ has a `set` $v[i]$ that contains each number $k$ if and only if $\sum_{i=l}^{r} count(a_i, k

Full text and comments »

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

39.
By brunomont, history, 6 years ago, In English
[Tutorial] A powerful representation of integer sets Hello, Codeforces! This blog is heavily inspired by [user:TLE,2020-10-22]'s blog [using merging segment tree to solve problems about sorted list](https://codeforces.me/blog/entry/49446). I don't know exactly how well known this data structure is, but I thought it would be nice to share it anyway, along with some more operations that are possible with it. What it can do ------------------ We want a data structure that we can think of a set/multiset of **non-negative integers**, or even as a sorted array. We want to support all of the following operations: 1. Create an empty structure; 2. Insert an element to the structure; 3. Remove an element from the structure; 4. Print the $k$'th smallest element (if we think of the structure as a sorted array $a$, we are asking for $a[k]$); 5. Print how many numbers less than $x$ there are in the set (similar to lower_bound in a std::vector); 6. Split the structure into two: one containing the $k$ smallest elements, and the other ...
------------------ We want a data structure that we can think of a set /multiset of **non-negative integers**, or, Order statistic operations work as well:

Full text and comments »

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

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

Full text and comments »

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

41.
By paladin8, 15 years ago, In English
Partially Ordered Sets This post is motivated by a problem I recently saw, Problem G of [NCPC 2007](http://ncpc.idi.ntnu.no/ncpc2007/ncpc2007problems.pdf ""). This is a standard problem that I'm sure many of you have seen before, but the general topic of partially ordered sets is not too well known. ###Definitions Let $S$ be a set of elements and $\le$ be a partial ordering on the set. That is, for some elements $x$ and $y$ in $S$ we may have $x \le y$. The only properties that $\le$ must satisfy are reflexivity ($x \le x$), antisymmetry (if $x \le y$ and $y \le x$, then $x = y$), and transitivity (if $x \le y$ and $y \le z$, then $x \le z$). Note that because it is a _partial_ ordering, not all $x$ and $y$ are comparable. An example of a partially ordered set (poset) is the set of points $(x, y)$ in the Cartesian plane with the operator $(x_1, y_1) \le (x_2, y_2)$ iff $x_1 \le x_2$ and $y_1 \le y_2$ (e.g. NCPC 2007 problem). We define a **chain** $C$ to be a subset of $S$ such that the elements of...
Partially Ordered Sets, before, but the general topic of partially ordered sets is not too well known., sorted in order by $x$. We maintain a set of pairs $(a, b)$ which indicates that there is an, ###Definitions Let $S$ be a set of elements and $\le$ be a partial ordering on theset. That is, $ are comparable. An example of a partially ordered set (poset) is the set of points $(x, y)$ in the, , x_2, \ldots, x_n$ such that $x_1 \le x_2 \le \cdots \le x_n$. A **partition** $P$ is aset of, An example of a partially ordered set (poset) is the set of points $(x, y)$ in the Cartesian plane, Notice, however, that if we have two points in the set $(a, b)$ and $(c, d)$ such that $c \le a

Full text and comments »

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

42.
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...
To store the graph, we simply store the set of points which forms the valleys (the red crosses in

Full text and comments »

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

43.
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 ...
according to their decreading order of $f$ values. Suppose $\vec{b_h}$ is the one with the hightest, update the basis such that it can also represent the new vector $\vec{v_i}.$ In order to do that

Full text and comments »

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

44.
By minstdfx, history, 2 weeks ago, In English
[Shitpost] How to Teach Kids Basic Data Structures Using the Methods of a Mathematics Textbook ## Conventions This article is based on ordinary set theory. Natural numbers, integers, finite sequences, maps, Cartesian products, total orders, trees, induction, and the finite recursion theorem are assumed to be established. Write $\mathbf N=\{0,1,\ldots\}$ and $\mathbf N_{>0}=\mathbf N\setminus\{0\}$. All trees are finite trees; all intervals not otherwise qualified are integer intervals. For $l,r\in\mathbf Z$, put $$ [l,r]=\{i\in\mathbf Z:l\le i\le r\},\qquad [n]=[1,n]. $$ When $l>r$, $[l,r]=\varnothing$. For a nonempty finite set $E$, $|E|$ denotes its cardinality. The symbol $\sqcup$ denotes disjoint union. Composition of maps follows the convention $(f\circ g)(x)=f(g(x))$. For $n\ge1$, put $$ \lambda(n)=1+\lfloor\log_2 n\rfloor. $$ All asymptotic estimates are taken as $n\to\infty$; bounds written in terms of $\lambda(n)$ also apply to $n=1$. **Computational conventions.** Unless otherwise stated, we use the random-access machine model with word leng...
totally ordered set. Interval aggregation on a general idempotent semigroup is distinguished from RMQ., ## §2. Range Minima on Ordered Sets, $ in a totally ordered set, RMQ has a representation with preprocessing time $O(n)$, space $O(n)$, and, **Definition 7.5.** Let $(X,\le)$ be a totally ordered set and $a\in X^n$. Use the lexicographic, **Proof.** A root satisfying heap order is strictly smaller along every path than all other, **Proof.** The root is a common ancestor. All ancestors of $u$ form a finite totallyordered chain, **Proposition 10.3.** $C_a$ is the unique ordered binary tree with vertex set $[n]$, inorder, **Proposition 7.6.** On a totally ordered set, the binary operation defined by taking the smaller, 1. Set $s_u\leftarrow s_u+|J|c$. 2. If $J=I_u$, set $t_u\leftarrow t_u+c$ and terminate. 3, Fix a totally ordered set $X$ and $a\in X^n$, and continue using the lexicographicorder on $q_i, This article is based on ordinary set theory. Natural numbers, integers, finite sequences, maps, set $t=t_u$, then perform in order

Full text and comments »

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

45.
By Monogon, history, 6 years ago, In English
Efficient 3D Convex Hull Tutorial _Warning: The following contains graphic depictions of geometry, precision errors, and degenerate cases. Viewer discretion is advised._ ### Prerequisites I assume the reader is familiar with: - 2D Convex Hulls - 3D Vector Operations (dot and cross products) ### Introduction Recall that in the 2D convex hull problem, you are given a set of 2D points, and you must compute the smallest convex polygon containing all the given points. By convex, we mean that for any two points $A$ and $B$ inside the polygon, the entire line segment $AB$ is also inside the polygon. The problem in 3D is completely analogous. You are given $n$ 3D points, and you must compute the smallest convex polyhedron containing all the given points. Similarly, a polyhedron is convex if for any two points $A$ and $B$ inside the polyhedron, the line segment $AB$ is also inside the polyhedron. In the 2D case, it is more obvious what the output is. We can simply output a circular list of vertices on the ...
-bit integer types, we can convert to floating points for computations, and set $\epsilon=0.5$. Note

Full text and comments »

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

46.
By MikeMirzayanov, 10 years ago, translation, In English
Codeforces: summing up 2016 year <center> <img src="http://assets.codeforces.com/images/Happy-New-Year-HD-Wallpapers.jpg"/> </center> Somehow it turns out that for me, each coming the New Year means more and more. This is an excellent opportunity to take stock, to breathe fresh air and to go through a kind of catharsis. This is a rare opportunity to be with the family, dress up in Santa Claus and just have fun. Holidays give me a clear criterion that I do the right things. If during the holidays, I begin to think about it, to recall some deferred ideas, eager to implement something new. So I’m doing right things. My things. And now exactly the same as in several recent years: during New Year holidays I write code for Codeforces, trying new technology or simply I’m making minor changes in testlib. It is necessary to me: at this moment are no deadlines, do not press the obligation. Just now, at 3 am, I can not break away from being able to do something new. I would like to take a moment and realize that spun in ...
programming contest whether in order to find the brightest talent (yes, you are!) candidates

Full text and comments »

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

47.
By satyam343, 4 years ago, In English
Codeforces Round #838 (Div. 2) Editorial Thank you for participation! I hope you liked atleast one problem from the set (: We tried hard to have an interesting problemset. It is sad to see people disliking the round only because some problems were hard. Please read the intended solutions to know why we decided to put the problems(especially D) at current positions. [problem:1762A] Idea:[user:satyam_343,2022-12-16] <spoiler summary="Hint 1"> If sum is even, answer is $0$. Otherwise we need to change parity of atleast one element of $a$. </spoiler> <spoiler summary="Hint 2"> It it optimal to change parity of atmost one element. </spoiler> <spoiler summary="Hint 3"> Answer can be atmost $20$, as we need to divide any integer $x$ ($1 \leq x \leq 10^6$) atmost $20$ times to change its parity. </spoiler> <spoiler summary="Solution"> We are assuming initial sum is odd. Suppose $f(x)(1 \leq x \leq 10^6)$ gives the minimum number of operations needed to change parity of $x$. Iterate from $i=1$ to ...
or ordered set to find $f(i,l,r)$.

Full text and comments »

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

48.
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 ...
Note that K was not present in the WF46 set. I will go into detail about our process with solving

Full text and comments »

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

49.
By Geothermal, history, 6 years ago, In English
Codeforces Round #709 / Technocup 2021 Final Round - Unofficial Editorial As the editorial for round #709 has yet to be released, I thought I'd write up and post my solutions to the problems (with the exception of Div. 1 F). My code may not be especially useful, since it's a bit messier than necessary in some cases, but I'm hoping that the written explanations will be fairly helpful. Feel free to comment if you have any questions! --- #[2A &mdash; Prison Break](https://codeforces.me/contest/1484/problem/A) By simply playing around with a few small test cases, you might guess that the answer is always equal to $ab$. This intuition is correct; let's prove it formally. Consider a graph with $ab+1$ vertices including one vertex representing each cell of the prison, one vertex representing the outside world, and an edge for each wall of the prison connecting the two vertices on either side of the wall. Then, observe that a set of walls we can remove such that the outside world is accessible from every cell is equivalent to a set of edges that s...
Now, let's actually define these variables. We'll iterate over the buildings in reverseorder, We repeat this process until set two is empty. It will then give us a complete list of all the

Full text and comments »

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

50.
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...
(l_i, r_i)$. 3. Set $y = a_1 + a_2 + \ldots + a_n$. 4. Sort the values of $b$ in descendingorder. 5

Full text and comments »

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

51.
By Zlobober, history, 11 years ago, translation, In English
Editorial for VK Cup 2015 — Finals Thanks everybody for participating. Tasks follow in the order of the original contest (the mirror order is given in the brackets). [problem:562A] -------------- (in mirror: [problem:566C]) Let's think about formal statement of the problem. We are given a tricky definition of a distance on the tre: $\rho(a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_i$. We need to choose a place $x$ for a competition such that the sum of distances from all vertices of the tree with their weights is minimum possible: $f(x) = w_1 \rho(1, x) + w_2 \rho(x, 2) + \ldots + w_n \rho(x, n)$. Let's understand how function $f(x)$ works. Allow yourself to put point $x$ not only in vertices of the tree, but also in any point inside each edge by naturally expanding the distance definition (for example, the middle of the edge of length $4$ km is located $2$ km from both ends of this edge). **Fact 1**. For any path $x \in [a, b]$ in the tree the function $\rho(i, x)$ is convex. Actually, the ...
it. So, we know the set of all neighborhoods of all vertices in some arbitrary order, and also each, Order numbers in the sought clique in ascending order. Note that set $X = \{x_1, \ldots, x_k\}$ is

Full text and comments »

Tutorial of VK Cup 2015 - Finals
  • Vote: I like it
  • +100
  • Vote: I do not like it

52.
By Flamire, history, 2 years ago, In English
EPIC Institute of Technology Round August 2024 (Div. 1 + Div. 2) Editorial [2002A &mdash; Distanced Coloring](https://codeforces.me/contest/2002/problem/A) idea & solution: [user:xcyle,2024-08-12] <spoiler summary="Hint 1"> Consider the case with $n=m=k$. </spoiler> <spoiler summary="Hint 2"> Generalize the solution for all $n,m,k$. </spoiler> <spoiler summary="Tutorial"> It can be shown that for any $k\times k$ subgrid, the colors we use must be pairwise distinct. Thus, we have an lower bound of $\min(n,k)\cdot\min(m,k)$. We can show that this lower bound is indeed achievable by coloring the upper-left $\min(n,k)\cdot\min(m,k)$ subgrid with distinct colors, and copy-pasting it to fill the rest of the grid. Time complexity: $O(1)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int t, n, m, k; int main() { scanf("%d", &t); while (t--) { scanf("%d%d%d", &n, &m, &k); printf("%d\n", min(n, k)*min(m, k)); } return 0; } ~~~~~ </spoiler> [2...
There also exists $O(n\log n)$ solutions using ordered sets or heaps.

Full text and comments »

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

53.
By osvarp, 13 months ago, In English
Ordered Set Intersection I'm a simple guy. When I find out I can reduce a problem to something known (or something I suspect must be known) and I've never learned it, then I just look in the internet to see if my approach may be feasible. When I was solving [problem:2155F], which I'll refer on the blog as JCT, and found out it could be reduced to finding the size of the intersection of ordered sets, I did just that. What I found was Binary Search ------------------ Given two ordered sets $A$ and $B$, which Im assuming to be of type `vector<int>`, then this one works in time $O(|A| log |B| )$ where $|A|\leq |B|$. The code is something like ~~~~~ int res=0; for(int ac:A)res+=binary_search(B.begin(),B.end(),ac); ~~~~~ When I sent it to JCT. It got AC with $\approx 1.8$ seconds and a total complexity of something like $O(n\sqrt{n}lgn)$. However, now it seems to be patched out (it got in $\approx 1.8$ seconds when testing, now it gets TLE). But I decided I could do better... Weird? Binary Sea...
Ordered Set Intersection, out it could be reduced to finding the size of the intersection of ordered sets, I did just that. What, Binary Search ------------------ Given two ordered sets $A$ and $B$, which Im assuming to be of

Full text and comments »

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

54.
By bicsi, history, 6 years ago, In English
Compressed segment trees and merging sets in O(N logU) Hello! Today I will present a data structure that I have worked on for my Bachelor thesis a while ago, called (by me) a PreTree ([link to thesis](https://github.com/bicsi/pretree)). This is a type of "compressed" trie that is arguably easier to implement than a regular compressed trie, and it achieves merging in amortized $O(N L)$ complexity for $N$ keys of equal length $L$. I will present an implementation as a segment tree, though, as it is easier to understand. **Prerequisite: know segment trees, and "sparse" segment trees (a.k.a. bitwise tries).** ### Main idea We will keep a regular segment tree, with the twist that *the root contains the minimum key*. Basically, a PreTree on keys in the universe $[b, e)$ is a binary tree $T$ where either $T$ is empty, or the following conditions hold: 1. $T$ holds the lowest key present in the range $[b, e)$ 2. $T$'s left son is a PreTree on values $[b, \frac{b + e}{2})$ 3. $T$'s right son is a PreTree on values $[\frac{b + e}{2...
number of nodes. In order to see why is that, we will have to look at the depths of each node in the, subjective), and also because their pre-order traversals yield keys in sorted order., tree" (of course, beauty is subjective), and also because their pre-order traversals yield keys in, In order to find the greatest key smaller than a given $k$, one can do the following:, In order to insert a key into the tree, just merge it with a singleton tree., In order to make the implementation easier, we will define a single big operation called "merging

Full text and comments »

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

55.
By leaf_node, 3 years ago, In English
Custom Ordered Set Hello Codeforces, ================= This is my first constructive blog on this platform. ### Introduction ordered_set is a PBDS(Policy Based Data Structure) that provides all the functionalities of a set, such as logarithmic time complexity for insertion, deletion, and searching. However, it also allows additional operations, including finding the k-th smallest/largest element and finding the order statistics. (more about PBDS could be found on this [blog](https://codeforces.me/blog/entry/11080)) An **ordered_multiset** is an ordered_set which allows duplicates. After experimenting with the ordered_multiset, I discovered that the find and erase functions were not functioning as expected. Consequently, I took it upon myself to create my own implementation of an ordered_multiset and decided to share it with you. Lets call it COS **Custom Ordered Set** `:)` The whole idea is to efficiently maintain a sorted array like structure so that we can answer all of the requ...
Custom Ordered Set, ordered_multiset and decided to share it with you. Lets call it COS **Custom Ordered Set** `:)` The, shift some elements in the sorted array in order to make space for the new element., ordered_set is a PBDS(Policy Based Data Structure) that provides all the functionalities of aset

Full text and comments »

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

56.
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...
Sort $a$ in nonincreasing order so that $a_1 \ge a_2 \ge \dots \ge a_n$. We can simulate the greedy

Full text and comments »

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

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

Full text and comments »

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

58.
By adamant, history, 4 years ago, In English
Lagrange inversion theorem Hi everyone! There is a concept that is sometimes mentioned [here](https://codeforces.me/blog/entry/77284?#comment-622525) and [there](https://codeforces.me/blog/entry/77551). The [Lagrange inversion theorem](https://en.wikipedia.org/wiki/Lagrange_inversion_theorem). Let $x = f(y)$. We want to solve this equation for $y$. In other words, we want to find a function $g$ such that $y = g(x)$. The Lagrange inversion theorem gives an explicit formula for the coefficients of $g(x)$ as a formal power series over $\mathbb K$: $$ \large k[x^k] g(x) = [x^{-1}] f^{-k} $$ In a special case $y = x \phi(y)$, that is $f(y) = \frac{y}{\phi(y)}$, which is common in combinatorics, it can also be formulated as $$ \large k[x^k] g(x) = [x^{k-1}] \phi^k $$ Finally, to avoid division by $k$ one may use (see the [comment](https://codeforces.me/blog/entry/104184?#comment-925505) by [user:Elegia,2022-06-25]) the following formula: $$ \large [x^k]g(x) = [x^{-2}] f' f^{-(k+1)}, $...
In other words, as a set-theoretic object, an ordered tree can be represented as a $(k+1)$-tuple, We can enumerate ordered $n$-tuples of arbitrary objects from class $A$ as $A^n(x)$. And to

Full text and comments »

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

59.
By EvenImage, history, 7 years ago, In English
A problem collection of ODE and differential technique ##A problem collection of ODE and differential technique *This problem might be well-known in some countries, but how do other countries learn about such problems if nobody poses them.* For those who are interested in well-known problems in China. Thank [user:Elegia,2020-04-23] and [user:djq_cpp,2020-04-23] for developing this technique. Thank [user:tEMMIE.w.,2020-04-23] for reviewing this article. ####[Chain Reaction](http://uoj.ac/problem/50) in UOJ Round 3 By [user:vfleaking,2020-04-23] **Statement** ​ You are given a set $A$, you need to compute $g_{i} = \frac{1}{2} \sum_{j,k}{i-1 \choose j}{i-1-j \choose k} g_jg_k$ where $i-1-j-k \in A$. **Solution** ​ Let the EGF of $g$ be $x(t)$ and EGF of $A$ be $a(t)$. Thus $x'(t)=\frac{1}{2} a(t) x^2(t)+1$. We can solve this equation by D&C and FFT in $O(n\log^2 n)$. But there is a <s>slower</s> solution in $O(n\log n)$. ​ For a polynomial equation $f(x(t))=0$, we can use the Newton's method to solve it. If we find ...
-04-23] **Statement** You are given a set $A$, you need to compute $g_{i} = \frac{1}{2

Full text and comments »

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

60.
By ko_osaga, history, 3 years ago, In English
A Brief Inquiry into Online Connectivity This question striked my head: *"How can I solve dynamic $k$-connectivity efficiently?"* And then I tried to answer it, but I realized that my question was open to a lot of different interpretations. Two vertices are $k$-connected if there are $k$ edge-disjoint paths connecting two vertices. For $k = 1$, it is the usual definition of *connectivity*. ## Solve? If I say, "I solved the graph connectivity problem", what can it possibly mean? **First Interpretation ($s$-$t$ connectivity)**. I can respond to the following query efficiently: Given two vertices $s, t$, determine if there is a path between them. In the case of $k = 1$, graph search suffices. What about higher $k$? You can find $k$ edge-disjoint path by reducing it into a flow problem. Each edge-disjoint path corresponds to a flow from $s$-$t$, so make all edges to capacity one, and find a flow of total capacity $k$ from $s$ to $t$. This algorithm takes $O(\min(k, m^{1/2}) (n + m))$ time. **Second Interpre...
. In that case, you can take advantage of the fact that you know the whole set of queries that will

Full text and comments »

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

61.
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...
about `vector`, `deque`, `set` and other containers? ~~~~~ vector v; v = {1, 2, 5, 2

Full text and comments »

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

62.
By n0sk1ll, 4 years ago, In English
Editorial for Hello 2023 ## [problem:1779A] Author: [user:n0sk1ll,2022-12-27] <spoiler summary="Hint"> What happens when $\texttt{L}$ appears after some $\texttt{R}$ in the string? </spoiler> <spoiler summary="Solution"> Suppose that there exists an index $i$ such that $s_i = \texttt{R}$ and $s_{i+1} = \texttt{L}$. Lamp $i$ illuminates trophies $i+1,i+2,\ldots n$ and lamp $i+1$ illuminates $1,2,\ldots i$. We can conclude that all trophies are illuminated if $\texttt{L}$ appears right after some $\texttt{R}$. So, strings $\texttt{LLRRLL}, \texttt{LRLRLR}, \texttt{RRRLLL}, \ldots$ do not require any operations to be performed on them, since they represent configurations of lamps in which all trophies are already illuminated. Now, we consider the case when such $i$ does not exist and think about how we can use the operation **once**. Notice that if $\texttt{R}$ appears right after some $\texttt{L}$, an operation can be used to transform $\texttt{LR}$ into $\texttt{RL}$, and we have concluded before...
large sum and then we excluded all subsets which are less than some other includedset. So, the max, tournament graph, in the topological order ($S_1$ is the "highest" component, while $S_k$ is the "lowest, The second step is to sort all players by out-degree in non-increasing order and maintain the

Full text and comments »

Tutorial of Hello 2023
  • Vote: I like it
  • +356
  • Vote: I do not like it

63.
By awoo, history, 6 years ago, translation, In English
Educational Codeforces Round 91 Editorial [problem:1380A] Idea: [user:BledDest,2020-07-12] <spoiler summary="Tutorial"> [tutorial:1380A] </spoiler> <spoiler summary="Solution (Ne0n25)"> ~~~~~ #include <bits/stdc++.h> using namespace std; const int N = 1000; int n; int a[N]; void solve() { cin >> n; for (int i = 0; i < n; ++i) cin >> a[i]; for (int i = 1; i < n - 1; ++i) { if (a[i] > a[i - 1] && a[i] > a[i + 1]) { cout << "YES" << endl; cout << i << ' ' << i + 1 << ' ' << i + 2 << endl; return; } } cout << "NO" << endl; } int main() { int T; cin >> T; while (T--) solve(); } ~~~~~ </spoiler> [problem:1380B] Idea: [user:adedalic,2020-07-12] <spoiler summary="Tutorial"> [tutorial:1380B] </spoiler> <spoiler summary="Solution (adedalic)"> ~~~~~ fun main() { val winBy = mapOf('R' to 'P', 'S' to 'R', 'P' to 'S') repeat(readLine()!!.toInt()) { val s = readLine()!! val maxCnt = s.groupingBy { it }.eachCount().maxBy ...
Now we have all $cnt_i$ set now. The only thing left is to assign chests optimally. Write down the

Full text and comments »

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

64.
By Tareq_Ali, history, 3 weeks ago, In English
Organized C++ Ordered Set and Multiset Hello everyone! After a long break from competitive programming, I’m back with something I wanted to have ready in my template: an ordered set and multiset with a clean member-function interface. One of the main reasons I created this project was to support the competitive programming community at Latakia University (Previously Tishreen University). I wanted contestants to have a reusable ordered-set and multiset template they can keep in their own templates and adapt to their problems. The project is **Organized C++ Ordered Set**. You can write `ordered_set<int>` or `ordered_multiset<int>`, access sorted ranks with `s[i]`, and use normal-looking bounds and erasure functions. It uses GNU PBDS with a strict comparator, including when duplicates are present. [Code, examples, and complete API reference](https://github.com/Tareq-Ali-1998/Organized-CPP-Ordered-Set) [GitLab mirror](https://gitlab.com/tareqali591998/organized-cpp-ordered-set) ## Usage first ```c++ ordere...

Full text and comments »

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

65.
By _ja, 5 months ago, In English
Order Capital Round 2 (Codeforces Round 1104, Div. 1 + Div. 2) Hello / Selamat sejahtera / 你好 Codeforces! ================== <div style="float:right; margin-left:15px; width:200px;"> <img src="/predownloaded/80/7f/807f4117591c25d5cd189f81cecec2afc0afceef.jpg" width="200px" > <div style="font-size:smaller; text-align:center;"> Crochet penguin plushie,<br> credits to [user:gry3125,2026-06-15] </div> </div> We, [user:quacksaysduck,2026-06-15] and [user:_ja,2026-06-15] are excited to invite you to [contest:2237], which will start on [contest_time:2237]! In this round, you will help Ja the Ghost and Quack the Duck on their daily shenanigans. <strike>This round will be in the format of an IMO mock.</strike> There will be $9$ problems which you will have to solve in $3$ hours. This round will be combined for Division 1 and Division 2 and will be rated for everyone. Please note that this contest contains **at least one run-twice problem,** so please read the guide for [run-twice problems](https://codeforces.me/blog/entry/14799...
Order Capital Round 2 (Codeforces Round 1104, Div. 1 + Div. 2), with **Order Capital Round 2**🚀._ _We’ve prepared a fresh set of problems with interesting, _We’ve prepared a fresh set of problems with interesting ideas and a few surprises along the way

Full text and comments »

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

66.
By dreamoon_love_AA, 12 years ago, In English
If you ask me how to improve your algorithm competition skill, I will give you the link of this blog. In recent one year, I don't know why but there are many people sending messages to me for asking similar problems. So I decide to create this blog. In the beginning, I must say, you may feel disappointed after reading this blog. Because I don't have any special tips. My study method has wasted me many many time. There are some basic points I think you have known. 1. **Practice, practice, and practice.** I take so many time to think and solve problems. I think I do it 5 hours a day on average. 2. **Make friends with many awesome people.** I know many awesome people. For example, [user:arosusti,2015-02-24], [user:kelvin,2015-02-24], peter50216([user:0O0o00OO0Oo0o0Oo,2015-02-24]), [user:seanwu,2015-02-24], [user:Shik,2015-02-24], [user:takaramono,2015-02-24], [user:tmt514,2015-02-24], ... If I have some problems that I can't solve in few weeks, I can almost get solution from my friends. Then I say what I do for training myself. When I do problems. There are two possi...
possible order for choosing problem. 1. Start from most people solved one. 2. Solve consecutive

Full text and comments »

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

67.
By cry, 3 years ago, In English
Codeforces Round 887 (Div 1, Div 2) Tutorial We hope you enjoyed these problems :) This contest has been in the works for almost a year. <spoiler summary = "About the Authors"> This round was mostly made possible by problemsetters from the [CerealCodes](https://www.cerealcodes.org/) initiative! CerealCodes is an organization based in the United States dedicated to running high quality competitive programming contests. You can check out our previous contest [here](https://codeforces.me/gym/103886). </spoiler> **UPD: D1D Editorial have been updated** **UPD 2: D1D Editorial now has images by [user:EmeraldBlock,2023-08-01]. As an apology gift for being so slow, the image generator is programmatic and available [here](https://artofproblemsolving.com/texer/codeforces).** #### [problem:1853A] Problem Credits: [user:buffering,2023-06-02] Analysis: [user:buffering,2023-06-02] <spoiler summary="Hint 1"> To make $a$ not sorted, we just need to pick one index $i$ so $a_i > a_{i + 1}$. How do we do this? </spoiler...
Thus, we can just try every possible $x$ in decreasing order and maintain the filled indices as we

Full text and comments »

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

68.
By Geothermal, history, 6 years ago, In English
AtCoder Beginner Contest 172 English Solutions #A &mdash; Calc Just directly print the given sum. Time Complexity: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc172/submissions/14750143) --- #B &mdash; Minor Change The answer is simply the number of positions $i$ for which $S[i] \neq T[i]$. This is because we must make a move fixing each of those position, and each move can only make $S[i] = T[i]$ for one new position. Thus, we can iterate through the positions and count those where $S$ and $T$ differ, printing the total as our answer. Time Complexity: $O(|S|)$. [Click here for my submission.](https://atcoder.jp/contests/abc172/submissions/14750027) --- #C &mdash; Tsundoku We apply two pointers. Iterate over the number of books to be read from desk A in decreasing order, starting with the greatest number of those books we could read without exceeding $K$ minutes. Maintain the sum of all books to be read from desk A. Then, while we can do so without exceeding $K$ minutes, add ...
$ in order to guarantee that $x < A[1]$, allowing us to set $a$ to $\max(a, b)$.

Full text and comments »

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

69.
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...
item by its ordinal number (ie, order statistic in the set). And then I remembered that in the

Full text and comments »

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

70.
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...
consider the segments in decreasing order of $l$. Let's assume we are considering segment $i$. If there is

Full text and comments »

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

71.
By bicsi, history, 6 years ago, In English
I might get stigmatized for this, but here it goes Recently, Moscow Fall Workshops has taken place (it ended about one week ago), and I wanted to address some issues that came into my mind during that period. As you might notice, it took me some time to build the courage and get in the right mindset to write about this. First of all, I want to say that I am a huge supporter of programming camps and, in general, initiatives to enhance the joy of doing competitive programming and I respect the efforts of building communities around CP. I have always had a kind of excitement when thinking about participating in programming camps (Petrozavodsk, Moscow Workshops, etc.) and their “hardcore” style with lots of contests. I therefore appreciate the immense efforts of organizers, problem setters, and testers, when preparing this camp. ### Main point Coming towards the main point of the blog, I felt that the last programming camp was a bit… underwhelming. Moreover, I’m having a hard time trying to justify the costs of doing such a camp,...
that making a good problem set is very time consuming and involves a lot of hard work. However, after

Full text and comments »

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

72.
By AnandOza, history, 6 years ago, In English
Atcoder Beginner Contest 171 — Unofficial English Editorial Hi all, [Atcoder Beginner Contest 171](https://atcoder.jp/contests/abc171) was today. I wrote an unofficial English editorial. Hope it helps! ### [A: αlphabet](https://atcoder.jp/contests/abc171/tasks/abc171_a) We simply write an if statement. Runtime: $\mathcal{O}(1)$. <spoiler summary="Sample code"> ~~~~~ char x = in.next().charAt(0); if (x >= 'A' && x <= 'Z') out.println("A"); else out.println("a"); ~~~~~ </spoiler> ### [B: Mix Juice](https://atcoder.jp/contests/abc171/tasks/abc171_b) We want to buy the cheapest fruits, so we can sort the array and then pick the first $K$ fruits. Runtime: $\mathcal{O}(N \log N)$. <spoiler summary="Sample code"> ~~~~~ int n = in.nextInt(), k = in.nextInt(); int[] p = in.readIntArray(n); Util.safeSort(p); // this shuffles and sorts to avoid hacks long answer = 0; for (int i = 0; i < k; i++) { answer += p[i]; } out.println(answer); ~~~~~ </spoiler> ### [C: One Quadrillion and One Dalmatia...
In order to process a query, we move everything from $B_i$ to $C_i$ and update our sum

Full text and comments »

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

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

Full text and comments »

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

74.
By Vladosiya, 5 years ago, translation, In English
Codeforces Round #762 (Div. 3) Hello! [contest:1619] will start at [contest_time:1619]. You will be offered 7-8 problems with expected difficulties to compose an interesting competition for participants with ratings up to 1600. However, all of you who wish to take part and have a rating of 1600 or higher, can register for the round unofficially. The round will be hosted by rules of educational rounds (extended ACM-ICPC). Thus, solutions will be judged on preliminary tests during the round, and after the round, it will be a 12-hour phase of open hacks. You will be given 7-8 problems and 2 hours and 15 minutes to solve them. Note that the penalty for the wrong submission in this round (and the following Div. 3 rounds) is 10 minutes. Remember that only the trusted participants of the third division will be included in the official standings table. As it is written by link, this is a compulsory measure for combating unsporting behavior. To qualify as a trusted participant of the third division, you must: ...
**UPD 1:** The opinion of the testers about the order of problems turned out to be so heterogeneous

Full text and comments »

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

75.
By nik_exists, 10 months ago, In English
Some reflections as a round setter v2 + How to set a round This blog post is inspired by [user:RobinFromTheHood,2026-01-19]'s [blog post](https://codeforces.me/blog/entry/134377). Creating Problems ------------------ After [contest:2185] ended, I received **many** questions about how to write a contest along with how the proposal process works, so I thought that I might write a blog post all about it. I'll be mentioning different problems I made throughout the round setting process, and copying from [this post](https://codeforces.me/blog/entry/135218), I'll be denoting final problems in bold, and I'll be denoting the $n$-th iteration of a problem by putting that many apostrophes after it: e.g A' is the first iteration of problem A, A'' is the second, and so on. Similarly, I won't go into detail about why a problem wasn't used. I started competitive programming on Codeforces in the summer of 2024, though I had dipped my toes into it with some in person competitions and Advent Of Code before then; even before that, I used to practice c...
Some reflections as a round setter v2 + How to set a round, How to set your own contest ------------------ I'll be talking about Div3 / Div4 rounds below

Full text and comments »

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

76.
By SomethingNew, 4 years ago, In English
Codeforces Round #814 (Div. 1, Div. 2) Editorial Sorry for not very good samples, and late editorial. It was our first round, so it was wary stressful for us, But we hope you liked the problems despite this! [problem:1719A] <spoiler summary="Hint 1"> Try to look at the parity of $n, m$. </spoiler> <spoiler summary="Hint 2"> The player who wins does not depend on player's strategy. </spoiler> <spoiler summary="Hint 3"> The only thing that the winning player depends on is the parity of $n, m$. </spoiler> <spoiler summary="Tutorial"> Note that the game will end only when the chip is in the upper right corner (otherwise you can move it $1$ square to the right or up). For all moves, the chip will move $n - 1$ to the right and $m - 1$ up, which means that the total length of all moves is $n + m - 2$ (the length of the move is how much the chip moved per turn). Since the length of any move is odd, then after any move of Burenka, the sum of the lengths will be odd, and after any move of Tonya is even. So we can find...
In order to find a set of prime numbers on a segment, you can use the MO algorithm.

Full text and comments »

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

77.
By sammyuri, 15 months ago, In English
Codeforces Round 1044 (Div. 2) Editorial Thank you for participating in my round! I hope you all enjoyed it. <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2133A] <spoiler summary="Hint 1"> What does the speed of each gear depend on? </spoiler> <spoiler summary="Solution"> Suppose we have some arrangement of gears where gear $i$ from the left has $b_i$ teeth. Then the speed of gear $n$ is $1 \cdot \frac{b_1}{b_2} \cdot \frac{b_2}{b_3} \cdot \ldots \cdot \frac{b_{n-1}}{b_n}$. Notice that most of the fractions cancel, leaving only $\frac{b_1}{b_n}$. So in fact, the speed of gear $n$ depends only on $b_n...
To reconstruct the set of detonated creepers, we can also have a predecessor array storing which

Full text and comments »

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

78.
By Um_nik, history, 14 months ago, In English
On AI ruining "solving math problems with computer" [a year later] I guess you were right in the part "a year from now LLMs will solve problems on your level". You were also saying something along the lines of "you'll change your mind when it starts affecting you". In this part, you were wrong. Cheaters always existed, and they always will. LLMs make it easier to cheat, true. There is no way of completely preventing LLM cheating (or any other kind of cheating) in online competitions. I just coordinated the round everyone is buzzing about, so I can with confidence say that in the CF rules for coordinators and authors, there isn't anything about making problems LLM-proof. Not for easy problems, not for hard problems, nothing. And I doubt any such rules will appear. LLMs are forbidden by the rules, that's that. So we, as honest participants (yes, I will assume that you are an honest participant, otherwise this blog is not applicable to you and I don't care about you), will have to accept that some problems in the future rounds will be LLM-able, ...
, and there will be people cheating using an LLM and getting Accepted verdicts on someset of

Full text and comments »

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

79.
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; ...
] && r2[i] <= 2 && c1[i] <= c2[i]); --c1[i]; } vector order(n); iota

Full text and comments »

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

80.
By dragonslayerintraining, history, 7 years ago, In English
Dynamic convex hull implementation I finally figured out a nice way to implement dynamic convex hull with a reasonable constant factor! I expect this will be "well known in China" though. Consider the problem of finding [nested convex hulls](https://en.wikipedia.org/wiki/Convex_layers) in $O(n\log^2{n})$. The simplest way I know of is to make a convex hull data structure that supports point deletions, which is what I do here. It should be possible to extend this implementation to handle insertions as well. This implementation is based on this [paper](https://www.sciencedirect.com/science/article/pii/002200008190012X) by Overmars and van Leeuwen that describes a data structure for online fully dynamic convex hull in $O(\log^2{n})$ per operation. Directly implementing that is complicated and has a bad constant factor, so we'll do it a bit differently using ideas from [user:FizzyDavid,2020-04-13]'s [solution](https://codeforces.me/blog/entry/72611?#comment-569105) to [1270H](https://codeforces.me/contest/1270/probl...
- If $a\ne b$ ($p$ is not a leaf) and $a,b,c$ is in counterclockwise order, we can discard $b$ and, - If $c\ne d$ and $b,c,d$ is in counterclockwise order, we can discard $c$ and all points below it

Full text and comments »

81.
By bestial-42-centroids, history, 16 months ago, In English
Codeforces Round #1039 — Editorial Thank you for participating in our round ! We hope you enjoyed our problems. Feel free to discuss them in the comment section :) /!\ The solution codes will be available in a few minutes UPD: The solution codes have been added ! UPD2: The solution codes links are fixed ! Sorry for the inconvenience. [problem:2128A] <spoiler summary="Solution"> Let's say a bag is expensive if $a_i > c$ and free if $a_i \leq c$. First, observe that as long as there is at least one free bag remaining, we should destroy a free bag. We will perform all expensive destructions at the end. The goal is to perform as much free destructions as possible. When there are multiple free bags, which one to choose? The bigger a bag is, the less time you have to destroy it before it becomes expensive. Hence, at each second, you should destroy the biggest remaining free bag. This process can be naively simulated in $\mathcal{O}(n^2)$, which was sufficient under given constraints. If you sort the arr...
ordered set (or you can also use two range sum point update queries to simulate the \text{big} and

Full text and comments »

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

82.
By yse, 7 months ago, In English
Codeforces Round 1096 (Div. 3) — Editorial Thanks for participating in the contest. I hope you enjoyed the problems :) <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | H | |----------------------------------|-----|-----|------|------|------|------|------|------| | [user:Argentum47,2026-04-23] | 800 | 800 | 900 | 1200 | 1500 | 1700 | 1900 | 2200 | | [user:simplelife,2026-04-23] | 800 | 800 | 1000 | 1300 | 1500 | 1800 | 1800 | &mdash; | | [user:lina_os,2026-04-23] | 800 | 800 | 1000 | 1100 | 1400 | &mdash; | &mdash; | &mdash; | | [user:-firefly-,2026-04-23] | 800 | 800 | 900 | 1400 | 1600 | 1900 | 2000 | 2300 | | [user:Syrianooo,2026-04-23] | 800 | 800 | 900 | 1200 | 1300 | &mdash; | &mdash; | &mdash; | | [user:Mousa,2026-04-23] | 800 | 800 | 1000 | 1300 | 1600 | 2000 | 2300 | 2100 | | [user:yse,2026-04-23] | 800 | 800 | 1000 | 1200 | 1400 | 1600 | 1900 | 2100 | </spoiler> <spoiler summary="Ra...
Fenwick Tree and coordinate compression, or using an ordered set with order statistics., ~~~~~ // written by omsincoconut

Full text and comments »

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

83.
By physics0523, history, 3 years ago, In English
TheForces Round #26 Editorial [problem:104802A] Writer: [user:wuhudsm,2023-11-14] <spoiler summary="Editorial"> We use two pointers to solve this problem. Set $l=1$ and $r=n$ initially. - If $a_l=a_r$, <code>l++,r--;</code> - If $a_l<a_r$,split $a_r$ into $a_r-a_l$ and $a_l$, <code>r--;</code> - If $a_l>a_r$,split $a_l$ into $a_r$ and $a_l-a_r$, <code>l++;</code> When $l \geq r$,the process ends. </spoiler> <spoiler summary="Rate the problem"> Good problem! : Average problem : Bad problem... : </spoiler> [problem:104802B] Writer: [user:pavlekn,2023-11-14] <spoiler summary="Editorial"> Let $M$ be the initial mass of the bus with all passengers: $M = w + \sum_{i = 1}^{n}{m_i}$. Let $F$ be the total force of the pushers, initially, $F=0$. Imagine getting out the $i$-th passenger out of the bus, then $M$ is decreased by $m_i$, while $F$ is increased by $f_i$. Hence, $M - F$ is decreased by $m_i + f_i$. Clearly, we want to make ...
For implementing, we can use set or ordered set (policy-based data structure), and can start

Full text and comments »

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

84.
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 ...
Consider all subsets of the original set in which tasks, in last question and $B$ numbers are not. In order to calculate our dp, if we ask about someset

Full text and comments »

85.
By thanhchauns2, history, 4 years ago, In English
Some short snippets that will shorten your time. Hi there! ================== In this blog I would like to share some of the code snippets that can shorten your time in future contests. Of course, I'll ignore the "international snippets" <spoiler summary="like:"> ~~~~~ #define SZ(a) (ll)a.size() #define FOR(i,a,b) for (ll i=(ll)a; i<=(ll)b; i++) #define f first #define mp make_pair #define s second #define p pair #define all(C) C.begin(), C.end() ~~~~~ </spoiler> Sometimes you may find typing the identical thing again and again is boring, this blog is about some method that a few people use to get rid of them (or just only me). So, let's get started. #### Scanning/printing the whole vector in a single `std::cin/std::cout` <spoiler summary="Snippet"> ~~~~~ template<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;}; template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {for(auto &x : a) out << x << ' '; return out;}; ~~~~~ </spoiler> ...
#### Ordered set and ordered multiset

Full text and comments »

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

86.
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...
master in order to propose the set on Codeforces.

Full text and comments »

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

87.
By de_sousa, history, 11 months ago, In English
An Imprecision Problem (Small Imprecision Contest Editorial) This is the editorial for my **Small Imprecision Contest** ( https://codeforces.me/gym/106258 ). It is more detailed than regular editorials and is meant to be a standalone blogpost, so it should still be an interesting read even if you didn't participate. This problem has been passed around as a funny concept in some Discord servers, and it was first proposed by [user:pajenegod,2025-12-25] in 2023. This problem doesn't belong in regular competitions, but regardless, I thought it was too cool to not exist, and at the same time, solving it requires some advanced floating point knowledge and intuition; this blogpost is more detailed than usual in an attempt to create a good introduction to these concepts. *With this blogpost I would like to participate in https://codeforces.me/blog/entry/149422 , a cool initiative by [user:ntherner,2025-12-25] that is rewarding interesting Codeforces blogposts. If you have something interesting to share, please give it a read.* I...
- For all positions $p$ from $1$ to $n$, we set $b_p$ to $2^{24}$ and all other positions to $1, - Let's consider positions $p$, $q$ and $r$. - We set $b_r$ to $z$, and the other two to $x$ and

Full text and comments »

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

88.
By ivan100sic, 9 years ago, In English
Interesting implementation of Persistent Sets *Do you really hate tree rotations? This blog post is for you!* Recently, I've been solving [problem:768G] and I came up with a solution which is so ridiculously overengineered that I think it deserves its own blog post! I don't want to go over all the details of the solution. Instead, I want to demonstrate a nice way to implement and apply Persistent Set and Persistent Array data structures and share a few ideas some may find interesting. Basically, what I wanted to do is compute for each node $x$ of the rooted tree a set, which would contain the sizes of all subtrees of $x$. In other words, if we denote $sz(y)$ &mdash; the size of the subtree rooted at $y$, I want to compute the set $S(x) = \{sz(y) | y \in subtree(x)\}$ for all $x$. We also want this set to have some `lower_bound` and `upper_bound` functionality. Obviously, just storing these sets in a normal way would require $O(n^2)$ memory, so we need another approach. Let's use the same idea that we use when building ...
easy to implement the order statistic query (find the kth largest element in theset). Remark 2, Remark 1. It's also relatively easy to implement the order statistic query (find the kth largest, `this_t` is the alias for `paorder>`, the data type of the class for persistent sets. This is

Full text and comments »

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

89.
By tibinyte2006, 4 years ago, In English
[Tutorial] Cartesian tree and some related problems The Cartesian Tree is a useful concept for solving some problems which revolve mainly about thinking of the range of maximality of elements. It also provides a sort of "persistance" to the algorithm of monotonic stack, if you will. In this blog, we will learn what a Cartesian Tree is, how to construct one and solve some related problems to strengthen our understanding. Let's begin! <hr> #### What is a Cartesian Tree? Let's consider an array $a$ where all values are distinct. The Cartesian Tree for the array $a$ is a binary labeled tree build recursively from the function $get(l,r)$ which constructs our desired tree from the subarray $l...r$. Now let's define $get(l,r)$ - First root the tree at index $i$ such that $a_i = min(a_l,a_{l+1},...,a_r)$. Note that because all values are distinct, $i$ will always be unique. - The aforementioned index will become the root of the Cartesian Tree. It's left and right subtrees will be recursively generated by $get(l,i-1)$ and $get(...
- Corollary: Let $S_i$ be a set where $x \in S_i$ if and only if there exists $1 \le l \le i \le r

Full text and comments »

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

90.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 139 English Solutions #A &mdash; Tenki This is a fairly simple task--just iterate over all positions in the strings and count the ones where S[i] = T[i]. Runtime: $O(|S|)$. [Click here for my submission.](https://atcoder.jp/contests/abc139/submissions/7247680) --- #B &mdash; Power Socket Note that we already have one socket, so we need to fill $B-1$ more sockets. Additionally, each new outlet we add will take up one socket and add $A$ sockets, resulting in a net addition of $A-1$ sockets. We thus need to create at least $B-1$ sockets where each outlet gives us $A-1$ sockets, making our answer $\lceil \frac{B-1}{A-1} \rceil$. Since most programming languages use floor division, we can also express this as $\lfloor \frac{A+B-3}{A-1} \rfloor$. Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc139/submissions/7249379) --- #C &mdash; Lower We essentially use two pointers. Maintain the starting position at zero. Then, while the next position isn't hi...
After the set is empty, we must have either processed every match or encountered a cycle. In the

Full text and comments »

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

91.
By Stefan2417, history, 2 years ago, translation, In English
Codeforces Round #948 (Div. 2) Editorial We hope you enjoyed the problems. Problem [problem:1977A] was created by [user:Stefan2417,2024-05-27] and prepared by [user:alexchist,2024-05-27]. Problem [problem:1977B] was created by [user:alexchist,2024-05-27] and prepared by [user:Stefan2417,2024-05-27]. Problem [problem:1977C] was created and prepared by [user:Stefan2417,2024-05-27]. Problem [problem:1977D] was created and prepared by [user:alexchist,2024-05-27]. Problem [problem:1977E] was created and prepared by [user:Stefan2417,2024-05-27]. [problem:1977A] <spoiler summary="Tutorial"> Note that one action with the cube changes the parity of the number of cubes in the tower. Therefore, if the parities of $n$ and $m$ do not match, it is impossible to build the tower. Also, if $n < m$, the tower cannot be built either. In all other cases, it is possible to build a tower of height $m$ in $m$ operations, and then add and remove a cube until the operations are exhausted. </spoiler> <spoiler summary="Author...
the maximum antichain is equal to the minimum number of chains that cover the PartiallyOrdered Set., Notice that the reachability relation in a graph defines a [Partially Ordered Set](https

Full text and comments »

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

92.
By MikeMirzayanov, history, 11 years ago, translation, In English
How to come up with the solutions: techniques As I work with students I often face the situation when if a problem doesn't seem clear to a student at the first sight, it makes them unable to solve it. Indeed, you always hear about specific methods and techniques. But you don't hear about how to think in order to apply them. In this note I'll try to sum up my experience of solving programming contest problems. However, some pieces of advice will also be applicable for olympiads in mathematics and your first steps in academic research. So you've read a problem and you don't know how to solve it. Try the following techniques, some of them can often come handy. ##### Technique 1: "Total Recall" Try to remember some similar problems that you had to solve. Quite many problems do not have a brand new idea. So probably, you can use your experience of solving a similar problem to solve this one. ##### Technique 2: "From Specific to General" Let's say that you've found the solution for the problem (hurray!). Let's consider ...
methods and techniques. But you don't hear about how to think in order to apply them. In this note I'll

Full text and comments »

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

93.
By Timosh, history, 9 months ago, In English
Imagine not using ordered_set `std::set` is a powerful data structure: it allows to do insertions/deletions pretty fast, while also being able to access the smallest/biggest element. On top of that, you can also find the smallest element in the set which is greater than some $x$. If you can use it properly, it is already enough to solve some of the 1800-2000 rated problems. On the other hand, what could `ordered_set` possibly offer? It can do 2 things (other than `std::set`): - `st.find_by_order(x)` &mdash; returns the iterator of the $x$-th smallest element - `st.order_of_key(x)` &mdash; returns the number of elements less than $x$ (i.e. index of the smallest element $\ge x$) One of the basic applications of `ordered_set` would be counting the number of inversions of an arbitrary permutation. For comparison: #### Ordered set way ~~~~~ ordered_set<int> st; int ans = 0; for (int i = n - 1; i >= 0; i--) ans += st.order_of_key(p[i]), st.insert(p[i]); ~~~~~ #### Merge sort way ``` // to...
sets, and inserting each bit of the element being added to the corresponding ordered set. To get a sum, For comparison: #### Ordered set way

Full text and comments »

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

94.
By fchirica, 13 years ago, In English
Codeforces Round #225 Hello everyone! We invite you to participate at Codeforces Round #225, scheduled [Monday, 20th January at 7:30 PM MSK](http://www.timeanddate.com/worldclock/fixedtime.html?day=20&month=1&year=2014&hour=19&min=30&sec=0&p1=166). This is the third round I coauthor, along with [contest:341] (and of course Div. 2 version of contest) and [contest:327]. If you recall my old rounds, you'll see that main character is Iahub. The other writer of this round is... Iahub... the real person corresponding to "Iahub" character. Let me introduce you to Rares Buhai ([user:rares.buhai,2014-01-18]). He's the author of Div. 2 C / Div. 1 A, Div. 1 D and Div. 1 E. You can expect those problems to be interesting, coming from a [2 times IOI gold medalist](http://ioi.eduardische.com/people/2688) (being allowed to participate 2 more times). All other problems are created by me. I like them, but I wouldn't be objective if I said that they're interesting. Let's see if someone will think so after the contest ...
Like last time, I'll give you a little spoiler about the tasks. We tried to make the problemset as

Full text and comments »

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

95.
By neal, 8 years ago, In English
A brief overview of Round #503 (by SIS, Div. 1) Thanks to the _many_ authors of this contest ([all eight of them](http://codeforces.me/contests)) for a great set of problems! I'll sketch out the solution ideas for a few of them here: #### [problem:1019A] Let's assume our goal is to end the election with $v$ votes and determine the minimum cost to do so. First, we need to make sure every other party ends up with fewer than $v$ votes. To do this, we should bribe enough people in every party to get them down to $v - 1$ votes or fewer. We can do this greedily by bribing the cheapest people in the party. After that if we have $v$ votes (or more), we are done. Otherwise, we should repeatedly bribe the cheapest voters remaining until we get to $v$. Note that we can do this in $O(n)$ time rather than $O(n \log n)$ by using an $O(n)$ selection algorithm such as [nth_element](https://en.cppreference.com/w/cpp/algorithm/nth_element), though this wasn't necessary to pass the problem. Finally, simply loop over all possible values o...
We can perform a rotational sweep on the set of points, which lets us set up this height-sorted

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

98.
By TeaTime, 2 years ago, In English
Counting perfect matchings Thanks to [user:t.ravnushkin,2024-09-27] for helping in writing contents of this blog. Thanks to [user:Alexdat2000,2024-09-27] for proof-reading and to [user:bashkort,2024-09-27] for announcing the month of blog posts. Even though I have started writing this blog before the announcement it would have probably been left in a trash bin due to my laziness. # Introduction Matching is a beloved topic throughout competitive programming community due to its simple nature and fun applications. Matchings are not only useful in graph theory, but are also essential in topics such as game theory, partially ordered sets and combinatorics. In this blog we are gonna talk about less known applications of the subject. The main goal of the blog is explaining the intuition behind being able to associate the number of some combinatorial species to the amount of perfect matchings and understanding when it is possible to efficiently compute their counts. The blog mainly consists of two parts: ...
topics such as game theory, partially ordered sets and combinatorics. In this blog we are gonna talk

Full text and comments »

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

99.
By errorgorn, 3 years ago, In English
Confession: I sent problem H to goodbye Going to be 100% honest here, I sent problem H to goodbye. I feel really bad to authors of Goodbye 2023 for ruining their round, it seems the round would have been better by just removing H. As much as the community is out here roasting [user:74TrAkToR,2023-12-31], I also had a part to play in this contest. I wish to be as transparent as I can here without saying any classified information (apologies to [user:KAN,2023-12-31] and [user:74TrAkToR,2023-12-31] if anything here shouldn't be disclosed). To give some context, here is what went down in goodbye round from my perspective: - 13 days before contest: KAN asks me if I can source a 1E for goodbye. I asked traktor to send me the testing gym so that I could gauge how hard the 1E should be. He told me he will send me after he translates the statements. (UPD: Note that the IMO 1986 problem was already removed before this stage which is why a new 1E was needed, I never saw this IMO problem) - 11 days before contest: traktor send it...
to do when p has a small order modulo 998" . In a discord group chat with [user:endagorion,2023-12-31

Full text and comments »

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

100.
By cry, 22 months ago, In English
Codeforces Round 998 (Div. 3) Editorial <spoiler summary="Rating Predictions"> | Predictor | A | B | C | D | E | F | G | |--------------------------------------------|------|------|------|------|------|------|------| | [user:Proof_By_QED,2025-01-15] | 800 | 1000 | 1100 | 1300 | 1600 | 1900 | 2400 | | [user:cry,2025-01-15] | 800 | 1000 | 1000 | 1200 | 1700 | 2000 | 2400 | | [user:chromate00,2025-01-15] | 800 | 1000 | 1000 | 1400 | 1700 | 2000 | 2400 | | [user:DivinePunishment,2025-01-15] | 800 | 1200 | 1100 | 1200 | 1700 | 2000 | 2300 | | [user:-firefly-,2025-01-15] | 800 | 1000 | 1000 | 1400 | 1800 | 2000 | 2400 | | [user:Error_Yuan,2025-01-15] | 800 | 1100 | 1200 | 1600 | 1800 | 2100 | 2400 | | [user:macaquedev,2025-01-15] | 800 | 1000 | 1500 | 1400 | 1300 | 2000 | 1900 | | [user:In...
If the cows are not ordered correctly, we need to rearrange them. To construct the solution, find

Full text and comments »

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

101.
By tribute_to_Ukraine_2022, history, 7 years ago, In English
Ordered set mindfuck Let's write some simple code using policy based data structures ~~~~~ #include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; template <class c, class cmp = less<c> > using ordered_set = tree<c, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>; int main() { ordered_set<vector <int> > s; s.insert({1, 2, 6}); s.insert({1, 3, 3}); s.insert({2, 6}); cout << s.order_of_key({1, 3}) << endl; for (int x : *s.find_by_order(1)) cout << x << " "; cout << endl; } ~~~~~ Compiles and outputs: ~~~~~ 1 1 3 3 ~~~~~ So far so good, but let's try to compile it with -D_GLIBCXX_DEBUG. Now the compiler spews out an error containing: ~~~~~ /usr/include/c++/7/ext/pb_ds/detail/debug_map_base.hpp:208:7: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘const std::__debug::vector<int>’) std::cerr << __file << ':' << __line << ": check_key_exists " ~~~~~~...
Ordered set mindfuck

Full text and comments »

Tags c++
102.
By shorya1835, 20 months ago, In English
Editorial for Insomnia'25 [A \- XO-OR](https://codeforces.me/gym/590997/problem/A) <spoiler summary="Solution"> To solve this problem optimally, we need to ensure that we maximize the size of the set $S$ while satisfying the given constraints on XOR and OR operations. A necessary condition for a valid set is that $ y $ must be a **subset** of $ v $. In terms of bits, this means every bit that is set in $ y $ must also be set in $ v $. If $ y > x $, then at least one bit in $ y $ is missing from $ x $, making it impossible to construct a valid set where the XOR of elements results in $ y $. Thus, in such cases, the answer is immediately $ -1 $. To understand how we construct valid sets, consider forming all possible subsets of the bits set in $ v $. The total number of such subsets is $ 2^{pc} $, where $ pc $ is the number of set bits in $ v $. Each individual bit contributes exactly $ 2^{(pc - 1)} $ times across all subsets, meaning the overall XOR of the entire set cancels out to $ 0 $ when $ pc \ge...
segment using an ordered set.

Full text and comments »

Tutorial of Insomnia 2025
  • Vote: I like it
  • +73
  • Vote: I do not like it

103.
By GlebsHP, history, 11 years ago, translation, In English
Codeforces Round #327 problems analysis I like the idea of [user:Endagorion,2015-10-25] to supplement the problems analysis with small challenges, somehow related to the problem preparation, it's generalization, or more effective solution. Following this, some problems in this analysis are also complemented with this sort of tasks. Div. 2A (Wizards' Duel) ------------------ Idea of the problem: Roman Gusarev, development: [user:timgaripov,2015-10-25]. Let's start with determining the position of the first collision. Two impulses converge with a speed $p + q$, so the first collision will occur after $\frac{L}{p + q}$ seconds. The coordinate of this collision is given by the formula $x_1 = p \cdot \frac{L}{p + q}$. Note, that the distance one impulse passes while returning to it's caster is equal to the distance it has passed from the caster to the first collision. That means impulses will reach their casters simultaneously, and the situation will be identic to the beginning of the duel. Hence, the second collision ...
substring of $s_1$. That means the graph of substring relation defines a partiallyordered set.

Full text and comments »

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

104.
By FairyWinx, 3 years ago, translation, In English
Codeforces Round #926 (Div. 2) Editorial. Problem A. <spoiler summary="Solution"> $a_2 - a_1 + a_3 - a_2 + \ldots + a_n - a_{n - 1} = a_n - a_1$. So we just need to maximize this value, which means the answer is the maximum number in the array minus the minimum. </spoiler> ------------------------------ Problem B. <spoiler summary="Solution"> Let's notice that each cell intersects with no more than two diagonals, so the answer to the problem is at least $\frac{k + 1}{2}$. Claim: Let's look at the construction where we color all cells in the first row and leave only two side cells uncolored in the last row. Then each of these cells corresponds to exactly two diagonals. And if $k \leq (2n - 2) * 2$, then the answer is exactly $\frac{k + 1}{2}$. Now let's notice that if we color $2n - 1$ or $2n$ cells, then one or two cells will correspond to exactly one diagonal respectively, because in this case we must color the side cells, as they are the only diagonals not touched, but they are already covered by anoth...
Let $dp[mask]$ be the minimum number of edges that need to be removed in order for at least one

Full text and comments »

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

105.
By Sul_A., history, 18 months ago, In English
New CSES Tasks Editorials Editorial for some of the new CSES tasks. Tasks that are trivial or too similar to already existing tasks are not included. Every time I solve a new nontrivial task, I will add it here. **NOTE: ONLY READ THE SOLUTIONS IF YOU ARE COMPLETELY STUCK AND OUT OF IDEAS. CSES tasks are the kinds of tasks you can solve at a random time by random chance. You might read a task today and solve it next week. Or next month. Or next 3 months. So read at your own risk.** ## Sorting & Searching <spoiler summary="Distinct Values Subsequences"> For each value $x$, we can include $0$ or $1$. If $f(x)$ is the number of times $x$ appears in the array, Then there are $f(x) + 1$ ways to pick $0$ or $1$ occurrences of $x$. Since every value is independent of every other values, we will take the product of $f(x) + 1$ over all $x$. This can be done with `std::map` or sorting. </spoiler> ## Dynamic Programming <spoiler summary="Mountain Range"> Let $L_i$ be the nearest greater element o...
This can be done by maintaining the number of inversions and an ordered set.

Full text and comments »

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

106.
By TryOmar, 3 years ago, In English
Ordered Set with Custom Sorting Operator in C++ ## Ordered Sets in C++ In C++, ordered sets can be created using special code templates. ~~~~~ #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template<class T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template<class T> using ordered_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>; ~~~~~ Two primary structures are introduced: - `ordered_set` maintains sorted unique elements in ascending order using `less` comparison. - `ordered_multiset` allows duplicates using a `less_equal` comparison, preserving the sorted order. ### Fucntions In addition to normal set operations, the ordered set supports: - `order_of_key(k)`: Gives the count of elements smaller than `k`. &mdash; O(log n) - `find_by_order(k)`: Returns the iterator for the `k`th element (use `k = 0` for the first element). &mdash; O(log n)...
Ordered Set with Custom Sorting Operator in C++, descending order for set or multiset., sorted order. ### Fucntions In addition to normal set operations, the ordered set supports, ## Ordered Sets in C++ In C++, ordered sets can be created using special code templates., - `ordered_multiset` allows duplicates using a `less_equal` comparison, preserving the sortedorder., - `ordered_set` maintains sorted unique elements in ascending order using `less` comparison., In addition to normal set operations, the ordered set supports:, ordered multiset. It ensures that duplicate elements are retained while maintaining the desired sorting

Full text and comments »

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

107.
By Zlobober, 12 years ago, translation, In English
Разбор VK Cup Round 2 [problem:532A] -------------- We can add $n-k$ miners with height $0$ and it won't affect answer. So we can assume that numbers of miners and caves are the same. For every cave let's define $t_i$ as maximal possible height of miner working in cave $i$ if we wouldn't change any cave. We can calculate it from root to leaves with line $t_i = min(t_{father}, h_i)$. Let's say we don't change anything. We will try to assign all workers if it's possible or to do the best possible assignment otherwise &mdash; the one where there are few free (not occupied) caves and they are high (value $t_i$ is big). I will say later why we want them to be high. Formal definition (you don't have to read the next paragraph): For every assignment let's sort free caves by $t_i$. In the best assignment number of free caves is minimal possible. And for every position in such a list free cave in the best assignment has value $t_i$ not lower than in any other assignment. It can be proven that best possi...
every order of iterating over caves. And every order gives us the same set of free miners (but not

Full text and comments »

Tutorial of VK Cup 2015 - Round 2
  • Vote: I like it
  • +123
  • Vote: I do not like it

108.
By smax, 4 years ago, In English
[Tutorial] Fully Dynamic Trees Supporting Path/Subtree Aggregates and Lazy Path/Subtree Updates Hey everyone! Usually when I post stuff on CF I just drop an external link to my blog, but this time I would like to also paste the same content natively on CF to see if it leads to more engagement. You can read the exact same article on my blog [here](https://mzhang2021.github.io/cp-blog/ds5/). Also, special thanks to [user:alien_lover,2022-06-10] and [user:gabrielwu,2022-06-10] for proofreading. --- ## Motivation We will solve **[this problem](https://dmoj.ca/problem/ds5)**. ## Prologue The original name of this problem is [SONE1](https://darkbzoj.cc/problem/3153), originating from the fiery depths of Chinese OI. Amazingly, the Chinese have figured out how to augment the link/cut tree to solve this problem (ref [1](https://www.cnblogs.com/clrs97/p/4403244.html), [2](https://blog.csdn.net/iamzky/article/details/43494481)). Maintaining subtree aggregates with a LCT isn't difficult, and there's a well-known [Codeforces article](https://codeforces.me/blog/entry/67637) ...
partition of nodes, because otherwise there's no way to properly order the combination of lazy values

Full text and comments »

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

109.
By Geothermal, history, 7 months ago, In English
My Solutions to Spectral::Cup 2026 Round 1 (CF Round 1094) Since the editorial for today's Div. 1 hasn't been published yet, I thought I'd share solution sketches. Some of these won't include all of the specific details, but hopefully they should communicate the main ideas. (I didn't compete officially, but I got AC on all of the problems using the below approaches, so I'm fairly confident in correctness.) Feel free to leave questions below and I'll respond if I have time. ## A &mdash; A Wonderful Contest If any problem has $100$ subtasks, the answer is yes: we can achieve an arbitrary score by solving some of the other problems fully and by solving the right number of subtasks of the $100$-subtask problem. Otherwise, there is no way to achieve a score of 1, so the answer is no. ## B &mdash; Artistic Balance Tree Note that each of the reversal operations swaps odd positions with odd positions and even positions with even positions, as $u-i$ and $u+i$ differ by $2i$ and thus have the same parity. Thus, when we are to mark an od...
want to find $dp_n$. To transition, starting from a given $i$, iterate over $j$ in increasingorder

Full text and comments »

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

110.
By wangmarui, history, 10 months ago, In English
Hello 2026 Editorial We'd like to thank you all for participating in the contest, and hope you enjoyed it. Any feedback would be appreciated! <spoiler summary="Rate The Contest!"> - Great contest - Good contest - Average contest - Bad contest </spoiler> ## [2183A &mdash; Binary Array Game](https://codeforces.me/contest/2183/problem/A) Idea & Preparation: [user:wangmarui,2025-12-23] <spoiler summary="Rate The Problem!"> - Good Problem - Okay Problem - Bad Problem - Didn't Solve </spoiler> <spoiler summary="Hint 1"> If the sequence $a$ consists entirely of $1$ s, what will Alice do? </spoiler> <spoiler summary="Hint 2"> Consider discussing the values of $a_1$ and $a_n$. </spoiler> <spoiler summary="Solution"> First, if the entire sequence consists of $1$ s, Alice wins immediately by operating on the whole sequen...
their initial positions. Since the relative order of the snakes remains unchanged, performing

Full text and comments »

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

111.
By OrderCapital, history, 5 months ago, In English
Order Capital is back with Round 2 <img alt="Order Capital" src="/predownloaded/00/3e/003eef1043e9506ad4620583c5be192631830899.png" style="float:right;height: 200px; margin: 10px; max-width:40%;"/> ### &#128075;Yo Codeforces! Hello from **Order Capital**! Last year we launched our very [first Codeforces contest](https://codeforces.me/blog/entry/144537) and the response was way beyond our expectations. So we had no choice but to run it back! For those who don’t know us yet: [Order Capital](https://ordercapital.com/) is a group of companies specializing in software development and automated trading. We combine modern technology and research to make data-driven decisions in quantitative trading and explore new opportunities for business growth. &#128640; Introducing: [contest:2237]. This time we’ve prepared: - a new set of problems; - plenty of interesting ideas; - a few unexpected twists. Whether you're aiming for a new rating milestone, looking for a good challenge, or simply enjoy...

Full text and comments »

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

112.
By aryanc403, 5 years ago, In English
Power series on sets? (Added one example) Update 2 &mdash; Thanks ~adamant,2021-06-25 for his [Subset convolution interpretation](https://codeforces.me/blog/entry/92153) blog. It does simplifies a lot of things. Update 1 - Let's consider this problem - We have a function `subset_convolution(A,B)` it gives us [Subset Sum Convolution](https://codeforces.me/blog/entry/72488) of two sets $A, B$. Let's say we array $A$ with $A[0]=1$ and we want to find `A^K` defined as $A$ convoluted with itself $K$ times. `A^2 = subset_convolution(A,A)` `A^3 = subset_convolution(A^2,A)` ... `A^k = subset_convolution(A^{k-1},A)` The best I can think right now is using something on lines of fast exponential to achieve $O(log K*N^2*2^N)$ time where $2^N$ is the size of A. Also, there exist some solutions $O(N^3*2^N)$ using the fact that the majority of the multiplications will be with A[0] and permutations & combinations. But it can be done in $O(N^2*2^N)$ using tricks well known at some pla...
; Just me rambling about the old ARC problem I was solving for the last 3 days. Something "set power, ordered partitions in that logarithm and dividing by $|P|!$, while counting them as unordered would

Full text and comments »

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

113.
By YMSeah, history, 6 years ago, In English
Ordered Set and Multiset Alternatives for Languages Without Built-In Libraries I have been doing competitive programming for some months now. While attempting problems above 1800 in difficulty, I noticed that some of them required the use of ordered sets/multisets that support lookup, addition and deletion of elements in O(log(n)) time. Their solutions usually involve the use of std::set or std::multiset in C++. However, I code primarily in Python and there are no built-in packages available on Codeforces. Normally outside of Codeforces I just import sortedcontainers.sortedlist which I use like an Order Statistic tree. Here I discuss some strategies which I have used to overcome these issues. I hope that it helps others who are stuck so that they do not give up on their favourite languages. For C++ users, this may not be as useful, but you can still see how alternative data structures may be used to solve problems. The example I use here is CSES &mdash; Concert Tickets (for those with no CSES account, see [here](https://www.technicalkeeda.in/2020/10/concert-ti...
Ordered Set and Multiset Alternatives for Languages Without Built-In Libraries, OrderedList data structure. By the way, the **OrderedList** is my implementation of theOrder Statistic, deleted), use a sum Segment Tree and set index to 1 if element is present, and 0 if element is deleted, in difficulty, I noticed that some of them required the use of ordered sets/multisets that support, **Method 3: Actually using a self-implemented B-tree or Order Statistic Tree** ------------------------------------------------------------------------------, **Method 3: Using some sort of Order Statistic Tree (PyRival's SortedList)** : [submission, EDIT: [user:rishabnahar2025,2021-03-31] has a good suggestion for an Order Statistic Tree template, If you want to search for next smallest to the right, use a minimum segment tree,set value to inf

Full text and comments »

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

114.
By dmkozyrev, history, 4 years ago, translation, In English
I have merged lower_bound and order_of_key into a single method in C++ ordered_set Hi everyone! I took an [ordered_set](https://codeforces.me/blog/entry/11080) in C++ (i.e. `__gnu_pbds::tree<...>` from GNU C++ Standard Template Library with implemented Policy-Based Data Structures) and added 6 new methods to derived class: 1. `lower_bound_with_order` -> iterator to minimal element such `>=` than given key + its index in the set (its order); 2. `upper_bound_with_order` -> iterator to minimal element such `>` than given key + its index in the set (its order); 3. `count_less` -> number of elements which are less than given element; 4. `count_less_equal` -> number of elements which are less or equal than given element; 5. `count_greater` -> number of elements which are greater than given element; 6. `count_equal` -> just a number of elements which are equal to given element. Advantages of (1) and (2): it is implemented in a single traversal of a tree ($\log{N}$). If you will call `lower_bound` firstly, and call `order_of_key` secondly, then you w...
= 0; i < 10; i += 2) vec.push_back(i); OrderedSet set(vec.begin(), vec.end, the set (its order);, , order = 5 test: test reversed set: 8 6 4 2 0 lower_bound_with_order: -1: lb = 1000000007, test: test reversed set: 8 6 4 2 0 lower_bound_with_order: -1: lb = 1000000007, order, ~~~~~ test: test sorted set: 0 2 4 6 8 lower_bound_with_order: -1: lb = 0, order = 0

Full text and comments »

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

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

Full text and comments »

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

116.
By SlavicG, history, 5 years ago, In English
Merging Queries Trick Credits to [user:VPurice,2022-03-07] for teaching me this trick. #### Introduction Recently I learnt an interesting trick I wanted to share with others. I'm not sure if this trick is well known, but I didn't know about it and didn't find any other articles on it so decided to write this blog. #### Problem statement We have a connected undirected graph with $n$ nodes and $m$ edges between them, each node having a value $w_i$ ($1 <= n, m <= 10^5$), ($1 <= w_i <= 10^9$). Let's denote $f(a, b)$ as the minimum value of a node on a path from node $a$ to node $b$. We have to answer $q$ queries about this graph. Each query contains $2$ nodes $a$, $b$ and asks for the maximum $f(a, b)$ over all possible paths from node $a$ to node $b$. ($1 <= q <= 10^5$). #### Notes This problem can be solved in another (more optimal) way, which is described in these comments: [1](https://codeforces.me/blog/entry/100666?#comment-893646), [2](https://codeforces.me/blog/entry/100666?...
After that, we need to set the initial components. Initially, nodes should have an empty queryset, In order to fully understand the idea you have to know about DSU (disjoint set union) and small to, We will do some kind of DSU (disjoint set union). For each node, we don't only keep its parent, but

Full text and comments »

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

117.
By I_love_Hoang_Yen, history, 11 years ago, In English
Validators with testlib.h If you have written some programming problems, and have prepared test cases, you will probably experience the terrible feeling that some test cases may be invalid (meaning it does not agree with the constraints in problem statement): upper bound can be violated, your graph not satisfied connectivity requirements or is not at tree... It is reasonable to feel that way. Even experienced problem setters make mistakes sometimes (for example, in the prestigious ACM ICPC World final 2007). It is strictly recommended to write a special program (called _validator_) to formally check each test to satisfy all requirements from problem statements. Validators are strictly required for problems on Codeforces. [Polygon](https://polygon.codeforces.com) has built-in support of validators. It is really easy to write a validator using testlib.h. ## Example Following is a validator that could be used for problem [problem:100541A]: ~~~~~ #include "testlib.h" int main(int argc, char* argv...
the beginning of your code in order to use validator. After calling this method, you can

Full text and comments »

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

118.
By cadmiumky, 5 years ago, In English
Infoleague Winter 2021 Training Round Editorial [103449A &mdash; Mountains](https://codeforces.me/gym/103449/problem/A) ------------------ Author: [user:Gheal,2021-12-01] <spoiler summary="Solution"> At the beginning of year $y$, the height of peak $i$ can be any integer $H \in [h_i + y \cdot l_i, h_i + y \cdot r_i]$. Therefore, the problem boils down to finding the maximum number of overlapping segments, where segment $i$ is $[h_i + y \cdot l_i, h_i + y \cdot r_i]$. This can be done in many ways, either via greedy, or by using difference arrays. Time complexity: $O(N log N)$ </spoiler> <spoiler summary="Code"> ``` #include <bits/stdc++.h> using namespace std; using ll = long long; const ll NMAX = 2e5+9; int main() { ios_base::sync_with_stdio(false); cin.tie(0); ll n, y, v, l, r, peaks=0, maxpeaks=0, cnt=0; map<ll,ll> dif_array; cin>>n>>y; for(ll i=0;i<n;i++){ cin>>v>>l>>r; dif_array[v+l*y]++; dif_array[v+r*y+1]--; } for(auto it = dif_arr...
This solution requires setting up a fenwick tree where every node contains an ordered set (bitwise

Full text and comments »

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

119.
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'...
one might be useful in order to know linear and radial sweep algorithms. So , what's all about ? It's

Full text and comments »

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

120.
By ShivanshJ, history, 4 years ago, In English
Codeforces Round #845 (Div. 2) and ByteRace 2023 Editorial We hope you enjoyed the contest!. Thank you for your participation! Do vote under the Feedback section, and feel free to give your review of the problems in the comments. --- [problem:1777A] <br> Idea: [user:ShivanshJ,2023-01-21] <br> Preparation: [user:ShivanshJ,2023-01-21] <br> Editorialist: [user:ShivanshJ,2023-01-21] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Try to make the problem simpler. </spoiler> <spoiler summary="Hint 2"> Parity? </spoiler> <spoiler summary="Hint 3"> Try replacing even numbers with $0$ and odd numbers with $1$ in other words consider all numbers modulo $2$. </spoiler> <spoiler summary="Hint 4"> Think harder! It works! </spoiler> </spoiler> <spoiler summary="Solution"> [tutorial:1777A] </spoiler> <spoiler summary="Implementation (C++)"> ~~~ /* Enjoying CP as always!*/ #include <bits/stdc++.h> using namespace std; #define int long long signed main() { ios_base:...
Let there exist a set of possible starting nodes. If this set is non

Full text and comments »

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

121.
By ivan100sic, history, 9 years ago, In English
What are the things that you discovered independently? Hello CodeForces! I know this happened to everyone &mdash; you made an interesting mathematical/algorithmic/whatever discovery and you were very proud of it and later you realized it's already well known. What's your story? I'll start: I discovered a variant of Mo's algorithm around 4 years ago. I was solving the following problem: Given a static array $a_1, ..., a_n$ and $q = O(n)$ queries. You are allowed to solve them offline. Each query has the form $(l, r)$ and you're supposed to answer, if you were take all the numbers from $a_l, ..., a_r$, extract them into another array and then sort that array, what would be the sum of all elements at odd indexes? This is how I was thinking: If all the queries could be ordered such that both their left ends and right ends form an increasing sequence, you could answer all those queries by adding/removing elements from some augmented balanced binary tree or segment tree in $O(n log n)$. Then again, the same is true when all the que...
This is how I was thinking: If all the queries could be ordered such that both their left ends and

Full text and comments »

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

122.
By mohammedehab2002, history, 6 years ago, In English
Codeforces round #649 editorial ### [problem:1364A] Let's start with the whole array. If every element in it is divisible by $x$, the answer is $-1$; if its sum isn't divisible by $x$, the answer is $n$. Otherwise, we must remove some elements. The key idea is that removing an element that is divisible by $x$ doesn't do us any benefits, but once we remove an element that **isn't**, the sum won't be divisible by $x$. So let the first non-multiple of $x$ be at index $l$, and the last one be at index $r$. We must either remove the prefix all the way up to $l$ or the suffix all the way up to $r$, and we'll clearly remove whichever shorter. Code link: https://pastebin.com/j2Y8AJBA Alternatively, we can notice that this means the answer is either a prefix or a suffix, so we can simply bruteforce them all. ### [problem:1364B] TL;DR the answer contains the first element, last element, and all the local minima and maxima, where a local minimum is an element less than its 2 adjacents, and a local maximum is an e...
There's a nice speed-up, but it relies much more on randomness: ask your indices in a randomorder

Full text and comments »

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

123.
By Bahamin, history, 15 months ago, In English
Atto Round 1 (Codeforces Round 1041, Div. 1 + Div. 2) Editorial ### ✨ **Hope you enjoyed the problems!** ✨ <span style="font-size: 20px;">[problem:2127A]</span><br> **Idea:** [user:Bahamin,2025-08-04]<br> **Preparation:** [user:Hamed_Ghaffari,2025-08-04] <spoiler summary="Hints"> <spoiler summary="Hint 1"> What happens if $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) = 0$? </spoiler> <spoiler summary="Hint 2"> Now what happens if $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) \neq 0$? </spoiler> </spoiler> <spoiler summary="Solution"> Let's see when does $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}])$ equal $\max([a_i, a_{i+1}, a_{i+2}]) - \min([a_i, a_{i+1}, a_{i+2}])$. **Case 1:** $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) = 0$ This implies that all numbers are equal and non-zero, since otherwise $\min$ would be less than $\max$ and the difference wouldn't be $0$. **Case 2:** $\operatorname{mex}([a_i, a_{i+1}, a_{i+2}]) \neq 0$ In this case $\min([a_i, a_{i+1}, a_{i+2}])$ should be $0$ because $0$ is in the seque...
b_i \leq a_j \leq b_j$. The specific order doesn't matter, since Bahamin can permute them freely

Full text and comments »

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

124.
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> [...
to recover the $a_i$ uniquely, but we can set bits to $0$ without loss of generality if they do not, - If an element is not covered by any constraints, it does not matter, and you canset it to any

Full text and comments »

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

125.
By artew, 3 years ago, translation, In English
Codeforces Round #932 (Div. 2) Editorial [problem:1935A] Idea: [user:i_love_penguins,2024-02-24] <br> Preparation: [user:i_love_penguins,2024-02-24] <br> Editorial: [user:i_love_penguins,2024-02-24] <spoiler summary="Hints"> <spoiler summary="Hint 1"> The answer will always have either the prefix $s$, or the reversed string $s$. </spoiler> <spoiler summary="Hint 2"> Adding the string to the end is required no more than once. </spoiler> </spoiler> <spoiler summary="Solution"> Let $t$ be the reversed string $s$. Notice that it is advantageous for us to use operation 1 (adding the reversed string at the end) no more than once. Indeed, having obtained some string, we will simply spend the remaining operations on flipping the string. Thus, we will get the original string or the reversed one, depending on the parity of the number of remaining operations. It is easy to see that the answer will always have either the prefix $s$, or $t$. Then, we find two lexicographically minimal strings with the prefix $s...
Let the order in the response be $p_1, p_2, \ldots, p_k$. Note that, Let's sort the pairs $(a_i, b_i)$ in ascending order of $b_i$. Fix the minimum value in theset of

Full text and comments »

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

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

Full text and comments »

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

127.
By nifeshe, 22 months ago, In English
Codeforces Round #997 (Div. 2) Editorial <spoiler summary = "Rating predictions"> | | A | B | C | D | E | F1 | F2 | |----------------------|------|-----------|---------|------|------|------|---------------| | [user:nifeshe,2025-01-17] | 800 | 1200 | 1400 | 2000 | 2200 | 2700 | 2800 | | [user:Intellegent,2025-01-17] | 800 | 1200 | 1600 | 2000 | 2300 | | | | [user:mwen,2025-01-17] | 800 | 1200 | 1300 | 1800 | 2300 | | | | [user:Markadiusz,2025-01-17] | 800 | 1100 | 1300 | 1800 | 2300 | 2500 | 2800 | | [user:_istil,2025-01-17] | 800 | | [1600, 2000] | 2000 | | 2400 | 2700 | | [user:hazzlek,2025-01-17] | 1000 | 1200 | 1500 | 2000 | 2100 | | | | [user:iLoveIOI,2025-01-17] | 800 | 1100 | 1600 | 2000 | 2400 | | | | [user:A_G,2025-01-17] | 800 | 1100 ...
For a fixed $\text{cnt}$, the number of ways to order $a$ is $\binom{n}{\text{cnt}_0, \text{cnt}_1

Full text and comments »

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

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

Full text and comments »

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

129.
By spike1236, 20 months ago, translation, In English
Virtual trees method This article explores the concept of *virtual trees*, proves their key properties, describes an efficient algorithm for their construction, and then applies the method to solve a specific problem using dynamic programming (DP) on trees. ## Introduction Many tree-related problems require working with a subset of vertices while preserving the tree structure induced by their pairwise lowest common ancestors (LCA). The concept of a *virtual tree* allows us to transition from the original tree $T$ with $N$ vertices to a substructure whose size linearly depends on the size of the selected set $X$. This significantly accelerates algorithms, particularly for DP computations. ## Definition of a Virtual Tree Let $T$ be a given rooted tree, and $X$ be some subset of its vertices. A **virtual tree** $A(X)$ is defined as follows: $$ A(X) = \{ \operatorname{lca}(x,y) \mid x,y \in X \}, $$ where $\operatorname{lca}(x,y)$ denotes the lowest common ancestor of vertices $x$ and $y$ in tr...
2. **Vertex Sorting.** We sort the vertices of set $X$ in the order of their appearance, set $X$ arranged in traversal order: $$ x_1, x_2, \dots, x_m. $$ Denote $$ l = \operatorname

Full text and comments »

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

130.
By Roms, history, 8 years ago, translation, In English
Сodeforces Round 512 (and Technocup — Elimination Round 1) Editorial [problem:1030A] <spoiler summary="Tutorial"> [tutorial:1030A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int curMax = 0; for(int i = 0; i < n; i++) { int curAns; cin >> curAns; curMax = max(curMax, curAns); } puts(curMax > 0 ? "HARD" : "EASY"); return 0; } ~~~~~ </spoiler> [problem:1030B] <spoiler summary="Tutorial"> [tutorial:1030B] </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int n, d; int m; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> d; cin >> m; for(int i = 0; i < m; ++i){ int x, y; cin >> x >> y; bool ok = true; if(!((x - y) <= d && (x - y) >= -d)) ok = false; if(!((x + y) <= n + n - d && (x + y) >= d)) ok = false; if(ok) puts("YES"); else puts("NO"); } return 0; } ~~~~~ </spoiler> [problem:...
set S; vector place[N]; vector > order;

Full text and comments »

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

131.
By salyg1n, 3 years ago, translation, In English
Codeforces Round #897 (Div. 2) Editorial Hello everyone! We're very sorry for the delay >_< We hope you enjoyed the tasks! Sorry for too tight limits in C so that Java solutions don't pass (actually one of our authors nickname used to be "java." :D), we'll hopefully do a better job next time! Feel free to leave your feedback in the comments. [1867A &mdash; green_gold_dog, array and permutation](https://codeforces.me/contest/1867/problem/A) Author: [user:green_gold_dog,2023-09-12] <spoiler summary="Tutorial"> Let's subtract $n$ from the minimum number, subtract $n - 1$ from the second minimum, $n - 2$ from the third $\ldots$, and subtract $1$ from the maximum. Then the number of distinct elements will be $n$. Obviously, it is impossible to achieve a better result. Let's prove that the number of distinct elements will be equal to $n$. Suppose $c_i = c_j$, then without loss of generality, let's say that $b_i > b_j$, then $a_i \leq a_j$, which means $c_i = a_i - b_i$ < $a_j - b_j = c_j$. Contradiction. ...
It is obvious that in order to maximize $\operatorname{MEX}(S)$ after the first move, Alice needs

Full text and comments »

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

132.
By ODT, history, 9 years ago, In English
Codeforces Round #449 Editorial [897A &mdash; Scarborough Fair](http://codeforces.me/contest/897/problem/A) By [user:mcfx,2017-12-04] For every $i$ in range $[l,r]$, if $c_i$ is $c_1$ then change it into $c_2$... Because $n, m$ are all very small, $O( nm )$ can easily pass it. PS. You can use binary search tree to solve it in $O( m\log n )$ time. [897B &mdash; Chtholly's request](http://codeforces.me/contest/897/problem/B) By [user:mcfx,2017-12-04] The $k$-th smallest zcy number is $conn(str(k),rev(str(k)))$, where $str$ denotes the decimal representation of a positive integer as a string, $conn$ denotes the concatenation two strings, and $rev$ denotes the reverse of a string. Then go over the smallest $k$ such numbers and sum them up to obtain the answer. [896A &mdash; Nephren gives a riddle](http://codeforces.me/contest/896/problem/A) By [user:mcfx,2017-12-04] $f(n)=str_1+f(n-1)+str_2+f(n-1)+str_3$. First we can compute the length of $f(n)$ for all possible $n$. For a pair of $(n...
My code uses about 600ms, in order to let some algorithms with large constant or larger time

Full text and comments »

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

133.
By Noobish_Monk, history, 10 months ago, In English
Gale-Ryser Theorem _This blog is a submission for the [Third Codeforces Month of Blog Posts](https://codeforces.me/blog/entry/149422), thanks to [user:cadmiumky,2026-02-10] for the initiative!_ _Thanks to [user:TeaTime,2026-02-10] and [user:k1r1t0,2026-02-10] for giving feedback on the post._ --- Hi everyone! I want to talk about Gale-Ryser Theorem and some of its applications. I've provided proofs for each fact in the blog, they're hidden under the spoilers. --- Gale-Ryser Theorem ================== We have an array of $n$ non-negative integers $a_1, a_2, \ldots, a_n$ and an array of $m$ positive integers $b_1, b_2, \ldots, b_m$, $b_i \le n$. The array $b$ describes a sequence of operations, in the $i$-th operation we need to decrease the values at $b_i$ positions by $1$, formally pick $b_i$ unique indices $j_1, j_2, \ldots, j_{b_i}$ and decrease $a_{j_p}$ by $1$ for $1 \le p \le b_i$. We want to know if it's possible to have all $a_i \ge 0$ after the operations. Without loss o...
first and if it's the second operation. They are the same, since the order, in which we pick indices, of

Full text and comments »

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

134.
By stefdasca, history, 2 years ago, In English
Cheaters now ruin the problem setting queue as well At this point, I think that just about everyone here is familiar with the recent series of blogs surrounding the case of [user:Psychotic_D,2024-07-27] and his gang of cheaters, things which have been exposed [here](https://codeforces.me/blog/entry/131781) and by [user:defnotmee,2024-07-27] in these two blogs ([here](https://codeforces.me/blog/entry/131821) and [here](https://codeforces.me/blog/entry/131826)) in more detail. But what if I tell you that cheaters end up setting rounds on a regular basis too? What makes it even worse is that in some cases, these people use the goodwill of some of the coordinators for their own benefit without having any remorse for their actions, and here is one example in action which caught my attention as it made waves in some of the communities I'm in. Background story ------------------ Cheating is more and more of a problem as shown by the fact that at almost any instance, there is at least one blog talking about a cheater or a cheatin...
mostly by cheaters who were given this code by someone in order to catch them off guard (there was, platforms. The first notorious case of a cheater who set a round which came to my mind was the round

Full text and comments »

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

135.
By darkkcyan, history, 6 years ago, In English
[Not tutorial] Sort before insert — A small extension to Merge sort tree Hello Codeforces! This is my first ever blog on Codeforces, and today I wanted to <s>gain contributions</s> share my small invention during my upsolving. I don't know if there existed a similar idea yet, but as far as I can tell, the editorial for the problem that I have solved does not use my idea. I think it would be nice to share with you guys and have your opinions on this idea. <h1>Prerequisite</h1> You should understand what is a segment and what is a merge-sort tree first. All the code in this blog is in <a href="https://codeforces.me/blog/entry/18051">efficient style</a>, therefore you should at least recognize part of it before reading the code. <h1>Idea explanation</h1> <h2>How do we build Merge-sort tree again?</h2> Merge sort tree is a Segment tree, each node of which contains a sorted set/vector of every element in its range. We build it in a bottom-up manner. To build the parent nodes, we merge 2 sets/vectors of the children the same as we do in the merge-...
Let's first see how we solve this problem without the positions, i.e we have an emptyset of number, Now back to the original problem. For each node, we need to maintain the order of operations for

Full text and comments »

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

136.
By yse, 3 months ago, In English
Codeforces Round 1114 (Div. 3) — Editorial Thank you for participating in the contest! I hope you enjoyed all problems :) Also, thanks to [user:reirugan,2026-08-04] for proofreading the editorial. <spoiler summary="Rating Predictions"> | Predictor | A | B | C1 C2 | D | E | F | G | |----------------------------------|-----|-----|------|------|------|------|------| | [user:yse,2026-08-04] | 800 | 800 | (900 &mdash; 1000) | 1200 | 1400 | 1700 | 2000 | | [user:Wageeh,2026-08-04] | &mdash; | 1000 | (1300 &mdash; 1300) | 1500 | &mdash; | &mdash; | 1900 | | [user:Proof_by_QED,2026-08-04] | 800 | 800 | (1000 &mdash; 1100) | 1300 | 1300 | 1900 | 2100 | | [user:detective...dots,2026-08-04] | 800 | 900 | (1100 &mdash; 1100) | 1300 | 1400 | 1800 | 2100 | | [user:Mr_Bald,2026-08-04] | 800 | 900 | (1100 &mdash; 1200) | 1400 | 1500 | 1800 | &mdash; | | [user:Argentum47,2026-08-04] | 800 | 900 | (1000 &mdash; 1200) | 1300 | 1400 | 1800 | 2000 | </spoiler> <spoiler summary=...
their order, how does it compare to the set of values you would get if you only performed a single, If we look at this final set of values, it is exactly the same as if we had skipped the first

Full text and comments »

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

137.
By Xellos, 13 years ago, In English
Samara SAU ACM ICPC 2013-2014 Quarterfinal Qualification Contest: Editorial ### A. The Power of the Dark Side (difficulty: easy) Let's sort the parameters of every Jedi: $a \ge b \ge c$. The "coverted" Jedi obviously wants to use his strongest 2 parameters ($a_k,b_k$) against the opponent's weakest 2 ($b_i,c_i$) to get 2 victories as assuredly as possible; besides, the optimal order is $a_k$ against $b_i$ and $b_k$ against $c_i$, because if he can win when using them in the opposite order, then he'll win after swapping them, too. So we want to find all Jedis that have $a_k > b_i$ and $b_k > c_i$ for all $i$. That's simple, because those are the same conditions as $a_k > B=\max(b_i)$ and $b_k > C=\max(c_i)$. When processing the input, we can count $B$, $C$ and then we just check for every Jedi if he satisfies these 2 conditions, in linear time. I decided during the contest to code a solution which is a bit slower, but more powerful &mdash; it allows us to answer stronger versions of this problem like "which Jedis can we choose, if we're satisfied with...
Firstly, realize that the groups form a rooted tree, and we're given the ordered pairs (parent,son

Full text and comments »

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

138.
By WorldWarV, history, 7 weeks ago, In English
Codeforces Round 1122 (Div. 3) Editorial Thanks for participating in [contest:2266]! <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2266A] <spoiler summary="Hint"> How many participants can possibly have solved all three problems? </spoiler> <spoiler summary="Solution"> At most $\min(a_1,a_2,a_3)$ participants could have solved all three problems. This is achievable by making the same $\min(a_1,a_2,a_3)$ participants solve every problem, then distributing the remaining solves arbitrarily. Thus, the answer is $n-\min(a_1,a_2,a_3)$. ...
a set and scan in increasing order.

Full text and comments »

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

139.
By djm03178, 23 months ago, In English
Explanation on the set/map hack for 2044F Problem: [problem:2044F] I initially wrote this [here](https://codeforces.me/blog/entry/137306?#comment-1228128), but it has gotten too long and it's hard to find within so many comments, and I see many people are wondering what exactly happened there. So, I'm re-writing all things in a single blog again. If you got time limit exceeded on test 25 or later, then you're caught by one of these hacks. ### What did the hack aim for? The editorial says a `map` (or a `set`, as they're basically the same) solution was intended to pass and no further optimization is needed. Unfortunately, it turns out that the tests weren't strong enough to actually evaluate its performance on the worst case. Let $SumA$ be the sum of elements of array $a$, and $SumB$ be the sum of elements of array $b$ (as stated in the editorial). Let's also say $SA$ is the set of $SumA-a_i$s and $SB$ is the set of $SumB-b_i$s. The most basic way to implement this solution is for each $i \cdot j = x$ ($1 \le i \l...
Explanation on the set/map hack for 2044F, these hacks. ### What did the hack aim for? The editorial says a `map` (or a ` set`, as they're, order of insertion, but as stated in the other blog, I don't know the exact rule for this. Just by

Full text and comments »

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

140.
By ooaa, history, 3 years ago, translation, In English
Codeforces Round #922 (Div. 2) Editorial Hello, everyone! We hope you like our problems! Thank you for participation! [1918A &mdash; Brick Wall](https://codeforces.me/contest/1918/problem/A) Author: [user:ooaa,2024-01-30] <spoiler summary="Tutorial"> The stability of the wall is the number of horizontal bricks minus the number of vertical bricks. Since a horizontal brick has a length of at least $2$, no more than $\lfloor\frac{m}{2}\rfloor$ horizontal bricks can be placed in one row. Therefore, the answer does not exceed $n \cdot \lfloor\frac{m}{2}\rfloor$. On the other hand, if horizontal bricks of length $2$ are placed in a row, and when $m$ is odd, the last brick has a length of $3$, then in each row there will be exactly $\lfloor\frac{m}{2}\rfloor$ horizontal bricks, and there will be no vertical bricks in the wall at all. This achieves the maximum stability of $n \cdot \lfloor\frac{m}{2}\rfloor$. The solution is one formula, so it works in $O(1)$ time. </spoiler> <spoiler summary="Solution">...
Suppose we set $0$ in $x$, then $a \oplus x$ will definitely be less than $b \oplus x$ (because in

Full text and comments »

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

141.
By Christine-, history, 21 month(s) ago, In English
Suspicious problem setter and tester, harsh__h ### Introduction Hello, Codeforces! I want to share my suspicions about [user:harsh__h,2025-02-03]. I wouldn't write the blog if he was not a relatively high ranked individual who both participated in problem setting and testing. Yesterday, I accidentally noted that the 6th place ([standings:2059]), in [contest:2059], which turned to be [user:harsh__h,2025-02-03], had very suspicious submissions. Next, I will try to explain in detail what got my attention in the order in which I uncovered it. ### Part 1. Codeforces Round 1002 Div2. During the contest in problems A([submission:304070640]), B([submission:304090034]), C([submission:304111128]) [user:harsh__h,2025-02-03] doesn't use spaces between brackets. That is, he writes, say, `for(ll i=0;i<n;i++){` not `for (ll i = 0; i < n; i++) {`. Also, for the newline he uses endl `cout << mex << endl;`, and these are not interactive problems. Next, In problems D ([submission:304092485]), E([submission:304129652]), in which I t...
. Next, I will try to explain in detail what got my attention in the order in which I uncovered it.

Full text and comments »

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

142.
By marat.snowbear, 12 years ago, In English
Codeforces Round #269 Editorial [problem:471A] ------------------ Given six sticks and their lengths we need to decide whether we can make an elephant or a bear using those sticks. The only common requirement for both animals is that four leg-sticks should have same length. This means that the answer "Alien" should be given **only** if we can't find four sticks for the legs. Otherwise we will be able to make some animal. The type of the animal will depend on the relation of the remaining sticks' lengths. If they are equal then it will an elephant, if they are different we will have a bear. So this algorithm should solve the problem: 1. Find the number which appears at least four times in the input. 2. If no such number exist then the answer is "Alien". 3. Otherwise remove four entries of that number from the input. 4. After removing that number you will have two numbers left, compare them and decide whether it's an elephant or a bear. One shortcut for this problem might be to sort the in...
Given a set of horizontal/vertical lines you need to erase some parts of the lines or some lines

Full text and comments »

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

143.
By EvenImage, history, 3 years ago, In English
2nd Universal Cup Announcement Hello everyone, we are happy to announce that the 2nd Universal Cup has started officially. The Universal Cup is a non-profit organization dedicated to offering training resources for competitive programming teams. Our website is [https://ucup.ac/](https://ucup.ac/) (in English and Chinese). In the previous season, over 750 teams from more than 300 affiliations all over the world, registered and participated in a total of 22 stages, encompassing contests from Asia, Europe, and America. With the permission of contest setters and without involving copyright disputes, the Universal Cup will hold mirror contests for some undisclosed competition sets. It is expected to hold at least 20 contests in this season. We will simulate the actual situation in the competition, executing the board freeze in the last hour. At the same time, we will provide an overall rating board, which will help the team to make a reasonable assessment of itself. Over the past few weeks, the committee has...
- Yaohui [user:quailty,2023-08-24] Zeng (Sorted by lexicographical order of the last name)

Full text and comments »

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

144.
By vitux, 12 years ago, translation, In English
Codeforces Round #262 (Div. 2) Editorial [problem:460A] At this problem you need to model what written in statements. Also, it can be proved, that answer can be calculated using formula: $n + \lfloor\frac{n - 1}{m - 1}\rfloor$ , where $\lfloor x \rfloor$ is the integer part of $x$. [submission:7536107] [problem:460B] Obviously $S(x)$ can take only integer values and $ 1 \le S(x) \le 81 $. Let's check $S(x)$ from $1$ to $81$, and calculate $ B*S(x)^{A} + C$. After that if sum of digits of this number is equal to $S(x)$, it is positive and less than $10^9$, than it is a solution. There could be bug because of using C++ pow() function. [submission:7536153] [problem:460C] Note,that answer is positive integer not greater than $10^9+10^5$. Using binary search on answer, we will find answer. Really, we can check in $O(n)$ if some height is achievable. We go from left to right. For current flower we calculate how much times it need to be watered to stand not lower than checking value. If cuurent flower nee...
(and points become ordered). After that we build recursion function with the next parameters:1) how

Full text and comments »

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

145.
By Xellos, 13 years ago, In English
Codeforces Trainings Season 1 Episode 10: Editorial #### **Welcome to The Editorial!** <img src="http://th04.deviantart.net/fs70/PRE/f/2013/078/b/f/mi_super_saiyan_god_remasterizado_by_salvamakoto-d5ymxyi.png" height="50%" width="50%" /> **Keep the upvotes piling up! muhehe** IZ.COMPLETE. ### A. Rasheda And The Zeriba [cut] $\ $ (difficulty: medium) The first question is: When is it possible to construct a (convex) polygon from sticks of given lengths $L_i$? This question is answered by what's sometimes known as Polygon inequality theorem, which states that the sufficient and necessary condition is for every $L_i$ to be strictly less than the sum of all other $L_i$. You can imagine that it works because for the endpoints of every side, the shortest path between them (equal to the length of that side) must be smaller than any other path, including the other one along the perimeter of the polygon; constructing such a polygon, even a convex one, is pretty easy, just imagine it as having sticks linked to each other that...
also store all visited vertices in an STL set ($S$), in order to be able to check if it's been visited

Full text and comments »

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

146.
By adamant, 12 years ago, translation, In English
C++ STL: Policy based data structures. Part 2 Hi everyone! Some of you may remember my [entry](/blog/entry/11080) about policy based data structures. In addition to a review article on these structures, I also wanted to write about the possibility of using your own `Node_Update` class. Then I hadn't enough time for it, but now I can and I want to catch up and share with you some new knowledge. <br> [cut] <br> So, let's start. Node_update class should looks like this: ~~~~~ template<class Node_CItr, class Node_Itr, class Cmp_Fn, class _Alloc> struct my_node_update { typedef my_type metadata_type; void operator()(Node_Itr it, Node_CItr end_it) { ... } }; ~~~~~ Let's consider how this class works. Policy based tree, which is using update policy will additionally keep in node one variable of type `my_type`. When the tree is rebuilt, part of the metadata spoils, so for each node, which could be damaged applied the operator (). At the same time this operator begins to be appli...
nodes of our tree. For example, here is the function that finds order of `int` key inset:

Full text and comments »

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

147.
By __baozii__, 9 months ago, In English
Codeforces Round 1077 (Div. 1, Div. 2) Editorial We hope you enjoyed the problems! <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2188A] - Idea: [user:__baozii__,2026-01-29], [user:Tobo,2026-01-29] - Solution: [user:__baozii__,2026-01-29] - Editorial: [user:__baozii__,2026-01-29] <spoiler summary="Solution"> For $|p_{n-1}-p_n|$ to be divisible by $n-1$, either $p_{n-1}=1$ and $p_n=n$, or $p_{n-1}=n$ and $p_n=1$. Either way, we can construct $p$ backwards. For $i$ from $n-2$ to $1$, there will only by one possible choice for $p_i$, where $...
different orders in the two permutations. The maximal entangled set of a node's children is defined as

Full text and comments »

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

148.
By Errichto, 11 years ago, In English
VK Cup 2016 Round 1 — Editorial Codes in nicer format will be uploaded later. [problem:658A] and [problem:639A] &mdash; [codes](http://ideone.com/NYuwV8). [problem:639B] and [problem:639C] &mdash; [codes](http://ideone.com/GcUNZJ). [problem:639D] &mdash; [codes](http://ideone.com/FkE3DU). [problem:639E] &mdash; [codes](http://ideone.com/OoSLF3). [problem:639F] &mdash; [codes](http://ideone.com/PUSLI2). [problem:658A] &mdash; Iterate once from left to right to calculate one player's score and then iterate from right to left. It's generally good not to write something similar twice because you are more likely to make mistakes. Or maybe later you will find some bug and correct it only in one place. So, try to write calculating score in a function and run them twice. Maybe you will need to reverse the given arrays in some moment. [problem:639A] &mdash; You should remember all friends displayed currently (in set or list) and when you add someone new you must check whether there are at most $k$ people ...
question will be: if there is a paradox for at least one order). Let's call such aset of tied

Full text and comments »

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

149.
By Getaway_Car, 3 weeks ago, In English
Codeforces Round 1129 (Div. 2) Editorial Thank you for participating in the round! <spoiler summary="Fun facts"> - D1 was originally proposed as B. - This round originally had a problem called "Token Moving", but we removed it during the testing phase. </spoiler> <spoiler summary="Rate this round"> - Amazing: - Good: - OK: - Bad: - Terrible: </spoiler> [problem:2277A] Author: [user:Getaway_Car,2026-10-24] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Check the values $0, 1, 2, \ldots$ in increasing order. What is needed for $i$ to be the maximum of some multiset? </spoiler> <spoiler summary="Hint 2"> A multiset with maximum $i$ needs one element equal to $i$ and $k - 1$ other elements not exceeding $i$. An element that is not used now can still be used for any larger value, so keep track of how many such elements are available. </spoiler> </spoiler> <spoiler summary="Tutorial"> To maximize ...
Construct the query as follows: set $x = a_i$ and $p_{a_i} = 1$. Order the already known vertices

Full text and comments »

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

150.
By caustique, 13 years ago, translation, In English
Editorial for Codeforces Round #202 ### [problem:349A] In the problem you need to decide whether cashier can give a change to all customers if the price of the ticket is 25 rubles and there's 3 kinds of bills: 25, 50 and 100 rubles. There's no money in the ticket office in the beginning. Let's consider 3 cases. - Customer has 25 rubles hence he doesn't need a change. - Customer has 50 rubles hence we have to give him 25 rubles back. - Customer has 100 rubles hence we need to give him 75 rubles back. It can be done in 2 ways. 75=25+50 и 75=25+25+25. Notice that it's always worth to try 25+50 first and then 25+25+25. It's true because bills of 25 rubles can be used both to give change for 50 and 100 rubles and bills of 50 rubles can be used only to give change for 100 rubles so we need to save as much 25 ruble bills as possible. The solution is to keep track of the number of 25 and 50 ruble bills and act greedily when giving change to 100 rubles &mdash; try 25+50 first and then 25+25+25. ### [problem:349B] ...
In order to effectively answer queries, for every set (both light and heavy) we calculate size of

Full text and comments »

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

151.
By Shisuko, history, 8 years ago, In English
The Intuition Behind NIM and Grundy Numbers in Combinatorial Game Theory There are already many wonderful resources online for learning the basics to combinatorial game theory, but the intention I have for _this_ guide in particular is to try to make them more intuitive. Why does XOR work for Nim? Why does mex produce the Grundy numbers? When it was taught to me, it was more or less just as 'magic' to memorize, but now I think I have a decent understanding of why they are true, so now that I have a grasp of the intuition behind it, I decided I should record my thoughts into a blog. Nim games ================== Suppose we are playing a Nim game. As we know, Nim games usually follow this sort of template: - There are $n$ piles of stones, and each pile contains $p_1, p_2, p_3, \cdots p_n$ stones, where each of the $p_i$ is some nonnegative integer. This collection of piles defines our game state. - There are two players who take turns removing stones. The current turn player may remove as many stones as they wish, so long as all the stones come f...
the set $\\{0,1\\}$ and the operation of addition modulo 2, *or* some ordered $n$-tuple of $\\{0,1

Full text and comments »

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

152.
By DrunkMaster, 5 years ago, In Russian
Как тренироваться: почему для школьных олимпиад не надо учить сложные темы и решать гробы Всем доброго времени суток! На этот пост меня вдохновил [user:Wind_Eagle,2022-04-05] своим [постом](https://codeforces.me/blog/entry/101549). Этот блог является заключительным в цикле [челлендж::поготовься к респе](https://codeforces.me/blog/entry/99856). Советую перед прочтением сначала прочитать его, а также вышеописанный блог, так как данный наследуется от них. Для начала подведу итоги челленджа. Он оказался скорее неуспешным, чем успешным. Единственное, что я получил от него &mdash; опыт, который будет полезен в будущем. Итак, итоги: - Взять диплом на республике. Не выполнил, остался без диплома. Нарешал очень плохо, наконец понял, что главная проблема не столько даже лежит в программировании, сколько в психологии. Заметил очень нехорошую особенность: пришёл как на первый, так и на второй тур, все 5 часов не мог сосредоточиться, чего-то боялся (сам не знаю, чего). Из-за этого я фактически не думал, а скорее просто выписывал на листочке что-то и пытался просто реализовать...
- встроенные в g++ структуры данных: ordered set / ordered multiset, их особенности и баги

Full text and comments »

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

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

Full text and comments »

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

154.
By Zlobober, 11 years ago, In English
An editorial of Topcoder SRM 672 Hi everybody! It was my first experience of writing problems for TopCoder SRM, hope you liked it. I was a writer of Easy and Medium task in both divisions, [user:subscriber,2015-10-21] was an author of both Hard tasks. In div1 they were harder than usual, but I hope you still liked them. #### Div2 easy This task was just about implementing exactly what is described in the statement. Looks like Python has a built-in support of set comparison. Usually coders using Python have a disadvantage, but in this task it looks more like an advantage :) There are built-in functions for sets in C++ and Java too, I recommend to learn about them even if you successfully submitted this problem. #### Div2 medium Knowing strings a and b, we can build a reverse mapping $q[d] = c$, that maps the encoded letter $d$ to it's original corresponding letter $c$. For letters that do not appear in $b$, we remember that we don't know their pre-image. After that, we just apply our mapping $q$ to a string...
adds one of the maximal edges between the already visited set and the rest of the vertices in the

Full text and comments »

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

155.
By SuperJ6, 4 years ago, In English
How to Effectively Practice CP + Problem Solving Guide This is a slight tweak of [a practice guide](https://www.reddit.com/r/usaco/comments/pk3tjp/the_ultimate_usaco_practice_method/) I wrote a while ago on USACO reddit since I thought it could be helpful to people here. Some USACO specific sections or extra clutter I left out here that aren't needed for a general audience. This should cover all general cp advice I have so I never have to retype. #Introduction This is a post on how I believe is the best method to practice modern day competitive programming based on my experiences. I assume you already have some knowledge and know simple things like binary search and dfs/bfs, but **read the footnote if you are complete beginner** (never code, solved <50 problems, div2 A/B too difficult, grey or stuck low pupil). First, a quick tl;dr of the practice strategy before a bunch of specifics and explanation: >**In short, mostly you only need to use codeforces (no matter what contest you're training for), find a rating range where you c...
the problem set tab in reverse order of id (the default sorting). Also take part in every live

Full text and comments »

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

156.
By niyaznigmatul, 10 years ago, translation, In English
Codeforces Round #402, Editorial ### [problem:779A] Problem setter: [user:MikeMirzayanov,2017-02-28] To solve this problem let's use array $cnt[]$. We need to iterate through first array with academic performances and for current performance $x$ let's increase $cnt[x]$ on one. In the same way we need to iterate through the second array and decrease $cnt[x]$ on one. If after that at least one element of array $cnt[]$ is odd the answer is $-1$ (it means that there are odd number of student with such performance and it is impossible to divide them in two. If all elements are even the answer is the sum of absolute values of array $cnt$ divided by 2. In the end we need to divide the answer on 2 because each change will be counted twice with this way of finding the answer. ### [problem:779B] Problem setter: [user:MikeMirzayanov,2017-02-28] To solve this problem we need to make $k$ zeroes in the end of number $n$. Let's look on the given number as on the string and iterate through it beginning from the end...
order. Because all these suffixes will be increased by the same value, the property of having the

Full text and comments »

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

157.
By kartik8800, history, 3 years ago, In English
Introduction to Disjoint Set Data Structure | DSU # Introduction to Disjoint Set Data Strucutres Hello Codeforces! I recently read about Disjoint Sets from the book Introduction to Algorithms and wanted to share the learnings in a simplified manner. So below article(and corresponding videos) is an attempt to create a good starting point for people who: 1. want to learn about DSU 2. practice some good DSU problems ## Contents 1. Introduction through an illustrative problem (video version: https://youtu.be/JDycPHW4kIs?si=WEp5Ft2jBWp9KnO2) 2. Sample SPOJ Problem and Implementation (video version: https://youtu.be/O4w-aX5mSks?si=vr0XSbyUswcXx-Yv) 3. Upcoming Practice Problems 4. Some Applications and References We will learn about disjoint set data structures and their operations union and find through a sample problem. ## Illustrative Problem Q: Given a undirected $Graph(V, E)$, answer Q queries of the form $(u, v)$ where answer to the query is True if there is a path from u to v, false otherwise. ![image](ht...
Introduction to Disjoint Set Data Structure | DSU, worst case graph can have order of $V^2$ Edges. 4. So worst case complexity can be $O(Q*V^2)$, # Introduction to Disjoint Set Data Strucutres Hello Codeforces! I recently read about Disjoint, 1. Overall height after N-1 union will be order of LogN 2. Hence ensuring Find is no worse than

Full text and comments »

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

158.
By BledDest, 5 years ago, In English
Codeforces Round #760 (Div. 3) Editorial [problem:1618A] Idea: [user:Brovko,2021-12-14], preparation: [user:Brovko,2021-12-14] <spoiler summary="Tutorial"> [tutorial:1618A] </spoiler> <spoiler summary="Solution (Brovko)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; for(int i = 0; i < t; i++) { vector <int> b(7); for(int i = 0; i < 7; i++) cin >> b[i]; cout << b[0] << ' ' << b[1] << ' ' << b[6] - b[0] - b[1] << endl; } } ~~~~~ </spoiler> [problem:1618B] Idea: [user:BledDest,2021-12-14], preparation: [user:awoo,2021-12-14] <spoiler summary="Tutorial"> [tutorial:1618B] </spoiler> <spoiler summary="Solution (awoo)"> ~~~~~ for _ in range(int(input())): n = int(input()) s = input().split() for i in range(n - 3): if s[i][1] != s[i + 1][0]: s.insert(i + 1, s[i][1] + s[i + 1][0]) break else: ...
> psum = {0ll}; vector> order; for(int i = 0; i < n; i++) order.push_back

Full text and comments »

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

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

Full text and comments »

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

160.
By makrav, 4 months ago, In English
Codeforces Round 1111 (Div. 2) Editorial Thank you for participating in the round! [problem:2247A] - Idea: [user:PvPro,2026-07-18] - Solution: [user:PvPro,2026-07-18] <spoiler summary = "Hints"> <spoiler summary = "Hint 1"> Try to find an invariant </spoiler> <spoiler summary = "Hint 2"> Consider the sum of all elements in the array </spoiler> </spoiler> <spoiler summary = "Solution"> It's easy to see that $\left( \sum\limits_{i = 1}^n a_i \right) \bmod 4$ does not change after a single operation. Therefore, if $\left( \sum\limits_{i = 1}^n a_i \right) \bmod 4 \neq 0$, then the answer is "NO". Otherwise, let's make $a_1 = 1, a_2 = -1, a_3 = 1, \dots, a_{n - 1} = (-1)^n$. We can always do that by performing operations with indices $1, 2, 3, \dots n - 1$ in this order, and after operation number $i$ we set the $i$-th element to the value we want. After that, $| \sum\limits_{i = 1}^n a_i | \leq 2$, so it is equal to zero because it's the only number divisible by $4$ in that range. </spoiler> ...
that by performing operations with indices $1, 2, 3, \dots n - 1$ in this order , and after operation

Full text and comments »

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

161.
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...
blog. Preorder Traversal or DFS Order of the Tree. Problem 1 — Handling Subtree Queries

Full text and comments »

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

162.
By literalchild, history, 6 months ago, In English
Unofficial Editorial for SEATST 2026 # Introduction On 23 and 24 May, 7 countries participated in the **S**outh **E**ast **A**sia **T**eam **S**election **T**est. As the only contestant who AKed both days, I decided to write an editorial for the bugaboos. (The bugaboos are [here](https://tlx.toki.id/bugaboos/seatst-2026).) # 1A (Two Exams) <spoiler summary="Solution"> My solution was the same as [user:blackscreen1,2026-05-27]'s [solution](https://codeforces.me/blog/entry/154034), but I found it in a different way. First, I tried binary searching on the answer, so it reduces to checking if $P[i] - i \leq K$. Rather than setting $P^{-1}[0], P^{-1}[1], \cdots$, giving each index $i$ a deadline of $i + K$, I decided to use the reverse order; first set $P^{-1}[N-1]$, then $P^{-1}[N-2]$, and so on. This means that each index $i$ is only "usable" from "time" $i+K$ onwards. Then, $P^{-1}[i]$ must be the remaining student with highest $A$ or highest $B$. Now, the key observation is that the only way we can "die...
decided to use the reverse order; first set $P^{-1}[N-1]$, then $P^{-1}[N-2]$, and so on. This means

Full text and comments »

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

163.
By Abinash, 12 years ago, In English
Good Blog Post Resources about Algorithm and Data Structures There are many good blogs in **Codeforces Blog** where people describes about different **Algorithm and Data Structures** . Lets gather all the resources about **Algorithm and Data Structures** Explanations. You can comment bellow the link and about it . I will always update that post gather new resources.Hope ,its help all and inspire all to write new blog post in future :) Last added blogs link will have a tag **(New)** Resources: **C++ STL** [C++ STL: Policy based data structures]( /blog/entry/11080) [C++ STL: Policy based data structures. Part 2]( /blog/entry/13279) **String Processing** [Suffix tree. Basics. Building in O(nlogn)]( /blog/entry/11337) [Z Algorithm]( /blog/entry/3107) [Great resource for string algorithms]( /blog/entry/8008) [Aho-Corasick algorithm. Construction]( /blog/entry/14854) [Suffix tree. Ukkonen's algorithm](/blog/entry/16780) [On suffix automaton (and tree)](/blog/entry/22420) **New** **Data Structur...
[About ordered set]( /blog/entry/11275), [Partially Ordered Sets]( /blog/entry/3781)

Full text and comments »

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

164.
By P_Nyagolov, 9 years ago, In English
[Tutorial] Nearest Neighbor Search: Locality-Sensitive Hashing, K-Dimensional Tree, Vantage-Point Tree Hello everyone, So I recently prepared a lecture for a Bulgarian camp on the topic since I find it quite wide and interesting. I have never seen an article discussing different approaches for the problem so today I am going to share my knowledge. Don't forget to give me your feedback, please! Let's start with first defining the problem we are going to solve. We are given a set of $N$ $d$-dimensional points. $Q$ queries follow, each containing a $d$-dimensional point. We should answer each query with the distance (we will use Euclidean distance) to the point from the set which is closest to the queried one. This will be our main focus but we are still going to consider inserting/deleting points from the set when possible. It's important to say that for $d>1$ we will consider only average-case complexity and we will assume that the points are distributed uniformly. Unfortunately, even the average-case complexity is exponential in the number of dimensions. ##### One-Dimensional N...
, we will need to get too lucky in order to answer many queries correctly with just oneset of lines

Full text and comments »

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

165.
By T1duS, history, 5 years ago, In English
IOI Training for Indian Aspirants (UFDS Mentoring 2022) Hey all! We hope you're doing well. Like last year, we're again looking to give back a little to the competitive programming community, in the form of mentorship. This mentorship is **completely free**. We're hoping to help aspiring competitive programmers do well at the [ZCO, INOI and IOITC](https://www.iarcs.org.in/inoi/), and hopefully even [represent India at the IOI](https://stats.ioinformatics.org/results/IND)! We're setting up another Discord server, to mentor people trying out for the ZCO, INOI and IOITC. Last year, we had 16 people from our server qualify for IOITC. This time, there's a larger limit on the total number of people we can take, as we have many more mentors. However, we're trying to focus more on olympiad preparation this year. You're still welcome to apply if you think you'd benefit from Olympiad training but are ineligible for INOI. We're also in the process of developing a resource similar to the USACO Guide, in order to help us organise our teaching ...
sessions to teach/discuss classical techniques (we now have a list of topics we'd like to cover inorder

Full text and comments »

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

166.
By gen, 13 years ago, In English
Codeforces Round #238 Tutorial #### [problem:405A] Observe that in the final configuration the heights of the columns are in non-decreasing order. Also, the number of columns of each height remains the same. This means that the answer to the problem is the sorted sequence of the given column heights. Solution complexity: $O(n)$, since we can sort by counting. #### [problem:405B] If the first pushed domino from the left was pushed to the left at position $l$, all dominoes at prefix $[1;l]$ fall down, otherwise let $l$ be 0. Similarly, if the first pushed domino from the right was pushed to the right at position $r$, all dominoes at suffix $[r;n]$ also fall down, otherwise let $r$ be $n+1$. Now, in the segment $(l;r)$ there will remain vertical dominoes and blocks of dominoes supported by the equal forces from both sides. When does a domino at position $p$ in segment $(l,r)$ remains standing vertically? One way is that it is not pushed by any other domino. This could be easily checked by looking at the ...
, call this set `adjacent`. Then block all the edges from this set vertices to $v$. For each $u$ in

Full text and comments »

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

167.
By Geothermal, history, 7 years ago, In English
Codeforces Round 629 -- Unofficial Solutions Hi all! As it might be a little while before the editorial for today's round is released (due to the open hacking phase), I thought I'd publish my solutions in case anyone wants to review the problems right away. --- #A &mdash; Divisibility Problem There are a few ways to approach this. One is to find the next multiple of $B$ after $A$ and subtract $A$. Recall that we can compute $\frac{A}{B}$, rounded up, as $\frac{A+B-1}{B}$, rounded down. We can compute this value and then multiply it by $B$ to get the next multiple of $B$, subtracting $A$ to get our answer. An alternative solution (and the one I implemented) is to realize that, as long as $A$ isn't already a multiple of $B$, the number of moves required is $B - (A \% B)$, since the distance to the next lower multiple of $B$ plus the distance to the next higher multiple of $B$ will be $B$. We can use this to compute the answer. In the case where $A$ is a multiple of $B$, this prints $B$ instead of $0$, so we can ...
the set. We can perform a pre-order traversal, tracking entry and exit times, to enable us to

Full text and comments »

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

168.
By zscoder, history, 10 years ago, In English
Weekly Training Farm 22 — Editorial Weekly Training Farm 22 is over. Congratulations to the winners : 1. [user:W4yneb0t,2017-01-20] (perfect score in < 1 hour!) 2. [user:aaaaajack,2017-01-20] (perfect score) 3. [user:eddy1021,2017-01-20] Here is the editorial : ### Problem A This problem can be solved by greedy. We list down the positive integers one by one. We keep a pointer that initially points to the first letter of $s$. Whenever the pointed character in the string $s$ matches the corresponding digit of the integer, we move the pointer one step to the right and continue. Repeat this process until the pointer reaches the end. However, we still need to know whether the answer can be large. The key is to note that the answer will never exceed $10^{6}$, because after writing down $10$ consecutive numbers, at least one of them has last digit equals to the current digit, so the pointer will move to the right at least once when we write down $10$ consecutive numbers. Thus, in the worse case, we'll onl...
which set of problems to solve, then it's best to solve the problem in increasingorder of time

Full text and comments »

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

169.
By Hazyknight, history, 8 years ago, In English
A brief tutorial to problem G of Hello 2019. The first step is how to deal with $(f(x))^k$.Here we can use Stirling Number of the second kind. Let's define $S(i,j)$ the number of ways to put $i$ different elements into $j$ sets and there are no empty set.Note that the all $j$ sets are the same.For example $S(3,2)=3$.The three ways are ${{1},{2,3}},{{1,2},{3}},{{1,3},{2}}$.So we have: $$a^b=\sum_{i=1}^{b}C(a,i) \times i! \times S(b,i)$$ How to proof it?$a^b$ is the number of ways to put $b$ different elements into $a$ different sets and empty sets are allowed.The other side of the equation means we select $i$ sets from $a$ sets and arrange them in $i!$ different orders and put $b$ different elements in it. So the fomula in the statement becomes: $$\sum_{X \subseteq \{1,2,3,...n\} X \neq \o} \sum_{i=1}^{k}C(f(x),i) \times i! \times S(k,i)$$ Which equals to: $$\sum_{i=1}^{k} i! \times S(k,i) \sum_{X \subseteq \{1,2,3,...n\} X \neq \o} C(f(x),i)$$ For $\sum_{i=1}^{k} i! \times S(k,i)$ we can use the following $O(k^2)$ DP to c...
consider the $i$th element.It can form a set by its own.Or you can insert it into one of those $j$ sets.

Full text and comments »

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

170.
By szdytom, history, 3 years ago, In English
2022 Joint exam of 5 schools (GZEZ Round2) Editorial [A. Refreshed](https://codeforces.me/gym/104538/problem/A) ------------------ If we don't take the shortest path from $s$ to $t$ but instead detour to some vertices to gain health, we must pass through an edge with both endpoints having a sum of weights greater than 0. If we reach either vertex of such an edge, we can gain infinite health. We mark such vertices as infinite health vertices. So, either we take the shortest path from $s$ to $t$, or we take the shortest path from $s$ to an infinite health vertex, gain infinite health, and then walk to $t$. The second case can be maintained through up and down DP, which keeps track of the minimum health required to reach an infinite health vertex from each vertex. The first case is to find the prefix minimum value of the path from $s$ to $t$. It is easy to see that the prefix minimum value is either the entire path or the entire path excluding the vertex $t$. Otherwise, there must be infinite health on the path, which can b...
**Definition** Orbit, order: The **orbit** of a permutation $p$ is the set $\langle p\rangle

Full text and comments »

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

171.
By DEGwer, 13 years ago, In English
Codeforces Round #219 editorial Sorry for late. This is the editorial of Codeforces Round #219. Div2 A, Div2 B, Div1 C are made by [user:m.kagamiz,2013-12-15], and other problems are made by me. [problem:373A] /\\_/\ First, you need to count the occurence of each number (1 through 9). If none of them are greater than 2 * k, Cucumber boy is able to press the panels in perfect timing. Complexity is O(1). My solution : http://ideone.com/CwQtBv [problem:373B] /\\_/\ Naive simulation (subtracting S(i) * k from w while w >= 0) won't finish in 2 seconds. At first, these two facts will make it easier to solve the problem : 1. k doesn't matter for solving this problem, so you can simply divide w with k at the first point. 2. S(10^x) + S(10^x + 1) + ... + S(10^(x+1) &mdash; 1) = 9 * x * 10^x . There are many ways to solve this problem, and I'll show you 2 ways. 1. Binary Search Let's define f(n) as \sum_{k=1}^{n} S(n). This problem can be solved by finding largest x that satisfies f(x) &md...
$s$ in dfs order, and assume that previous numbered vertices in dfs order in theset is t, and next

Full text and comments »

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

172.
By nifeshe, 10 months ago, In English
Codeforces Round 1073 (Div. 1, Div. 2) Editorial Special thanks to [user:reirugan,2026-01-17], [user:weirdflexbutok,2026-01-17] and [user:intellegent,2026-01-17] for helping with editorials. [problem:2191A] - Idea: [user:nifeshe,2026-01-17] - Solution: [user:nifeshe,2026-01-17] - Editorial: [user:reirugan,2026-01-17] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Without the "after sorting condition", there are only two ways to color the cards. </spoiler> </spoiler> <spoiler summary="Solution"> Without the "after sorting condition", there are only two ways to color the cards. We must have that $a$ is alternating in color. Without loss of generality, color the odd indices red and the even indices blue. This uniquely colors every card. Now, let's sort the array $a$, while also keeping track of the colors; one way to do this is by sorting it as a vector of pairs. Then we simply have to verify that no two adjacent cards are the same color. Alternatively, you can use the fact that $a$ is a permutation, ...
lexicographically smallest such option. Set $q_i$ to be the smallest element in $p[i, j]$ that is, such option. To do so, we set $q_i$ to be the smallest element in $p[i, j]$ that is larger than

Full text and comments »

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

173.
By jinhan814, 3 years ago, In English
[Tutorial] Zeta, Mobius Transform to AND, OR, GCD Convolution ## Introduction [Original Post(Korean)](https://blog.naver.com/jinhan814/223175490201) For those who have studied the Inclusion-Exclusion Principle or the Mobius Inversion formula, you may have wondered about the definition of $μ(n)$ and the process of offsetting unnecessary values by multiplying $(-1)^{|s|}$. Although it is possible to show the validity of these formulas through expansion, such proofs lack intuitive clarity. In this article, I will define Zeta and Mobius Transform on a Poset and explore examples from various Posets. Understanding these concepts will provide insights into the Inclusion-Exclusion Principle and the Mobius Inversion formula. Additionally, Zeta and Mobius Transform are essential concepts connected to SOS DP and AND, OR, GCD, LCM Convolution. In the final part of the article, we will examine interesting connections to various convolutions from Zeta and Mobius Transform. ## Table of Contents 1. What is Poset? 2. Zeta, Mobius Transform on Pose...
between $b$ and $c$. For this reason, ($S$, $≤$) is referred to as a Partially Ordered Set (Poset).

Full text and comments »

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

174.
By pedriwnl, 4 months ago, In English
AtCoder Educational DP Contest Editorial (The Best DP Contest for Beginners) Hello, Codeforces! ------------------ ### Introduction Searching for editorials for this [contest](https://atcoder.jp/contests/dp) can be surprisingly annoying, since there is no official editorial on the AtCoder website. Because of this, my friends ([user:murkat,2026-07-08] and [user:GuilhermeKK,2026-07-08]) and I felt it was necessary to put together a unified guide all in one place. We essentially wanted to create the editorial we wish we had when we were first solving these problems! ### Who is this for? This contest covers all the fundamental DP techniques and optimizations. If you are not familiar with DP (and you definitely should be, since it is one of the most common topics in cp), the first few problems will be perfect for you to understand the reasoning behind it. If you know the basics of DP but feel like you are always one step away from finding the right state or transition, there are a lot of great problems here for you to practice. If you are looking for...
Is there a better order to construct a tower using a specific set of

Full text and comments »

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

175.
By Ripatti, 15 years ago, translation, In English
Croc Champ 2012 — Round 2 — Editorial **A div2.** Required row is row that have only one star inside. Requred column is comumn that also have only one star inside. So, you can iterate over all rows/columns, calculate number of stars inside them and find the answer. Authors are ~MikeMirzayanov,2012-04-20,, ~Gerald,2012-04-20 [cut]. **B div2.** Naive solution $O(n^3)$ (where you check all triplets) doesn't fin into time limits. You can see that for every two points from triplet (for example, for A and C) you can find place of the third point. So you can find number of requred triplets just inerate over all pairs of points and check middle point between points in every pair. How to fast check position? You can add 1000 for all coordinates (you can see that this operation doesn't change the answer) and mark them in the 2-dimensional boolean array 2001х2001. So you can check every position for point in $O(1)$ time. Obtained solution works in $O(n^2)$. Authors are ~MikeMirzayanov,2012-04-20,, ~Gerald,2012-04...
For solving initial problem you should support set of active vertices in ordered state (for example

Full text and comments »

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

176.
By tibinyte2006, 4 years ago, In English
CodeTON Round 3 (Div. 1 + Div. 2) Editorial [A — Indirect Sort](https://codeforces.me/contest/1750/problem/A) ===== Authors: [user:mejiamejia,2022-10-31], [user:Ecrade_,2022-11-06] <spoiler summary="Solution"> We claim that we can sort the array if and only if $a_1 = 1$. **Necessity** We can notice that index $1$ cannot be affected by any swap operation. Let's see what happens to the value $1$. According to the definition of the operation, it can either increase or be swapped. In order to be increased, there must exist some $k$ such that $1 > a_k$, but since $1$ is the minimum possible value, it will never be true as other values in array $a$ can only increse as well. Since index $1$ can not be affected by a swap operation and $a_1>1$, we conclude that if $a_1 \neq 1$, the answer is **No**. **Sufficiency** Let's focus on the second operation. Since we have $a_1 = 1$, we can always choose $i=1$ and the operation then turns into picking some pair $2 \le j < k \le n$ and swapping $a_j$ with $a_k$. It's t...
{k+1},a_{k+2},...,a_n$ can be arranged in any order. Denote $S$ as the set of remaining numbers

Full text and comments »

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

177.
By lucifer1004, history, 6 years ago, In English
Unofficial Editorial for Educational Codeforces Round 97 [中文题解](https://cp-wiki.vercel.app/tutorial/codeforces/1437/) ### [problem:1437A] <spoiler summary="Hint"> What will happen if $r\geq2l$? </spoiler> <spoiler summary="Solution"> Suppose that $r\geq2l$, then at least we need to cover $[l,2l]$. Obviously, we must have $a>l$, since the length of the segment is already longer than $l$. Now if $l<a\leq2l$, there are at most $l$ modules of $a$ which are no less than $\frac{a}{2}$, which cannot cover the segment whose length is $l+1$. But if $a>2l$, then $l$ cannot be a good value. On the contrary, if $r<2l$, we can always choose $a=2l$ which will be a valid answer. So this problem can be simplified to judging whether $r<2l$ holds. Time complexity is $O(1)$. </spoiler> <spoiler summary="Code (Python 3)"> ~~~~~ def read_int(): return int(input()) def read_ints(): return map(int, input().split(' ')) t = read_int() for case_num in range(t): l, r = read_ints() print('YES' if l * 2 > r els...
names, we can use a set for each name in order to maintain the largest value of this name.

Full text and comments »

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

178.
By 7oSkaaa, history, 5 years ago, In English
Topics Problems Good Day to you! While a lot of us, when he begins to start competitive programming he found difficult to found problems on some topics in the beginning to practice of it, and same thing for a lot of ICPC Communites that they have started. These are some topic not advanced and videos, problems and articles on them. <br> <spoiler summary="Prefix Sum & Frequency Array"> [Wonderful Coloring](https://codeforces.me/contest/1551/problem/B1) [Do Not Be Distracted](https://codeforces.me/contest/1520/problem/A) [Letter](https://codeforces.me/problemset/problem/43/B) [Pangram](https://codeforces.me/problemset/problem/520/A) [Andryusha and Socks](https://codeforces.me/contest/782/problem/A) [Count Numbers](https://codeforces.me/group/c3FDl9EUi9/contest/262795/problem/A) [Count Characters](https://codeforces.me/group/c3FDl9EUi9/contest/262795/problem/B) [Range Sum Query](https://codeforces.me/group/c3FDl9EUi9/contest/262795/problem/E) [Count a's](https...

Full text and comments »

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

179.
By harsh__h, 3 years ago, In English
Codeforces Round 931 (Div. 2) Editorial [1934A &mdash; Too Min Too Max](https://codeforces.me/contest/1934/problem/A) <spoiler summary="Solution"> <spoiler summary="Hint 1"> What will be answer if there were only $4$ elements in the array? </spoiler> <spoiler summary="Solution"> Suppose if there were only $4$ elements in the array. Let them be $a \leq b \leq c \leq d$. Then the answer will be maximum of the three cases which are listed as follows:- $$|a-b|+|b-c|+|c-d|+|d-a| = 2*d - 2*a$$ $$|a-b|+|b-d|+|d-c|+|c-a| = 2*d-2*a$$ $$|a-c|+|c-b|+|b-d|+|d-a| = 2*(d+c)-2*(a+b)$$ so clearly $2*(d+c)-2*(a+b)$ is the maximum. So, to maximize this we can set $d$, $c$ as large as possible and $a$, $b$ as small as possible i.e. $d=a_n$, $c=a_{n-1}$, $b=a_{2}$ and $a=a_{1}$ where $a_i$ means $i^{th}$ element in sorted order of given array. </spoiler> </spoiler> <spoiler summary="Code (C++)"> ``` #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false);...
So, to maximize this we can set $d$, $c$ as large as possible and $a$, $b$ as small as possible i.e

Full text and comments »

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

180.
By Geothermal, history, 7 years ago, In English
Codeforces Round #570 Solutions Since it will be a little while longer before the editorials for the recent Division 3 Round come out, I thought I'd post some solutions I wrote up. Please feel free to post below if you have any questions or notice any errors. If any of my solutions end up getting hacked, I'll replace the submission and solution text as soon as possible. Links to my submissions are at the bottom of this post. --- **A:** We can easily prove that the answer will not be much bigger than A, so simply iterating through all the possible values until we find one that works will do fine. (As a trivial proof, note that 1003 is interesting, so we will have to test at most 1003 numbers.) Then, the only challenging part from here is finding the sum of the digits of a number, which can be implemented easily with modular arithmetic. --- **B:** Start by sorting the prices. It turns out that only the greatest and least prices matter. We have two key facts to prove: 1. The answer is -1 if the ...
One key observation is that the set of numbers we've added to get our answer will be unique--in

Full text and comments »

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

181.
By TheScrasse, history, 4 years ago, In English
Do you really understand Connected Components DP? [title inspired by [this](https://codeforces.me/blog/entry/83890) blog] Hello everyone, today, during a NEERC virtual contest, I found an unintended solution for problem [problem:1089I]. I've checked all the official submissions and no one of them uses my solution, so I think it's worth sharing it. Abridged statement: count the permutations of $[1, \dots, n]$ such that there are no subarrays of length between $2$ and $n-1$ where all the values are contiguous. For example, the permutation $[2,8,4,6,3,5,1,7]$ is bad because it contains $[4,6,3,5]$ as a subarray. Output the answer (modulo a prime, given in the input) for all $1 \leq n \leq 400$. My solution: - Let's use PIE (inclusion-exclusion principle) on minimal bad subarrays. - Let's use [Connected Components DP](https://codeforces.me/blog/entry/92602), somehow keeping track of minimal bad subarrays.<br><br> - Let $dp_{i,j,k}$ be the number of ordered sets of $j$ connected components with total length $i$, and $k =...
- Let $dp_{i,j,k}$ be the number of ordered sets of $j$ connected components with total length $i

Full text and comments »

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

182.
By arthur_9548, 12 months ago, In English
Editorial: XIII UnB Contest Mirror We hope everyone enjoyed the problems of [contest:106159]! This editorial contains the description of the solutions and their implementation. Feel free to discuss them in the comments! #### Problem A - Author: [user:PedroPacoca,2025-11-05] - Coauthor: [user:duduFreire,2025-11-05] <spoiler summary="Solution"> In this problem, we want to count the number of strings of length $n$ that have at least one occurrence of the given substring. To do this, we will use the Knuth-Morris-Pratt (KMP) algorithm and the automaton constructed from it, with a complexity of $O(m)$. If $n$ were small, we could solve this problem using dynamic programming, calculating, for each $1 \leq i \leq n$, how many ways we can reach state $0 \leq j \leq m$ of the automaton (representing a string with the last $j$ characters equal to the first $j$ of $s$). This solution has $n \cdot m$ states with transitions of the size of the alphabet, resulting in a time complexity of $O(26 \cdot n \cdot m)$, which is...
yet removed in an ordered manner. The order of the segments within the $set$ is as follows: segment

Full text and comments »

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

183.
By darry140, 8 years ago, In English
APIO 2018 pA & pB Editorial Hi Codeforces! I'm the author of the first two tasks in APIO 2018. Although the official site posted only the solution codes, I think the task analyses are equally appreciable, so I decided to publish them here. Here's the [link](http://apio2018.ru/competition/olympiad-materials/) to the problem statements if you haven't seen them yet. ### Problem A. New Home [cut]$\ \ $ #### Subtask 1 Naive solution will work. #### Subtask 2 Simulate all the events (store open/store close/query) in chronological order. Maintain $k$ BSTs, one per each (store-)type. During a query, for each type, check the two neighboring stores of the location. This solution runs in $O(nk\log{n})$. #### Subtask 3 Without the time constraint, the problem becomes querying the maximum of $k$ distance functions, each of which is composed of some segments with slope $=\pm 1$. ![ ](/predownloaded/d4/9a/d49a5993beb91e8191b043e14237d158909bf079.png) Fig. 1: Two types of stores locating at ${1,6...
From Property 1, if we represent the grid as a 2D array having each element as a set of origins

Full text and comments »

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

184.
By shsh, history, 7 months ago, In English
An editorial for IOI 2023: Closing Time While upsolving this problem, I noticed that there appears to be a dearth of editorials; I couldn't find any official ones, and the only unofficial one I found is [this one](https://codeforces.me/blog/entry/121499), which is unfortunately rather poorly formatted. Thus, I've decided to try my hand at writing my own editorial for future reference. Feel free to comment with any questions! **NOTE:** You can also read this editorial on [my blog](https://danielz.fyi/thoughts/closing-time), which has slightly better formatting. ## Basics First, consider how we might solve the problem if $X=Y$. Actually, if we let $d(u,v)$ denote the distance between nodes $u$ and $v$, it turns out the following algorithm works: > In order of increasing $d(u,X)$ and while we have not exceeded the $K$ threshold, set the closing time of node $u$ to be $d(u,X)$. *Proof.* We can use a bounding argument. 1. If we want $k$ nodes to be reachable from $X$, then the closing times of each of these no...
> In order of increasing $d(u,X)$ and while we have not exceeded the $K$ threshold,set the closing

Full text and comments »

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

185.
By MathModel, history, 20 months ago, In English
Robocontest Round 103 Editorial ### Thank you for Participating ! #### [A.Hasan and Binary Function](https://robocontest.uz/olympiads/2619/tasks/A) <spoiler summary="Solution"> We can obtain $n$ from the binary representation as following $$\displaystyle n=\sum_{i=0}^{|s|-1}2^i \times (s_i=\mathtt{'1'})$$ We know that the fact $$\displaystyle \sum_{i=0}^n 2^i=2^{n+1}-1$$ Let’s consider the last active bit i.e. $\mathtt{1}$ is $i$ then $n$ as integer is $$\displaystyle \sum_{i=0}^n 2^i=2^{n+1}-1 \implies \lfloor \log_2(2^{i+1}-1) \rfloor = i$$ thus the answer is the index of last occurrence of $\mathtt{1}$ , Complexity $O(n)$. </spoiler> <spoiler summary="Code"> ```python for _ in range(int(input())): n=int(input()) s=input() ans=0 for i in range(n): if(s[i]=='1'): ans=n-i-1 break print(ans) ``` </spoiler> #### [B.Hasan and Beautiful !](https://robocontest.uz/olympiads/2619/tasks/B) <spoiler summary="Solution"> Maintain two array...
ordered set / segtree and array recovery with answering/handling queries in reverse, or sqrt

Full text and comments »

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

186.
By stefdasca, history, 3 years ago, In English
Easy and Quick Video Tutorials for the CSES Problem Set Hello everybody! This year I decided to be way more active as far as posting educational content goes so I decided to start with posting video tutorials for as many problems from the [CSES problem set](https://cses.fi/problemset/) as possible, as there are many videos out there which often explain solutions by going through way more details than needed or simply make understanding the problem way more complicated than needed. [Here](https://youtube.com/playlist?list=PLS3KRNU_CGM7JclVzF2ynW9qlrkWQOEEW&si=mUmvmmkMWof4ZSRz) is a playlist with the solutions I did so far, with the most recent addition being [Tree Distances I](https://cses.fi/problemset/task/1132), a problem I reviewed today in [this video](https://www.youtube.com/watch?v=DZA4mYWpPno). In order to know what should I focus on going forward in terms of educational content, I would love and be grateful to hear in the comments about topics or problems from CSES or from other places (I prefer more well known/educational...
Easy and Quick Video Tutorials for the CSES Problem Set, In order to know what should I focus on going forward in terms of educational content, I would love

Full text and comments »

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

187.
By Jamshed11, history, 4 years ago, In English
Test Case generator for Trees Recently I had to create large Test Cases for trees so I came up with an idea that involved the use of PBDS / Ordered Set. So I created 2 pbds. One pbds for storing nodes I have included in the tree and the other for storing the remaining nodes. I will take 1 random value u from the first pbds and another random value v from the second pbds and then print u and v (i.e add edge between u and v). Then erase v from second pbds and insert it in first pbds cause now v is also included in the tree. I used pbds as it allows me to take any random value from it and also erasing it in log n time. ~~~~~ #define ll long long int #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; #define pbds tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> void treeTCgenerator() { ll numberOfNodes = 1e5; srand(time(0)); cout << numberOfNodes << "\n"; pbds includedInTree; pbds notIn...
of PBDS / Ordered Set.

Full text and comments »

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

188.
By gridnevvvit, 13 years ago, translation, In English
Editorial Codeforces Round #203 (Div. 2) ##[problem:350A] Let's $v = min(a_{i}), p = max(a_{i}), c = min(b_{i})$. So, if $max(2*v, p) < c$, then answer is $max(2*v, p)$, else answer is $-1$. Author solution: [submission:4632352] ##[problem:350B] Input data represents a graph, by using a array of parents of every vertex. Because every vertex has at most one parent, we can use following solution: we will go up to parent of vertex $v$ ($prev[v]$) until not found vertex with the outcome degree $\ge 2$. It is better to calculate outcome degrees in advance. After all, we will update the answer. This algorithm works in $O(n)$. Author solution: [submission:4632399] ##[problem:350C] First of all, Let's sort all point by increasing of value $|x_i| + |y_i|$, all points we will process by using this order. We will process each point greedily, by using maximum six moves. Now we want to come to the point $(x,y)$. Let's $x \ne 0$. Then we need to move exactly $|x|$ in the $dir$ direction (if $x < 0$ the dir is $L$...
Now the solution. We will have two maps (map<> in С++, TreeMap(HashMap) in Java) to aset of points

Full text and comments »

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

189.
By CountZero, 5 years ago, In English
[Tutorial] Setting up Windows C++ environment — Microsoft edition Hello. This is kind of continuation of this post https://codeforces.me/blog/entry/102287. In this tutorial I'll try to explain how to write and compile C++ code on Windows, using tools provided by (mostly) Microsoft. I'm going to use latest versions. Terminal ======== First of all, let's install [Windows Terminal](https://www.microsoft.com/store/productId/9N0DX20HK701) and [MS PowerShell](https://www.microsoft.com/store/productId/9MZ1SNWT0N5D). Standart windows command line is just not usable. Let's also install [winget](https://www.microsoft.com/store/productId/9NBLGGH4NNS1) &mdash; this is a package manager similar to, for example, homebrew. Maybe chocolatey is better but, again, this one is developed by Microsoft. Of course Microsoft Store isn't mandatory, you can use any other source for these packages. I'd also suggest to try [starship](https://starship.rs/) command prompt &mdash; very useful tool, supports powershell as well. Compilers and tools ================...
In order to properly use all these compilers, you need to set up PATH and other environment

Full text and comments »

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

190.
By Spheniscine, history, 5 years ago, In English
Unofficial AtCoder Beginner Contest 237 Editorial ### [A &ndash; Not Overflow](https://atcoder.jp/contests/abc237/tasks/abc237_a) <spoiler> Note that $N$ has to be read as a signed 64-bit integer type. You could check it by either doing to comparison manually, or casting back and forth between the signed 32-bit integer type. Time complexity: $O(1)$ </spoiler> ### [B &ndash; Matrix Transposition](https://atcoder.jp/contests/abc237/tasks/abc237_b) <spoiler> Simply construct a $W$-by-$H$ matrix, assign $B_{i, j} = A_{j, i}$ for all relevant $i, j$, then output it. Alternatively, if you use Python, the `numpy` library installed in AtCoder gives a really short implementation, as noted in this user editorial: https://atcoder.jp/contests/abc237/editorial/3344 Time complexity: $O(HW)$ </spoiler> ### [C &ndash; kasaka](https://atcoder.jp/contests/abc237/tasks/abc237_c) <spoiler> Note that for a string to be a palindrome, it must start with the same number of contiguous `a`s as it ends with. If there are less con...
- Maintain a dynamic array or ordered set $L$, that is initially empty. - For each element $A_i

Full text and comments »

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

191.
By gojira, 13 years ago, translation, In English
Codeforces Round #196 — Problems Analysis [problem:337A] -------------- First, let's sort the numbers `f[i]` in ascending order. Now assume that the smallest jigsaw puzzle which the teacher purchases consists of `f[k]` pieces. Obviously, she should buy the smallest `n` puzzles which are of size `f[k]` or greater to minimize the difference. These are the puzzles `f[k], f[k+1], ..., f[k+n-1]` (this is not correct when `f[i]` are not distinct and `f[k]=f[k-1]`, but such cases can be skipped). The difference between the greatest and the least size of the puzzles in such set is `f[k+n-1]-f[k]`. To choose the optimal `f[k]`, we can test every `k` between 1 and `m-n` and pick the one producing the least difference. The full algorithm is as follows: ~~~~~ read(n, m, f[1..m]) sort(f[1..m]) best = INFINITY for k = 1 to m-n best = min(best, f[k+n-1] - f[k]) print best ~~~~~ [cut] - [problem:337B] --------- Suppose that the width and height of the screen are `W` and `H` correspondingly. Since `W:H = a:b...
First, let's sort the numbers `f[i]` in ascending order. Now assume that the smallest jigsaw puzzle

Full text and comments »

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

192.
By rng_58, history, 6 years ago, In English
Three Revolutions of AtCoder Hello. Today I announce three revolutions of AtCoder! ### 1. AtCoder Library (ACL) We provide a collection of pre-written codes of various algorithms and data structures. I'll describe details in a [separate post](https://codeforces.me/blog/entry/82400). ### 2. New Color Scheme Previously, we decided colors by ratings. For example, gold for 3600 and above, silver for 3200 and above, red for 2800 and above, etc. However, it's not clear what the rating values mean, for example, 2800. If we design the rating system relatively well, in the short term the rating 2800 corresponds to a certain level. The skill required to reach 2800 today is probably similar to that of a year ago. However, the structure of the contests may change, the number of users may change, the average level of users may change, etc., and the exact value of ratings is very sensitive to these changes (and it may cause inflation/deflation). Now I believe ranks are more robust against inflation/deflation and ...
. Internally, we are planning to classify problems as follows (in the order of difficulty from top to

Full text and comments »

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

193.
By Ripatti, 14 years ago, translation, In English
Editorial for Codeforces Round #150 **Adiv2.** Consider an array $A$ of integers in range from 1 to $nk$. Let's remove from $A$ all numbers $a_i$ and all other numbers store into an array $B$. The array $B$ will have $(n-1)k$ elements. Now for $i$-th kid you should output numbers $a_i$, $B[(n-1)*(i-1) + 1]$, $B[(n-1)*(i-1) + 2]$, ... $B[(n-1)*(i-1) + n - 1]$ ($B$ is 1-based). Author is [user:Gerald] [cut] . **Bvid2.** Solution 1. You should write some bruteforce solution over all numbers with no more than 9 digits (number $10^9$ should be considered separately). Bruteforce algo seems like this: ~~~~~ dfs( int num ) // run it as dfs(0) if (num > 0 && num <= n) ans++ if (num >= 10^8) return for a = 0..9 do if num*10+a>0 then if number num*10+a has no more than 2 different digits then dfs( num*10+a ) ~~~~~ ans will store the answer. After that you wrote bruteforce, you can run it and see that it works fast (that is same time for any testcase). Solution 2. Let's build al...
some edge $(u,v)$ (order of vertices is important, i.e. you should also check edge $(v,u)$). Now you

Full text and comments »

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

194.
By YipChip, history, 6 months ago, In English
Farey sequence and Approximation of real number First, the Farey sequence $F_n$ represents the set of all completely reduced proper fractions with denominators not exceeding $n$, arranged in ascending order of value. Formally speaking, $$F_n = \left\{\frac{p}{q} \bigg\vert 0 < p < q \le n, \, \gcd(p, q) = 1\right\}$$ The asymptotic size of this sequence is $\sum\limits_{i = 1}^{n} \varphi(n) \sim \frac{3}{\pi^2}n^2 + o(n \log n)$. Regarding the Farey sequence, there are two classic conclusions: - If $\frac{a}{b}$ and $\frac{c}{d}$ are two consecutive elements in $F_n$, then $\frac{a + c}{b + d}$ is also a valid Farey fraction. - If $\frac{a}{b}$ and $\frac{c}{d}$ are two consecutive elements in $F_n$, then their next element $\frac{p}{q}$ satisfies $$\begin{cases}p = \left\lfloor\frac{n + b}{d}\right\rfloor c - a \\ q = \left\lfloor\frac{n + b}{d}\right\rfloor d - b\end{cases}$$ We will only prove the second theorem above. For the Farey sequence of order $n$, two adjacent terms $\frac{a}{b} < \frac{c}{d}$ satisfy...
First, the Farey sequence $F_n$ represents the set of all completely reduced proper fractions with

Full text and comments »

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

195.
By Nakagawa.Kanon, history, 4 months ago, In English
Me trying to study Atcoder World Tour Finals 2026 Algorithm : E — Even Rows ![ ](/predownloaded/77/c3/77c355894f49137e2eda44b44cc2e53a9fd7371e.png) It took days for me to just to barely understand the editorials and from my own opinion, it was so obscure and omitted lot of thing to barely make sense so I had an idea to share my own analysis here for everyone to discuss. Please note this is a wall of text since I want to elaborate on every ambiguous part of editorial and explain my flow of logic as much as possible and for anyone patient enough to read through the end, please share some advice and opinion to optimize and speed up my logic arguments, maybe fixing some typo or request some clarification of my explanation if possible. Thank you for reading. First about the problem statement, it can be divide into 3 parts : - Input : + A table with size $N\times M$ + Each cell is either empty or has a piece on it - Algorithm 1 : Take a table with pieces on it as input + Define the way to move a piece in the table + The ...
to each other in a bad match chain. The edges will form a set of non crossing, ordered path

Full text and comments »

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

196.
By prabowo, history, 6 years ago, In English
[Tutorial] Reachability Tree / DSU-tree This is not to be confused with [DSU on Tree (Sack)](https://codeforces.me/blog/entry/44351). ### What can a Reachability Tree do? Suppose you are given a weighted (connected) undirected graph of $N$ vertices and $M$ edges. Let's define an ordering of the edges, for example, the edges are ordered in the ascending/descending order of their weights. The reachability tree can help you with: - Find the minimal/maximal weight of the edges when traversing from vertex $u$ to vertex $v$. - Find the set of vertices that are reachable from a given vertex using the first $x$ edges, for some arbitrary $x$. You can store some information in this set of reachable vertices, such as the maximum value or the sum of values of all the reachable vertices. ### Constructing a Reachability Tree The reachability tree is a rooted tree that consists of $N + M$ nodes. The tree will have $N$ leaves which represent the original vertices of the graph, and the rest of $M$ internal nodes represent th...
Unlike the usual reachability tree where we add edges, we will add the vertices in descendingorder

Full text and comments »

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