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 ...
Knowing the above facts, it is clear that we can apply binary search, apply binary search on the answer $Z$, which is less than $a_1+b_1$, or Alice can end the game, Using binary search on the answer, you can solve the whole problem in $O((n+m)\log A+n\log n+m\log

Full text and comments »

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

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

Full text and comments »

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

3.
By Um_nik, history, 5 years ago, In English
Things I don't know I'm just in a mood to shitpost. Don't take it too seriously. Things that I have heard of, but don't know (imagine how many things I haven't even heard of): - Li-Chao Segment Tree - Segment Tree Beats - RMQ in $O(n)$/$O(1)$ - Any self-balancing tree except treap - Link-cut tree - Wavelet tree - Mergesort tree - Binomial heap - Fibonacci heap - Leftist heap - Dominator tree - 3-connected components in $O(n)$ - $k$-th shortest path - Matching in general graph - Weighted matching in general graph - Preflow-push - MCMF in $O(poly(V, E))$ - Minimum arborescence (directed MST) in $O(E \log V)$ - Suffix tree - Online convex hull in 2D - Convex hull in 3D - Halfplane intersection - Voronoi diagram / Delaunay triangulation - Operation on formal power series (exp, log, sqrt, ...) (I know the general idea of Newton method) - How to actually use generating functions to solve problems - Lagrange Inversion formula - [...
learning useless algorithms, go and solve some problems, learn how to use binary search., . Stop learning useless algorithms, go and solve some problems, learn how to use binary search.

Full text and comments »

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

4.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #6 Hello, codeforces! Sorry for the long break, but the last weeks of holidays and the first weeks of academic year took my attention. I hope today's trick will make you forgive me. :P I invented this trick a few years ago, but for sure I wasn't first, and some of you already know it. Let's consider the following **interactive** task. There are $n$ ($1 \leq n \leq 10^5$) hidden integers $a_i$, each of them from range $[1, 10^{18}]$. You are allowed to ask at most $103000$ queries. In one query you can choose two integers $x$ and $y$ ($1 \leq x \leq n, 1 \leq y \leq 10^{18}$) and ask a question ''Is $a_x \geq y$?'' The task is to find the value of the greatest element in the hidden array. The checker **isn't** adaptive. Unfortunately, this task is only theoretical, and you cannot solve it anywhere, but it'll turn out, that solution can be handy in many other, much more complicated problems. [cut] $ $ Even beginners should be able to quickly come up with a solution which ask...
course, does $n$ independent binary searches, to find each $a_i$., hidden array like in the $n \cdot log(d)$ solution, but before doing the binary search, ask if $a_i, not — to skip the binary search. It gave me many more points (it was an IOI-like problem) even, we do the binary search to find the highest possible result from this source, and then we print the, )$ solution, but before doing the binary search, ask if $a_i$ that we are looking at right now is strictly, A filled circle means that we do the binary search, an empty circle means that we skip this number., Of course, this solution can do the binary search even $n$ times, for example when the hidden array, Of course, we should do the binary search when the prefix maximum changes (increases, in particular, Some techniques come to mind, for example we could do all binary searches at the same time, ask for

Full text and comments »

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

5.
By antontrygubO_o, 6 years ago, In English
Some thoughts on recent discussions Hello everyone! I finally decided to write some response/explain my view after all recent discussions of my problems and rounds I coordinate, and I would like to make a few points. **1.** After some recent contests there were a lot of comments saying that Data structure problems should appear as easy problems (say, D2A-D2D in a Div2 of $6$ problems) ![ ](https://i.imgur.com/fmA8zgE.png) ![ ](https://i.imgur.com/m4pJLv6.png) ![ ](https://i.imgur.com/JsryG77.png) I don't think I agree with this. To begin with, I don't think that having Data Structure problem is a requirement for a good contest at all, not just in first few positions. ![ ](https://i.imgur.com/VWAOgxg.png) However, for positions D2A-D2D, I just don't see a way to properly include data structure problems. Take some Data Structure problem, it consists from two parts: <ul> <li> Knowing/implementing the Data Structure </li> <li> Actually thinking about the problem, and how this Data Structure...
impossible hard to create an interesting DP/Binary Search/Graph problem which could, And I don't want to accept standard problems on DP/Binary Search/Graphs just to make the set more, [problem:1363D] is binary search problem.

Full text and comments »

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

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

Full text and comments »

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

7.
By parveen1981, history, 6 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...
comprehensive Binary Search lecture](https://codeforces.me/blog/entry/67509) - [Sublime Text, without using std::map](https://codeforces.me/blog/entry/15701) - [Binary search on real values, ) - [[Tutorial] Initializing Binary Indexed Trees in linear time](https://codeforces.me/blog/entry/63064

Full text and comments »

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

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

Full text and comments »

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

9.
By tourist, history, 7 years ago, In English
Codeforces Global Round 5 Editorial Enjoy! <spoiler summary="A. Balanced Rating Changes"> [tutorial:1237A] <spoiler summary="Solution by tourist"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int flag = 1; for (int i = 0; i < n; i++) { int x; cin >> x; if (x % 2 == 0) { cout << x / 2 << '\n'; } else { cout << (x + flag) / 2 << '\n'; flag *= -1; } } return 0; } ~~~~~ </spoiler> </spoiler> <spoiler summary="B. Balanced Tunnel"> [tutorial:1237B] <spoiler summary="Solution by tourist"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> a(n), b(n); for (int i = 0; i < n; i++) { cin >> a[i]; --a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; --b[i]; } vector<int> pos(n); for (int i = 0; i < n; i++) { pos[b[i...
[tutorial:1237E]

Full text and comments »

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

10.
By Radewoosh, 8 years ago, In English
Blogewoosh #3 Hello, codeforces! This time I've decided to choose a task from my own contest which took place last April and was known as the Grand Prix of Poland. If you want to write this contest virtually in the future, then consider not reading this blog. If you've participated in this contest and maybe even solved this task, then anyway I recommend reading it, cause this task has many very different solutions, each of them being very interesting (in my opinion). It's also a reason why this blog is longer than previous ones. I'll write about task C "cutting tree" (not uploaded to the ejudge yet :/). The statement goes as follows: You are given a tree with $n$ vertices ($1 \leq n \leq 2 \cdot 10^5$). The task is to calculate $f(k)$ for each integer $k$ from the range $[1, n]$ where $f(k)$ is defined as the maximum number of connected components of size $k$ which we can "cut off" from the tree. A connected component of size $k$ is a set of $k$ vertices such that it's possible to traverse ...
$k$ up to $\sqrt{n \cdot \log(n)}$, then we have to do only $O(\sqrt{\frac{n}{\log(n)}})$binary, do the binary search starting somewhere in one of these subtrees, then we could take this vertex, following algorithm is trivially correct: let's do a binary search from the bottom of this caterpillar to, know how many vertices he should want to cut doing the binary search., leaves cause we should start the binary search in them. Which leaves should we take? For each vertex, the value of $f(m+1)$. At this point, everybody should think about a binary search. So, let's use it, $) iteratively instead of recursively, making it a few times faster. Secondly, ourbinary search isn't, )$. At this point, everybody should think about a binary search. So, let's use it to determine for how, The last thing is how to do this binary search. This part is easy. We need jump-pointers. I won't, We can observe that whenever we do the binary search, we follow one heavy path in the tree (if we'd

Full text and comments »

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

11.
By tourist, history, 10 years ago, translation, In English
VK Cup 2017 Round 3 + Codeforces Round #412 -- Tutorial Here is the tutorial of VK Cup 2017 Round 3 and Codeforces Round #412. Enjoy! <spoiler summary="Is it rated?"> [tutorial:807A] <spoiler summary="Code"> ~~~~~ n = int(input()) results = [] for i in range(n): results.append(list(map(int, input().split()))) for r in results: if r[0] != r[1]: print("rated") exit() for i in range(n): for j in range(i): if results[i][0] > results[j][0]: print("unrated") exit() print("maybe") ~~~~~ </spoiler> </spoiler> <spoiler summary="T-Shirt Hunt"> [tutorial:807B] <spoiler summary="More efficient code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int p, x, y; cin >> p >> x >> y; for (int s = y; ; s++) { if (s % 50 != x % 50) { continue; } bool me = false; int i = s / 50 % 475; for (int j = 0; j < 25; j++) { i = (i * 96 + 42) % 475; if (i + 26 == p) { me = true; ...
~~~~~ #include

Full text and comments »

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

12.
By Golovanov399, 7 years ago, In English
C++ tips and tricks Hello, codeforces. I would like to tell you about some tricks and constructions I use in C++. They are not hidden or anything, moreover, most of them are from stl or maybe well known among software engineers, but I often see codes where something is done by hand in, say, 5 lines, while in stl there is a function which does the same. The things below are filtered by my personal sense of non-popularity (so no `__builtin` functions) and usage frequency (so there almost surely are similar things I don't know about) and are not really sorted in any reasonable order. Let's begin. [cut] <hr> - ### `all(x)` This may be an exception to the rule of non-popularity -- this is quite widely used, but some next items will depend on `all(x)`, so I define it here. So, I talk about ```[c++] #define all(x) (x).begin(), (x).end() ``` Now sorting a vector looks like `sort(all(vec))` instead of `sort(vec.begin(), vec.end())`. However, it's not all about this define. Imagine you nee...
implement your own binary search like, If we talk about binary search: assume you have a vector and a predicate `p(x)` so that `p(x

Full text and comments »

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

13.
By Um_nik, history, 10 years ago, In English
Bin search and relative error Suppose we want to solve a problem by doing binary search on answer. Then the answer will be checked against jury's answer by absolute or relative error (one of them should be smaller then $\epsilon$). For simplicity we will assume that our answer is always greater than $1$ and smaller than $B$. Because of that, we will always use relative error rather than absolute. Suppose we have made $n$ iterations of our binary search &mdash; what information do we have now? I state that we know that real answer is lying in some segment $[x_{i}, x_{i+1}]$, where $1 = x_{0} < x_{1} < \ldots < x_{i} < \ldots < x_{2^{n}} = B$. And what is great &mdash; we can choose all $x_{i}$ except for $x_{0}$ and $x_{2^{n}}$. Now, for simplicity, we will also assume that we will answer $x_{i+1}$ for segment $[x_{i}, x_{i+1}]$ and the real answer was $x_{i}$ &mdash; it is the worst case for us. It is obvious that we will not do that in real life, any other answer would be better, but you will get the idea. ...
Bin search and relative error, standard binary search (because absolute error smaller than relative); is answer is bigger than $1, the segment in binary search)., what we do by binary search with absolute errors. $\frac{\Delta x_{i}}{x_{i}} = \frac{\Delta x_{j, How to write such binary search? We want to choose $m$ in such a way that $\ln m - \ln l = \ln r, Suppose we have made $n$ iterations of our binary search — what information do we have now? I, Suppose we want to solve a problem by doing binary search on answer. Then the answer will be

Full text and comments »

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

14.
By tourist, history, 9 years ago, translation, In English
Hello 2018 -- Tutorial Here is the tutorial of Hello 2018. Enjoy! <spoiler summary="Modular Exponentiation"> Problem writer: [user:tourist,2018-01-08] [tutorial:913A] <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n, m; scanf("%d %d", &n, &m); printf("%d\n", n >= 31 ? m : m % (1 << n)); return 0; } ~~~~~ </spoiler> </spoiler> <spoiler summary="Christmas Spruce"> Problem writer: [user:BudAlNik,2018-01-08] [tutorial:913B] <spoiler summary="C++ solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> p(n), deg(n); for (int i = 1; i < n; i++) { cin >> p[i]; p[i]--; deg[p[i]]++; } vector<int> sons_leaves(n); for (int i = 0; i < n; i++) { if (deg[i] == 0) { sons_leaves[p[i]]++; } } for (int i = 0; i < n; i++) { if (deg[i] > 0 && sons_leaves[i] < 3) { puts("No"); return 0; } } puts...
~~~~~ #include

Full text and comments »

Tutorial of Hello 2018
  • Vote: I like it
  • +463
  • Vote: I do not like it

15.
By sdnr1, history, 8 years ago, In English
[Tutorial] Searching Binary Indexed Tree in O(log(N)) using Binary Lifting **NOTE** : Knowledge of Binary Indexed Trees is a prerequisite. ## Problem Statement Assume we need to solve the following problem. We have an array, $A$ of length $N$ with only non-negative values. We want to perform the following operations on this array: 1. Update value at a given position 2. Compute prefix sum of $A$ upto $i, i \leq N$ 3. Search for a prefix sum (something like a `lower_bound` in the prefix sums array of $A$) [cut] <br> ## Basic Solution Seeing such a problem we might think of using a Binary Indexed Tree (BIT) and implementing a binary search for type $3$ operation. Its easy to see that binary search is possible here because prefix sums array is monotonic (only non-negative values in $A$). The only issue with this is that binary search in a BIT has time complexity of $O(log^2(N))$ (other operations can be done in $O(log(N))$). Even though this is naive, here is how to do it: <spoiler summary="Implementation"> `int sum(pos)` -> comput...
[Tutorial] Searching Binary Indexed Tree in O(log(N)) using Binary Lifting, [TopCoder BIT Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/ binary, a problem we might think of using a Binary Indexed Tree (BIT) and implementing abinary search for, #### How binary lifting is used?, #### What is binary lifting?, **NOTE** : Knowledge of Binary Indexed Trees is a prerequisite., /binary -indexed-trees/](https://www.topcoder.com/community/data-science/data-science-tutorials/ binary, /data-science-tutorials/binary-indexed-trees/), which I recommend you to take a look at if you, 3. Search for a prefix sum (something like a `lower_bound` in the prefix sums array of $A$), In binary lifting, a value is increased (or lifted) by powers of $2$, starting with the highest, Let us assume we want to search for `v = 27`. The blue arrow shows the direction in which we, The only issue with this is that binary search in a BIT has time complexity of $O(log^2(N))$ (other, We will make use of **binary lifting** to achieve $O(log(N))$ (well I actually do not know if this, binary lifting in trees). If it is false, then target value lies between `pos` and `pos + 2^i`, so we, search for type $3$ operation. Its easy to see that binary search is possible here because prefix

Full text and comments »

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

16.
By peltorator, 18 months ago, In English
"Algorithms in Depth" Stream Series: Kicking Off With FFT Hi Codeforces! I’ve long believed that it's _really_ worth revisiting the same competitive programming topics multiple times. The first time, you’re just trying to survive and maybe grasp the basics. The second time, you’ve solved some problems, you know where you got confused, and you're ready to absorb more. By the third time, you’ve seen and solved enough to start appreciating the subtleties — the tricks, advanced applications, deeper meaning. But most lectures I’ve seen are designed as a one-size-fits-all — trying to cover everything from scratch _and_ dive into the advanced stuff in one go. That’s rarely optimal. Take binary search. I once talked about it for six hours straight. A beginner at that lecture would’ve probably quit CP immediately. And that’s ok. Beginners don’t need all that. But the truth is, there _is_ that much depth to explore even in seemingly simple topics like binary search — once you're ready. Yet many people only see the beginner version once and mo...
in one go. That’s rarely optimal. Take binary search. I once talked about it for six hours, Take binary search. I once talked about it for six hours straight. A beginner at that lecture

Full text and comments »

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

17.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Data structures Today I want to introduce you some very very useful data structures. In this lecture, we are trying to improve your data structures skills, stay with us and click on **read more**. [cut] Important data structures : Trees ----- Trees are one of the most useful data structures.A tree is a connected-acyclic graph.There are too many types of trees, like : rooted trees, weighted trees, directed trees, tries, etc. Partial sum ----------- There are two types of problems solvable by partial sum. 1.Problems which you are asked to answer some queries about the sum of a part of elements (without modify queries). Solution of all of this problems are the same. You just need to know how to solve one of them. Example : You are asked some queries on an array $a_1,a_2,...a,_n$. Each query give you numbers $l$ and $r$ and you should print $a_l + a_{l+1} + ... + a_r$ . Solution : You need to build another array $s_1, s_2, ..., s_n$ which $s_i = a_1 + a_2 + ... + a_i$ ...
less than another one, find their $LCP$ using binary search + hash and then check the next character, ![ ](http://programminggeeks.com/wp-content/uploads/2014/01/nodes-in-binary- search-tree.png), A binary search tree (BST) is a binary rooted tree that every node has a value, and for each node, Binary Search Tree (BST) ------------------------, Binary search trees are too useful.

Full text and comments »

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

18.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #7 Hello, codeforces! Long time no see, right? So maybe it's a good idea to try to return to my blogs slowly. This time the blog will be about a trick, which usually isn't necessary to solve a task, but can be useful to make implementation much more comfortable. Let's look at [this](https://codeforces.me/contest/932/problem/F) problem. It is about some DP on a tree in which we have to use convex hull trick to improve the complexity. The task requires merging two convex hulls with "smaller to bigger" trick. I recommend you to read the statement before reading the rest of the blog (and the [editorial](https://codeforces.me/blog/entry/57796) if you don't know how to solve it). [cut] $ $ So, how to merge two convex hulls? If we keep them in something like the set from C++, then we can just take every element from the smaller one and try to add it to the bigger one. Unfortunately, adding one element in this way requires some ifology and care. It's hard to implement it, especiall...
the other side, we have to do a binary/ternary search $O(\log(n))$ times in each node, instead of, to one of the nodes in this subtree. Normally, it would be done using a binary /ternarysearch on a, . Normally, it would be done using a binary/ternary search on a convex hull, so we can simply do it on

Full text and comments »

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

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

Full text and comments »

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

20.
By peltorator, 5 years ago, In English
8-hour Long Stream In Support Of Ukraine (With Great Guests!) I know that lots of you were saying that Codeforces should stay out of politics when there were lots of blog posts supporting Ukraine a couple of weeks ago. Well, I respect your opinion, but I can't agree. If you see a binary search tutorial on the "Top" page, do you complain about it if you're not interested in binary search, or do you just ignore it? And at the end of the day, it's not really about politics, but about people's lives. Having said that, I'd like to invite you to join my 8-hour long live stream on YouTube against the Russian invasion of Ukraine **next Sunday (27th of March) from 10 AM till 6 PM Ukrainian time** (be careful, 27th of March is a daylight saving start in Ukraine and a lot of other countries, but it may not be the case for your country, so check your timezone using [this link](https://www.timeanddate.com/worldclock/fixedtime.html?msg=Live+Stream&iso=20220327T10&p1=367&ah=8)). Сurrent plan is (all time periods are in Ukrainian timezone): 10:00-10:30 ...
agree. If you see a binary search tutorial on the "Top" page, do you complain about it if you're not

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

23.
By himanshujaju, history, 10 years ago, In English
Parallel Binary Search [tutorial] [Click here to download the pdf](https://www.dropbox.com/s/cndim2lv872dzen/parallel-binary-search.pdf?dl=0) Pre Requisites -------------- Binary Search &mdash; How it works and where can it be applied! Motivation Problem ------------------ We aim to solve this problem : [Meteors](http://www.spoj.com/problems/METEORS/) The question simply states : There are $N$ member states and $M$ sectors. Each sector is owned by a member state. There are $Q$ queries, each of which denote the amount of meteor shower in a $[L,R]$ range of sectors on that day. The $i^{th}$ member state wants to collect $reqd[i]$ meteors over all its sectors. For every member state, what is the minimum number of days it would have to wait to collect atleast the required amount of meteors? Solution -------- The naive solution here is to do a binary search for each of the $N$ member states. We can update in a range using segment trees with lazy propagation for each query. The time complexity of such a ...
Parallel Binary Search [tutorial], solutions to the mentioned problems are also welcome, almost every question on parallelbinary, the linked list and update their binary search interval accordingly., we group member states by the range of their binary search. In the first step, all member states lie, "A cool way to visualize this is to think of a binary search tree. Suppose we are doing standard, $ denoting range of binary search for each member state. 3. range update and query structure for $Q$ queries, -search.pdf?dl=0) Pre Requisites -------------- Binary Search — How it works and where can it be, Let's see if there's something we are overdoing. For every member state, the binary search applies, Pre Requisites -------------- Binary Search — How it works and where can it be applied!, So what Parallel Binary Search does is move one step down in $N$ binary search trees simultaneously, Solution -------- The naive solution here is to do a binary search for each of the $N$ member, [Click here to download the pdf](https://www.dropbox.com/s/cndim2lv872dzen/parallel-binary

Full text and comments »

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

24.
By pashka, history, 6 years ago, In English
EDU: Binary Search Hello Codeforces! New [lesson](https://codeforces.me/edu/course/2/lesson/6) in English EDU section. This time I will talk about binary search. <img src="/predownloaded/f1/a3/f1a3c7a64d01066e4668251e45c8b08b6b26a88d.jpg"/> <center style="margin:2.5em;"> <a href="/edu/courses" style="text-decoration:none; font-size:18px; background-color:#01579B; color:white; font-weight:bold; padding:0.5em 1em;">Go to EDU &rarr;</a> </center> More about EDU section you can read in [this](/blog/entry/79530) post. Hope it will be helpful, enjoy!
EDU: Binary Search, talk about binary search.

Full text and comments »

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

25.
By Um_nik, history, 4 years ago, In English
Hooray! Binary Search Episode! Just a reminder that [Um](https://codeforces.me/blog/entry/113418) still exists and I just posted [Episode 9](https://youtu.be/kHxaTXQfu9E). And it is just 0:54 long, no reason not to watch. Magic words to attract attention: Um_nik does binary search, $O(\log N)$ per query online solution to [Stamp Rally](https://atcoder.jp/contests/agc002/tasks/agc002_d). I switched to the "1 video every 2 days" schedule, it seems manageable. The [list](https://um-nik.notion.site/cff90514c6174afcb4ab8ff5dbb5b9a3?v=88948840b1494f18aea5535a6329a914) now contains 15 problems. Also, there are slides for the problems for which videos are already posted. [Checklist](https://um-checklist.aryanc403.com/) by aryanc403 for tracking your progress on Um problems, [Playlist](https://www.youtube.com/watch?v=oZfoiVr0OWs&list=PL_2SIhFoM1-sAlY5JENWxFi3IiXD8WB-M) with all Um episodes, [My YouTube channel](https://www.youtube.com/@umnik_team), [Discord](https://discord.gg/HPjyarXvsN), [Um_nik World](https://bi...
Hooray! Binary Search Episode!, words to attract attention: Um_nik does binary search, $O(\log N)$ per query online solution to

Full text and comments »

Tags um
  • Vote: I like it
  • +387
  • Vote: I do not like it

26.
By kpw29, 6 years ago, In English
Meet IT Codeforces Round Editorial Thank you very much for taking part in the contest! <spoiler summary="Contest timeline"> - -0:05. Starting the chat with the Questions Answering team: [user:tnowak,2020-11-15] and our beloved coordinator [user:antontrygubO_o,2020-11-15]. We hope that there won't be that many questions :) - -0:01. One minute to go! I hope that everything goes smoothly. I'm so afraid of posting the editorial accidentally that I moved this timeline into another blog... - 0:01. First blood in Div2! Congratulations to [user:majorro,2020-11-15]!. - 0:03. First blood in Div1 as well! Congratulations to [user:Errichto,2020-11-15], your knapsack is ready for a journey to win! - 0:04. [user:Sho10,2020-11-15] first to solve Div2B. Well done! - 0:05. We also have the first question. So far so good... - 0:06. [user:Um_nik,2020-11-15] gets the first pretests pass in Div1B. The cheaters are caught! - 0:09. [user:bandiaoz,2020-11-15] packs the first Knapsack in Div2! A difficulty spike is coming... - 0:12....
Binary search is your friend. To determine if the answer is bigger

Full text and comments »

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

27.
By ivan100sic, 5 years ago, In English
Binary search on integers using C++20 **Never write binary search again\*!** Often, solving a problem involves finding the smallest integer satisfying some predicate. The C++20 Ranges library allows us to run generic algorithms on ranges. Ranges can be backed by real data, such as ranges constructed from `std::vector`s, or they could be purely logical, such as `std::ranges::iota_view`. This class can construct views given two values. In case those values are integers, the constructed `range` supports random-access, meaning that random-access algorithms such as `std::ranges::lower_bound` can run efficiently i.e. in $O(\log n)$. For example, `std::ranges::iota_view(0, 5)` returns a view representing integers $[0, 1, 2, 3, 4]$. If you need to find the smallest integer value $v$ between $l$ and $r-1$ inclusive satisfying a predicate $p$ with the binary search property, or $r$ if it doesn't exist, you can do this in one line of C++ code: ``` auto v = *std::ranges::lower_bound(std::ranges::iota_view(l, r), true, {},...
Binary search on integers using C++20, `std::less`, it can be used in binary search since `false < true` is true in C++. It is, better than writing binary search manually., predicate $p$ with the binary search property, or $r$ if it doesn't exist, you can do this in one line, **Never write binary search again\*!**

Full text and comments »

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

28.
By pashka, 6 years ago, In English
ITMO Algorithms Course Hello Codeforces! I teach a course on algorithms and data structures at ITMO University. During the last year I was streaming all my lectures on [Twitch](https://twitch.tv/pmavrin) and uploaded the videos on [Youtube](https://www.youtube.com/pavelmavrin). This year I want to try to do it in English. This is a four-semester course. The rough plan for the first semester: - Algorithms, complexity, asymptotics - Sorting algorithms - Binary heap - Binary search - Linked lists, Stack, Queue - Amortized analysis - Fibonacci Heap - Disjoint Set Union - Dynamic Programming - Hash Tables The lectures are open for everybody. If you want to attend, please fill out [this form](https://docs.google.com/forms/d/e/1FAIpQLSfHIhiwAUyKfnt92NluNj2tLnczp0oxu5szPS4S_PF3N7EUDA/viewform) to help me pick the optimal day and time. See you!
, complexity, asymptotics - Sorting algorithms - Binary heap - Binary search - Linked lists, Stack, - Algorithms, complexity, asymptotics - Sorting algorithms - Binary heap - Binary search

Full text and comments »

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

29.
By cip999, 5 years ago, In English
Editorial of Global Round 15 We hope you liked the problems! Before we go ahead with the editorial, let us make some general comments about this round. Problems A, B, C, D, E, F are "div 2" problems, while problems G, H, I are meant to be solved by Grandmasters. Overall, our goal was to provide a problemset that could be enjoyable for a wide range of participants and such that the winner could solve all the problems. There were three big "jumps" in the difficlty gaps between consecutive problems. Problems A and B are meant to be easy, many contestants have the skills and the techniques to attack them (and, maybe, to solve them). Problems C, D, E, F are gradually harder but the difficulty gap between C and F is not as large as usual (and this is reflected in the score distribution). The same holds for problem G, H, I; the difficulty gap between G and I is relatively small (but there is a big score difference because coding I is much harder). Sadly, we discovered 14 minutes into the round that problem I...
Binary search on the $2$-adic evaluation of the number of points on the

Full text and comments »

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

30.
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...
I won't discuss this approach, it's using binary search an will get TLE., binary search for counting. So, memory will be $O(n.log(n))$ (each element is in $O(log(n))$ nodes

Full text and comments »

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

31.
By gepardo, history, 9 years ago, In English
Sqrt-tree: answering queries in O(1) with O(NloglogN) preprocessing. Hello, Codeforces! Some time ago I invented an interesting data structure and I'd like to share it with the community. Maybe, it was known before, and if you knew about it before my blog post, please share the link to the source. # What can the data structure do? Given an array $a$ that contains $n$ elements and the operation $op$ that satisfies associative property: $(x\ op\ y) op\ z = x\ op (y\ op\ z)$ is true for every $x$, $y$ and $z$. So, such operations as $gcd$, $\min$, $\max$, sum, multiplication, $and$, $or$, $xor$, etc. satisfy these conditions. Also we have some queries $l, r$. For each query, we need to find $a_l\ op\ a_{l+1}\ op\ \dots op\ a_r$. Let's call such queries $q(l, r)$. My data structure can process such queries in $O(1)$ time with $O(n \cdot \log \log n)$ preprocessing time and $O(n \cdot \log \log n)$ memory. # How it works? [cut] # ## 1. Sqrt Let's do a sqrt-decomposition. We divide our array in $\sqrt{n}$ blocks, each block ha...
One of the most obvious optimization is to binary search the tree node we need. Usingbinary search

Full text and comments »

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

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

Full text and comments »

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

33.
By adamant, history, 5 years ago, In English
Multi-dimensional ternary search Hi everyone! I'm currently trying to write an article about $\lambda$-optimization in dynamic programming, commonly known as "aliens trick". While writing it, I stumbled upon a fact which, I believe, is a somewhat common knowledge, but is rarely written out and proved explicitly. This fact is that we sometimes can repeatedly use ternary search when we need to optimize a multi-dimensional function. Thanks to - [user:mango_lassi,2021-12-30] for a useful discussion on this and for counter-example on integer ternary search! - [user:Neodym,2021-12-31] for useful comments and remarks about the article structure. [cut]<br> #### $1$-dimensional search --- **Def. 1**. A function $f : X \to \mathbb R$, where $X \subset \mathbb R$, is called **unimodal** if there is a segment $[L, R]$ such that $f(x)$ strictly decreases on $(-\infty, L] \cap X$, strictly increases on $x \in [R,+\infty) \cap X$ and is equal to its global infimum on $x \in [L, R] \cap X$. --- **Ternary s...
Multi-dimensional ternary search, generalization of binary search on multi-dimensional case? Quasi-linear functions?, meaningful generalization of binary search on multi-dimensional case? Quasi-linear functions?

Full text and comments »

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

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

Full text and comments »

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

35.
By Errichto, 5 years ago, In English
3 Hard Interactive Problems Hi. I think these are nice medium-hard interactive problems. I will discuss solutions in a stream today at https://www.twitch.tv/errichto. UPD, recording is here https://youtu.be/9oEihYrAR5kUPD and I added text solutions in this blog. P1. **Mostly A** &mdash; You're given two integers $N$ and $K$ ($N \leq 50\,000$, $K \leq 10$). You need to find a hidden string of length $N$ with lowercase English characters a-z. At most $K$ characters are different than 'a'. You can choose your own string of length $N$ and you will get info YES/NO whether your string is lexicographically smaller than the hidden one. There is no explicit limit on the number of queries. There's still some time limit (say, 2 seconds). Hard version: Minimize the number of queries. <spoiler summary="slow solution"> It seems reasonable to discover characters one by one from left to right. Let's say that we already know the prefix `raay` and we're looking for the fifth character. We can binary search it in $...
As always, use binary search., like `raayazzzzz...`. If the hidden string is lexicographically greater than this, we runbinary or, possible in $O(\log n)$ by binary searching the length of such a block. For example, asking a query, After finding the length of a block of 'a', binary search the next character from 'b' to 'z'. The, binary search it in $\log 26$ queries with queries like `raaymzzzzz...` to know if the fifth, binary search. Each iteration requires iterating possible pairs and there are initially $N^2$ of

Full text and comments »

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

36.
By sammyuri, 6 months ago, In English
Spectral::Cup 2026 Round 2 (Codeforces Round 1100, Div. 1 + Div. 2) Editorial Thank you for participating in our round! We hope you enjoyed the problems as much as we enjoyed preparing them. <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Absolute Cinema contest - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2229A] Idea by: [user:Intellegent,2026-05-23] Prepared by: [user:Intellegent,2026-05-23] Editorial by: [user:reirugan,2026-05-23] <spoiler summary="Hint 1"> Let $y$ denote the final position of all of the slimes. Then it is optimal to choose $x = y$ for every operation. </spoiler> <spoiler summary="Hint 2"> Let $\mathrm{mn}$ denote the minimum value in $a$, a...
This allows you to binary search for the final answer. , upper and lower bound for the binary search which are A apart, so time complexity ends up being $O(n, Binary search is your friend.

Full text and comments »

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

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

Full text and comments »

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

38.
By adamant, history, 5 years ago, In English
Theoretical grounds of lambda optimization Hi everyone! This time I'd like to write about what's widely known as "Aliens trick" (as it got popularized after 2016 IOI problem called [Aliens](https://ioinformatics.org/files/ioi2016problem6.pdf)). There are already some articles about it here and there, and I'd like to summarize them, while also adding insights into the connection between this trick and generic Lagrange multipliers and Lagrangian duality which often occurs in e.g. linear programming problems. Familiarity with a [previous blog](https://codeforces.me/blog/entry/98524) about ternary search or, at the very least, definitions and propositions from it is expected. Great thanks to [user:mango_lassi,2022-01-01] and [user:300iq,2022-01-01] for useful discussions and some key insights on this. Note that although explanation here might be quite verbose and hard to comprehend at first, the algorithm itself is stunningly simple. Another point that I'd like to highlight for those already familiar with "Aliens tr...
$\lambda$ (it will be a contiguous sequence of integers) and make the binary search based on the, size of $x$ by the binary search., typical solutions using it require binary search on lambdas to reach specified constraint by minimizing, (n \log^2 n)$ with parallel binary search., ,\lambda_2)$ instead of binary search on $\lambda$ to match it with $|A|=a$ and $|B|=b$. In this way, we, 1. Do the binary search on $\lambda$. Assume that you work in $[\lambda_l, \lambda_r)$ and test, For nested binary search on $\lambda$ components to work, every function $h_{\lambda_1 \dots, Or binary search on $d_{v_i}(k+1, \dots) - d_{v_i}(k, \dots)$, as the optimal value corresponds to, This means that for the example problem strong duality holds and instead of doingbinary search on

Full text and comments »

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

39.
By Vladithur, history, 4 years ago, In English
Codeforces Round #813 (Div. 2) Editorial Thanks for participating in the round, we hope you liked the problems! <spoiler summary="Solve count predictions (official div. 2)"> Handle | A | B | C | D | E1 | E2 | F --- | --- | --- | --- | --- | --- | --- | --- [user:Vladithur,2022-08-13] | 16K | 8K | 3K | 900 | 500 | 50 | 4 [user:_dlbm17,2022-08-13] | 14K | 9K | 5K | 500 | ? | ? | ? [user:thanhchauns2,2022-08-13] | 14K | 8K | 2K | 1K | 500 | ? | ? [user:QuangBuiCP,2022-08-13] | 14K | 7K | 2K | 1K | 500 | 24 | 5 [user:welleyth,2022-08-13] | 16K | 10K | 4K | 1.5K | 600 | 130 | 2 [user:Kon567889,2022-08-13] | 14K | 10K | 5K | 2K | ? | ? | 5 </spoiler> [problem:1712A] <spoiler summary="Hint"> The smallest possible sum is $1 + 2 + \ldots + k$. </spoiler> <spoiler summary="Tutorial"> [tutorial:1712A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const ch...
Binary search on the answer or do a clever greedy.

Full text and comments »

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

40.
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...
Let's run a binary search for the answer. This will work because if, We can use the binary search for the answer. , thrown out. This can be done using the binary search for each segment separately.

Full text and comments »

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

41.
By Errichto, 10 years ago, In English
Good Bye 2016 — hints and codes You can download my codes to all problems [here](http://www.filedropper.com/codes_1). I will write a full editorial in the next few days. Now you can read hints and short solutions. [problem:750B] <spoiler summary="hint"> Create a variable that will denote your current distance from the North Pole. What are allowed values of this variable? When can't we go West or East? </spoiler> [problem:750C] <spoiler summary="hint1"> Let $x$ denote the initial rating (or his final rating, whatever is easier for you to think about). The information that Limak is in some division in the $i$-th contest gives us some inequality for $x$. Can you see it? </spoiler> <spoiler summary="hint2"> For every contest we know that the current rating is $x$ increased by some prefix sum of c_i (changes of rating). If Limak is in the division 1, we have inequality x+prefSum >= 1900 so we have x >= 1900-prefSum. If Limak is in the division 2, we have inequality x_prefSum <= 1899 so it is ...
$O(n)$ code in C++: [submission:24069564] $O(n \cdot \log n)$ code in C++, with binary search, From this, with binary search or just a division, we can compute the largest $x$ where this formula, binary-searched $x$ to $1$.

Full text and comments »

Tutorial of Good Bye 2016
  • Vote: I like it
  • +168
  • Vote: I do not like it

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

Full text and comments »

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

43.
By feecIe6418, 5 years ago, In English
Editorial of Codeforces Global Round 21 Thanks for participation! If your solution to D involves any data structures and is not $O(n)$ -- please read the "solution 1". I believe it is very interesting, but to make the difficulty suitable for D we allowed not $O(n)$ solutions. [problem:1696A] <spoiler summary="Hint 1"> How many operations will we perform? <spoiler summary="Answer"> At most one. Why? </spoiler> </spoiler> <spoiler summary="Solution"> Suppose we can only perform exactly one operation. In this case the answer is $S=\max_{1\le i\le n}(a_i\mathrm{\ or\ }z)$. In fact, we can prove that this is the answer. Define $a_i'$ as the value of $a_i$ after some operations. It suffices to prove the answer will never exceed $S$. Note that $z$ will always become a submask of itself after any number of operations, so $a_i$ will always be a submask of $(a_i\mathrm{\ or\ }z)$ after any number of operations. This leads to the conclusion that $a_i'\le (a_i\mathrm{\ or\ }z)$ for all $i$. Thus $\max_{1\le i...
we know $j\in [i+1,r_i]$. $r_i$ can be pre-computed with a stack, or binary search + some data

Full text and comments »

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

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

Full text and comments »

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

45.
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; ...
(;;){ //binary search for unvisisited neighbor auto it=active.lower_bound(a[node]); if (it

Full text and comments »

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

46.
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 ...
Simply make all $a_i$ equal and binary, Since we now know the order, we can binary, The rest of the solution is binary search on $k$, with the

Full text and comments »

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

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

Full text and comments »

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

48.
By brunomont, history, 5 years ago, In English
[Tutorial] Dynamic Suffix Arrays Hello, Codeforces! In this blog I will describe yet another <s>useless</s> unconventional data structure. This time, I will show how to maintain an extended suffix array (suffix array, inverse of suffix array, and $lcp$ array) while being able to add or remove some character at the <b>beginning</b> of the string in $\mathcal{O}(\log n)$ amortized time. It can be used to <s>overkill</s> solve problem M from [2020-2021 ACM-ICPC Latin American Regionals](https://codeforces.me/gym/103185), which my team couldn't solve during the contest. I learned it from [here](https://oi-wiki.org/string/suffix-bst/) (Chinese), but it is not shown how to maintain the $lcp$ array. Here is the whole code of the data structure. To read this blog, I recommend you ignore this code for now, but use it if you have questions about helper functions, constructors, etc, since I will pass over some implementation details in the explanations. <spoiler summary="Full code"> ~~~~~ struct dyn_sa { struct ...
of the string (and, equivalently, a single node in the binary search tree), and the previous, where the suffix we want to remove is. When found, just remove it using standardbinary search tree, $ comes before suffix $j$ in the $SA$ (equivalently, in the binary search tree). Using this, we can, 2. Binary search tree ------------------, Because we want to maintain the $tag$ array, we will not use a binary search tree that does, Let's represent the $SA$ using a binary search tree, such that the in-order traversal of the tree, On the binary search tree used: [Link1](https://www.lcg.ufrj.br/python/ADs/AD1_2019-2.EN.pdf, We could represent this using the following binary search tree.

Full text and comments »

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

49.
By sum, history, 3 years ago, In English
Editorial for Codeforces Round #919 (Div. 2) ##Information about the round <spoiler summary="Rating predictions (inspired by BucketPotato's editorial)"> | Person | A | B | C | D | E | F1 | F2 | |--------------------------------------------|------|------|------|------|------|------|------| | [user:sum,2024-01-13] | 800 | 1300 | 1500 | 1900 | 2000 | 2200 | 2900 | | [user:oursaco,2024-01-13] | 800 | 1100 | 1300 | 1600 | 1800 | 2100 | 3100 | | [user:omeganot,2024-01-13] | 900 | 1000 | 1400 | 1700 | 1900 | 2200 | 2800 | | [user:sriniv,2024-01-13] | | | | 1900 | 2000 | 1900 | | | [user:apple_method,2024-01-13] | 1000 | 1200 | 1400 | 1900 | 1600 | | | | [user:awesomeguy856,2024-01-13] | 800 | 1100 | 1400 | 1800 | 1900 | 2000 | 2800 | | [user:nonrice,2024-01-13] | 900 | 1000 | 1400 | 1750 | | | | | [user:null_aw...
```cpp #include using, the number of times we crossed the line})$. Naively, we can binary search for our answer and BFS to, Binary search! , For each query, binary search on the answer $k$ — we can only visit cell ($i, j$) if $d_{i,j

Full text and comments »

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

50.
By TLE, history, 8 years ago, In English
Avito Cool Challenge 2018 Editorial [problem:1081A] Idea: [user:yjq_naiive,2018-12-17] Developer: [user:yjq_naiive,2018-12-17] <spoiler summary="Hint"> 1 sounds like the minimum value we can get. Why? Is it always true? </spoiler> <spoiler summary="Solution"> When $n \leq 2$, we can do nothing. When $n \geq 3$, since $1<\frac{n}{n-1}<2$, $n-1$ isn't a divisor of $n$, so we can choose it and get $1$ as the result. </spoiler> <spoiler summary="Code (yjq_naiive)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); if (n == 2) { puts("2"); } else { puts("1"); } return 0; } ~~~~~ </spoiler> [problem:1081B] Idea: [user:yanQval,2018-12-17] Developer: [user:yanQval,2018-12-17] <spoiler summary="Hint"> Consider the number of people wearing hats of the same color. </spoiler> <spoiler summary="Solution"> let $b_i=n-a_i$ represent the number of people wearing the same type of hat of $i$-th person. Notice that the person wear...
Yet another binary search?

Full text and comments »

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

51.
By Nachia, history, 2 years ago, In English
Determine A Non-Increasing Integer Sequence of Length n with a[k]<=n/k in O(sqrt(n)) Steps This is a topic on complexity analysis (for [Round 975 Div. 1 E](https://codeforces.me/contest/2018/problem/E2)) with no special algorithm. ## Problem An integer sequence $(a _ 1,a _ 2,\ldots ,a _ n)$ is hidden. We know: * It is non-increasing. ( $a _ k\geq a _ {k+1}$ ) * $0\leq a _ k\leq n/k$ Suppose we can get one value of $a _ k$ in $O(C)$ time. Find all values of $a _ 1,a _ 2,\ldots ,a _ n$ . ## Algorithm Put $a _ 0=n+1$ and $a _ {n+1}=0$ and call $\text{S} _ \text{EARCH}(1,n)$ . In a call of $\text{S} _ \text{EARCH}(l,r)$ , do nothing if $l\gt r$ . Also no more search is required if $a _ {l-1}=a _ {r+1}$ . Otherwise evaluate $a _ {\lfloor (l+r)/2\rfloor}$ and recursively call $\text{S} _ \text{EARCH}(l,\lfloor (l+r)/2\rfloor -1)$ and $\text{S} _ \text{EARCH}(\lfloor (l+r)/2\rfloor +1,r)$ . ```py A = [0] * (n+2) A[0] = n+1 A[n+1] = 0 def f(k) : # find a_k def search(l, r) : if l > r return if A[l-1] == A[r+1] : for x ...
Since the algorithm is just a binary search, searching space $[0,n+1)$ is splitted in $2^d

Full text and comments »

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

52.
By errorgorn, 6 years ago, In English
Codeforces Global Round 13 Editorial [problem:1491A] ------------------ Setter: [user:syksykCCC,2021-02-28] Prepared by: [user:syksykCCC,2021-02-28] <spoiler summary="Hint 1"> How can we find the largest $k$ such that the $k$-th smallest element of the array is $0$? </spoiler> <spoiler summary="Hint 2"> How can we maintain $k$? </spoiler> <spoiler summary="Solution"> Let's define $cnt$ to represent the number of 1s in the array. For the modifications, if $a_i$ is already $1$ now, then we let $cnt \gets cnt - 1$. Otherwise, let $cnt \gets cnt + 1$. For the querys, just compare $cnt$ with $k$. If $cnt \ge k$, the answer will be $1$. Otherwise, the answer will be $0$. The complexity : $O(n + q)$. </spoiler> <spoiler summary="Code (C++)"> ```c++ #include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n, q, a[N], cnt; int main() { scanf("%d%d",&n,&q); for(int i = 1; i <= n; ++i) { scanf("%d",a+i); cnt += a[i]; } while(q--) { int opt, x; ...
$0.5n$ and binary search is a very fast log. Hence, it passes quite comfortably (author's solution is, vector across the belt of NONREDs, and then for each RED, binary search the earliest position where, However, you have known that there is only $1$ magnetic magnet in the left, so you can do abinary

Full text and comments »

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

53.
By galen_colin, 3 years ago, In English
THE OPTIMAL PRACTICE STRATEGY (**NOT CLICKBAIT**) Spoiler: it's clickbait. Sorry. Titles like those are fun. ...but, it's the same style of clickbait as my [roadmap](https://www.youtube.com/watch?v=bSdp2WeyuJY) [spoiler 2: if you haven't seen that, it markets itself as a standard roadmap (y'know, soulless and devoid of purpose), but then a few minutes in, says "ok but roadmaps are stupid and here's the advice that you really need" and completely changes the direction of the video]. That's my style of clickbait, and that's the vibe this blog goes for. [cut] <br><br> So... hear me out, please. The start ------------------ First, a couple meta-notes. I will likely exaggerate my tone a bit here for dramatic effect. Don't take it personally, please. Also, **this applies to almost all ratings**. At the very least, I recommend you process the main point of this blog and see whether or not you already do something similar (for most people... probably not?) The problem ------------------ I'm sure if you've looked at the...
If you consistently fail binary search problems... isn't that a sign that you should spend more

Full text and comments »

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

54.
By Errichto, 8 years ago, In English
ROI 2018 in GYM Hi. On Wednesday at [9:05 CET / 8:05 UCT](https://www.timeanddate.com/worldclock/fixedtime.html?day=27&month=3&year=2019&hour=11&min=5&sec=0&p1=166) you can participate in the GYM version of the finals of 2017-2018 Russian Olympiad in Informatics (ROI), Day 1. And on Thursday there will be day 2, same time. Links to GYM contets: [day1](https://codeforces.me/gym/102147) and [day2](https://codeforces.me/gym/102154). 5 hours, 4 problems, IOI-style scoring with subtasks. Statements will be available in three languages: English, Russian, Polish. We wanted to use those problems in a camp in Warsaw so we had to import the problems to some system anyway. Then why not Polygon+Codeforces and thus allowing everybody to participate? Huge thanks to [user:MikeMirzayanov,2019-03-25] for helping me with using GYM. And credits to problem authors: [user:Andreikkaa,2019-05-21] for Radium, [user:Endagorion,2019-05-21] for Viruses, [user:pashka,2019-05-21] for Innophone, Георгий Корнее...
if you store a pointer to optimal element in each bucket instead of binary searching (a pointer can

Full text and comments »

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

55.
By TheScrasse, 3 years ago, In English
Editorial of Codeforces Round 889 (Div. 1 + Div. 2) The official implementations of all the problems are [here](https://drive.google.com/file/d/1stkidhN_ftTOzK4qcMYxkUAlwWWb3AqF/view?usp=sharing). [problem:1855A] Author: [user:Kaey,2023-07-23]<br> Preparation: [user:akifpatel,2023-07-23] <spoiler summary="Hint 1"> What's the most efficient way to make the sad students happy? </spoiler> <spoiler summary="Hint 2"> In most cases, you can make $2$ sad students happy in $1$ move. </spoiler> <spoiler summary="Solution"> Let $s$ be the number of sad students at the beginning. The answer is $\lceil \frac{s}{2} \rceil$. In one move, you can make at most $2$ sad students happy (because you can change the position of at most two students), so you need at least $\lceil \frac{s}{2} \rceil$ moves. In fact, you can make everyone happy in exactly $\lceil \frac{s}{2} \rceil$ moves: - while there are at least $2$ sad students, you can swap them and both of them will be happy; - if there is exactly $1$ sad student left, you ...
- First, find $k$ nodes in the cycle, doing a binary search on the successor of the last node found, You can get a node in the cycle in $9$ queries, doing a binary search on the $n$-th successor of

Full text and comments »

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

56.
By Urbanowicz, 7 years ago, In English
Binary Lifting, No Memory Wasted Hello everyone! This time I’d like to tell you about a data structure from 1983 which, I believe, deserves to be widely known in CP community. This structure solves the problem of quickly finding ancestors in a rooted tree. Like usual binary lifting, it does so in $O(\log n)$. But unlike with usual binary lifting, you can add and remove leaves in $O(1)$, which means that the total space requirement is just $O(n)$. Each node in the tree requires the following fields: ~~~~~ class Node { int depth; Node parent; Node jump; } ~~~~~ Here `depth` is the number of times you need to `.parent` the node in order to reach the root. Field `jump` points to some ancestor of the node. Below is the definition of the root node. Its jump pointer is undefined, but it turns out convenient if it points to the root itself. ~~~~~ root.parent = null; root.depth = 0; root.jump = root; ~~~~~ Here’s how you find an ancestor that has specified (smaller) depth: ~~~~~ Node fi...
Binary Lifting, No Memory Wasted, same depth throughout the process. Then we can find LCA using the approach of binary search. We, Binary search on the ancestry path ==================================, You might be tempted to implement standard binary search and use `find` as its subroutine. This

Full text and comments »

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

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

Full text and comments »

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

58.
By rembocoder, history, 5 years ago, In English
Integer Binary Search – proper implementation It seems, there are so many materials on binary search already that everyone must know how to code it, however every material seems to tell its own approach, and I see people being lost and still making bugs on such a simple thing. That's why I want to tell you about an approach which I find the most elegant. Of all the variety of articles, I saw my approach only in this [comment](https://codeforces.me/blog/entry/9901?#comment-153756) (but less generalized). UPD: Also in the [user:nor,2022-05-29]'s [blog](https://codeforces.me/blog/entry/96699). ### The problem Suppose you want to find the last element less than `x` in a sorted array and just store a segment of candidates for the answer `[l, r]`. If you write: ~~~~~ int l = 0, r = n - 1; // the segment of candidates while (l < r) { // there are more than 1 candidate int mid = (l + r) / 2; if (a[mid] < x) { l = mid; } else { r = mid - 1; } } cout << l; ~~~~~ ...you will run int...
Integer Binary Search – proper implementation, can use binary search. As we need _the last number for which this is true_, we will use a normal half, It seems, there are so many materials on binary search already that everyone must know how to code, The binary search will only do checks for some numbers strictly between initial `l` and `r`. It

Full text and comments »

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

59.
By cry, 2 years ago, In English
Codeforces Round 965 (Div. 2) Editorial #### [problem:1998A] Problem Credits: [user:sum,2024-07-03] <br> Analysis: [user:cry,2024-07-03] <spoiler summary="Solution "> We can construct a solution by fixing all $x_i$ as $x_c$ or all $y_i$ as $y_c$. For example, if we fix all $y_i$ as $y_c$, then we can output pairs $(x_c-1, y_c), (x_c+1, y_c), (x_c-2, y_c), (x_c+2, y_c), ... , (x_c- \lfloor \frac{k}{2} \rfloor, y_c), (x_c + \lfloor \frac{k}{2} \rfloor, y_c)$. If the $k$ is odd, we need one more pair, so just output $(x_c, y_c)$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <iostream> using namespace std; int main() { int t; cin >> t; while(t--){ int x, y, k; cin >> x >> y >> k; for(int i = 0; i < k - k % 2; i++){ cout << x - (i & 1 ? 1 : -1) * (i / 2 + 1) << " " << y << "\n"; } if(k & 1){ cout << x << " " << y << "\n"; } } } ``` </spoiler> #### [problem:1998B] Problem Credits: [user:satyam343,2024-08-07] <br> Analysis: [user:cry,2024-07-03] <spoiler summ...
Apply binary search , Let's binary search! Suppose we want to check if we can get $med(c_n) \ge x$ or not., } - a_r$. We can binary search to find the range of available $l$ that satisfy this. Specifically, let

Full text and comments »

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

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

Full text and comments »

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

61.
By prvocislo, 3 years ago, In English
Editorial for Codeforces Round #945 (Div. 2) We hope you enjoyed the problems! Thank you for your participation! We are really sorry that A and D turned out to be harder than usual. [Problem A](https://codeforces.me/contest/1973/problem/A): idea by [user:prvocislo,2024-05-17] and [user:satyam343,2024-05-17], prepared by [user:prvocislo,2024-05-17] <spoiler summary="Hint 1:"> If someone would claim that the number of draws that happened between the three players are $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$, can you check in $O(1)$ whether this can be true? </spoiler> <spoiler summary="Hint 2:"> The constraints are very small. The number of draws between any two players is at most $30$. </spoiler> <spoiler summary="Hint 3:"> Hint 3: Try all the possibilities for $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$ and find the one with the biggest sum out of all possibilities that could've been the result of game that ended with scores $p_1$, $p_2$ and $p_3$. </spoiler> <spoiler summary="Solution:"> After each round, sum of...
sort them and use binary search to answer the queries., Once you have a checking function that runs in $O (n \log A)$, you can binary search the answer in, binary search the answer :)

Full text and comments »

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

62.
By Vladithur, history, 3 years ago, In English
Codeforces Round #890 (Div. 2) Editorial Hope you liked the problems! [problem:1856A] <spoiler summary="Hints"> <spoiler summary="Hint 1"> How many operations are needed to make $a_i \le a_{i + 1}$ if initially, $a_i > a_{i + 1}$? </spoiler> </spoiler> <spoiler summary="Tutorial"> [tutorial:1856A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() #define gsize(x) (int)((x).size()) const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; int ans = 0; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) { ans = max(ans, a[i]); } } cout << ans << nl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); ...
Binary search on the answer.

Full text and comments »

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

63.
By MikeMirzayanov, 10 years ago, translation, In English
Interactive Problems: Guide for Participants Sometimes you can meet _interactive problems_ on programming contests (including Codeforces). In problems of this type, the input data given to your program may be not predetermined but is built specifically for your solution. Jury writes a special program &mdash; _interactor_, such that its output is tranferred to the input of your solution, and the output of your program is sent to interactor’s input. In the other words, your solution and the interactor exchange the data and my decide what to print based on the "history of communication". When you write the solution for the interactive problem it is important to keep in mind that if you output some data it is possible that this data is first placed to some internal buffer and may be not directly transferred to the interactor. In order to avoid such situation you have to use special `flush` operation _each time_ you output some data. [cut] There are these `flush` operations in standard libraries of almost all languages. Fo...
Of course, this problem can be solved using binary search. Here is an example of the C++ solution:

Full text and comments »

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

64.
By Misuki, 2 years ago, In English
Editorial of Codeforces Round 967 (Div. 2) Except hints/solutions, I try to add a "general idea" section discuss about some general strategy and standard ideas used to solve the problem, hope you would like it :) [problem:2001A] idea & solution: [user:Misuki,2024-08-20] <spoiler summary="Hint 1"> What's the most obvious lower bound of the answer? </spoiler> <spoiler summary="Hint 2"> Is the lower bound achievable? </spoiler> <spoiler summary="General idea"> One standard way to solve optimization problem is to make observation on lower(upper) bound of the answer and prove such bound is achievable, it's useful in lot of problems. </spoiler> <spoiler summary="Solution"> Let $x$ be one of the most frequent elements in $a$, then the answer must be at least $(n - \text{frequency of } x)$, and this lower bound is always achievable by keep erasing a non-$x$ element from $a$, and we can prove it's always possible to do so. proof: If all elements of $a$ are $x$, we are done. Otherwise, let $y$ denote ...
Use binary search.

Full text and comments »

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

65.
By oolimry, history, 6 years ago, In English
Codeforces Raif Round 1 Editorial [problem:1428A] ------------------ Setter: [user:bensonlzl,2020-10-17] Prepared by: [user:errorgorn,2020-10-17] <spoiler summary="Hint 1"> Consider when $x_1=x_2$ </spoiler> <spoiler summary="Hint 2"> Consider when $x_1 \ne x_2$ </spoiler> <spoiler summary="Solution"> We consider 2 cases. The first is that the starting and ending point lie on an axis-aligned line. In this case, we simply pull the box in 1 direction, and the time needed is the distance between the 2 points as we need 1 second to decrease the distance by 1. The second is that they do not lie on any axis-aligned line. Wabbit can pull the box horizontally (left or right depends on the relative values of $x_1$ and $x_2$) for $|x_1-x_2|$ seconds, take 2 seconds to move either above or below the box, then take another $|y_1-y_2|$ seconds to move the box to $(x_2,y_2)$. </spoiler> <spoiler summary="Code (C++)"> ```c++ #include <bits/stdc++.h> using namespace std; int main(){ ios_base::...
Binary Search. , The way we perform the binary search is quite important here. Performing it in a naive manner (e.g, while (T.size() > 1){ // while the number of candidate arcs is > 1, we binary search on the

Full text and comments »

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

66.
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> [...
Binary search the answer.

Full text and comments »

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

67.
By Vladithur, history, 2 years ago, In English
EPIC Institute of Technology Round Summer 2024 (Div. 1 + Div. 2) Editorial Hope you liked the problems! We apologize for the (very?) weak tests in H. Editorials for problems will be added over time (and hints), for now, please take a look at the available hints and model solutions. <spoiler summary="Easter eggs"> <spoiler summary="A"> ForceCodes is a reference CrossCode, you should try it. </spoiler> <spoiler summary="C"> Basil is one of the characters in OMORI, you should also try it. </spoiler> <spoiler summary="D"> "World is Mine" is one of Hatsune Miku's most well known songs, and a fan-made MV has a lot of cakes in it) I originally wanted to make the characters names Miku and Sweetheart(from OMORI), but decided to stick to Alice and Bob to keep the statement clean. </spoiler> <spoiler summary="E"> The epigraph is a reference to KonoSuba. </spoiler> <spoiler summary="H"> The epigraph is a quote from Celeste (you should try it), and the title is a reference to one of it's locations, Mirror Temple, but only now there are fumo...
"Binary search" base case for small $m$. , // Bruteforce base case (uses binary search) if (n <= 25) { // can be n <= 22 or above

Full text and comments »

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

68.
By MladenP, history, 5 years ago, In English
Best of COCI #1 Since a new season of COCI (Croatian Open Competition in Informatics) started [last saturday](https://codeforces.me/blog/entry/96022), here is the first in a series of COCI appreciation posts (I will post one after each COCI round, so six in total!). For my coaching, I went through all COCI contests since 2006 to gather tasks and selected some of my favorite ones. ### Notes - I skipped a lot of the really hard tasks because they weren't useful for my students. I kept a list of these tasks, if someone wants it, they can PM me. Also, I only considered COCI, not COI. This current season is not being considered. - There are many great tasks outside of the 48 shown (throughout the series), so it's worth it to go through other tasks as well. I have selected just my favorite ones. - These tasks are maybe not always the most innovative, I have selected the tasks that are most useful for coaching and learning new ideas, so for people who already know the idea, the difficulty might be mu...
persistent segment tree or parallel binary search , binary search. Simple statement.

Full text and comments »

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

69.
By Errichto, 3 years ago, In English
Group tutoring Hi. I offer classes for groups of 2-3 students. I teach competitive programming with a focus on problem-solving. There won't be many lectures because I can send you an article/video link instead. The lesson cycle is usually: I choose a problem, you say your thoughts and ideas, I comment on incorrect ideas, and we talk about the valid solution(s), possibly with drawings and pseudocode. In beginner groups, I might ask you to implement something, C++ or Python preferred. There's a lot of homework and you're expected to practice a few hours per week. We might spend half a lesson talking about 1-2 homework problems from last week. This is intended. We use Google Meet, shared whiteboard, and a collaborative editor Codebunk. After a lesson, you get a video recording and a codebunk with code/text history like this one https://codebunk.com/pb/3501100331621/. This allows you to copy links and code easily. There's a Discord group chat to ask questions between classes. - 1.5h les...
I can cover standard algorithms (binary search, recursion and backtracking, hashing, graphs, DFS

Full text and comments »

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

70.
By LinkinPony, history, 5 years ago, In English
The most disgusting contest I participated in: The 2021 ICPC Asia Regionals Online Contest (I) Just a few hours ago, The 2021 ICPC Asia Regionals Online Contest (I) was held on https://pintia.cn/. This contest(and the next on 26th) will determine the WHOLE Asia-East Division‘s quota. And how fantastic(according to some coaches) of these problems in this online contest? I upload the statement on GDrive and you can preread it here: [aec-online-i-2021.pdf](https://drive.google.com/file/d/1g5AfTLL8-9JtxbpKGv9VtO-h2_kAWqUs/view?usp=sharing) I should clarify something here: This contest doesn't have a clarification function, and some problems are from Huawei. Guess which they are! <spoiler summary="Some fantastic part of problems"> Health tips: If you just participated in this contest and your blood pressure is high, please don't continue reading. <spoiler summary="A"> What is exactly the finish time of one request? `arrival_time + processing_time` or `arrival_time + processing_time + 1`? As there is no clarification, you can only enumerate it. Enumerate question meaning ma...
This is an interactive problem. You should use `assert` and binary search to

Full text and comments »

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

71.
By TheScrasse, history, 4 years ago, In English
Competitive Programming Roadmap (target: [gray, blue]) tl;dr ------------------ - Competitive programming roadmap [here](https://drive.google.com/file/d/16Jydn250Ue7K7hOfzLxw4p5jFF4ZCqWT/view?usp=sharing). - It should be suitable both for newcomers and for people with some experience with CP: let's say, up to blue on Codeforces. - It contains ~ 100 "must-know" problems about various topics: ad-hoc, STL, binary search, DP, number theory, graphs. - There are solution sketches at the bottom, don't feel guilty reading them if stuck. Why? ------------------ Many people new to Codeforces seek advice about how to get better / which problems to try. Other people are stuck on gray / green even after solving a lot of problems. This roadmap aims to be a solution. My take: to be good at competitive programming, you have to know "what to think" and "how to think" when you try a problem. - "What to think": you have to know a decent amount of standard problems / techniques. Sometimes, a problem requires steps / observations that seem ob...
various topics: ad-hoc, STL, binary search, DP, number theory, graphs. - There are solution

Full text and comments »

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

72.
By PrinceOfPersia, 12 years ago, In English
Codeforces Round #299 Editorial ### [problem:535A] First of all check if $n$ is one of the values $0, 10, 11, …, 19$. Then, let’s have array $x[]$ = {"", "", "twenty", "thirty", …, "ninety"} and $y[]$ = {"", "one", …, "nine"}. ![ ](http://espresso.codeforces.com/d5f38500e79e3e89be0519dc22736124c000bada.png) Let $a = \frac{n}{10}$ and $b = n\ modulo\ 10$. If $n$ is not one of the values above, then if $a=0$, print $y[b]$, else if $b=0$ print $x[a]$ otherwise print $x[a]$-$y[b]$. Time complexity: $O(1)$ [Code](http://ideone.com/mytb2L) by [user:SoroushE,2015-04-02] [Another Code](http://ideone.com/CqgNe5) by [user:PrinceOfPersia,2015-04-05] [Another Code](http://ideone.com/dqiMNL) by [user:Haghani,2015-04-08] [Python Code](http://ideone.com/6tZmNF) by [user:Zlobober,2015-04-04] ### [problem:535B] Sol1: Consider $n$ has $x$ digits, $f(i) = $ decimal representation of binary string $i$, $m$ is a binary string of size $x$ and its $i-th$ digit is 0 if and only if the $i-th$ digit of $...
For this problem, use binary search on $r$ and use the fact that the sequence is non-decreasing and

Full text and comments »

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

73.
By employed, history, 2 months ago, In English
Editorial of DeepInfra Round 1 (Codeforces Round 1126, Div. 1 + Div. 2) thanks to [user:nifeshe,2026-10-10] for making my life easier with templates [problem:2271A] <spoiler summary = "Hints"> <spoiler summary = "Hint 1"> After performing $z$ operations, the robot's $x$-coordinate is exactly $z$. </spoiler> <spoiler summary = "Hint 2"> After completing any operation, the $x$-coordinate and $y$-coordinate always have the same parity. </spoiler> <spoiler summary = "Hint 3"> Try to find a construction to reach any point $(x,y)$ where $y\le x$ and $x$ and $y$ have the same parity. </spoiler> </spoiler> <spoiler summary = "Solution"> Notice that after performing $z$ operations, the robot's $x$-coordinate will be exactly $z$, while its $y$-coordinate cannot exceed $z$. We will first consider the case $b\le a$, then handle the special case $b=a+1$. Notice that the robot can reach any point $(x,y)$ where $0\le y\le x$ and $x$ and $y$ have the same parity in exactly $x$ operations. To do so, we can first move up until reaching $y$...
After finding a position $pos$ with maximum $f(pos)$, try using binary, simply output $pos$. - Otherwise, $kbinary search., **Note that $f(s)$ does not need to be monotonic for this binary search to work!** We only need the, Binary search on the number of splits. When processing backward, Finally, if $c$ is the minimum number of splits found by binary search, the answer is, Now, let's binary search on the number of splits $c$., We can find such a position using binary search!

Full text and comments »

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

74.
By neal, 8 years ago, In English
Unofficial Editorial for Round 532 (Div. 2) Just finished this contest in virtual mode and noticed the editorial is missing, so I thought I would share my approaches. #### [problem:1100A] Loop over all values of $b$ and take the sum of all indices that are not equivalent to $b \bmod k$. Remember to take the absolute value at the end. Runtime is $\mathcal{O}(n^2)$. Code: [submission:48374675] #### [problem:1100B] Maintain a frequency array of size $n$ and track the number of distinct values seen so far as we loop through the array. Once the number of distinct values reaches $n$, we hold a round and decrement each index of the frequency array. Note that this takes $n$ time, but this is fine since we can only hold at most $\displaystyle \frac{m}{n}$ rounds. Runtime is $\mathcal{O}(m)$. Code: [submission:48374608]. Note that `x++` means use the value of `x` and then increment, whereas `++x` means increment and then use. Similar for `x--` and `--x`. #### [problem:1100C] Draw the line segments between the center of the inn...
When we want optimize the maximum of a set of things, it's a good idea to binary search. Let's say

Full text and comments »

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

75.
By AlexLuchianov, 5 years ago, In English
[Tutorial] Binary lifting ### The classic Problem The most common application of binary lifting is the following: "Let $G$ be a rooted tree with $N$ nodes. For $Q$ queries of the form $(K, V)$ we want to find the $K$-th ancestor of $V$ in the tree." One simple, yet quite inefficient way of solving this problem is to build for every node an edge towards its direct ancestor. Then, in order to solve a query we simply have to traverse $K$ edges. This approach has complexity $O(NQ)$. We can try improving it by adding some "jump-edges". ![Fig 1](https://i.imgur.com/ualhJEj.png) A jump-edge is simply an edge that starts from a node and is not directed towards its parent, but towards an arbitrary ancestor. These jump-edges will allow us to traverse large regions of edges in a single operation. Let's start by building jump-edges from *each* node towards its $2$-nd ancestor, $4$-th ancestor, $8$-th ancestor and so on. Note that in the above figure only a *subset* of these jump-edges is visible since otherwis...
[Tutorial] Binary lifting, order. For example, let's search for the $7$-th ancestor of $9$. Since $7$ = $4$ + $2$ + $1$, we can, ### The classic Problem The most common application of binary lifting is the following: "Let $G

Full text and comments »

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

76.
By Errichto, 5 years ago, In English
[GYM] 100 Easy Problems (Bootcamp) Target audience: newbies and pupils (rating up to 1400). Group link: https://codeforces.me/group/yg7WhsFsAp/contests (hit "join" on the right). Hi. Enjoy a series of 8 problem lists for beginners. The example topics are strings, arrays, math, and binary search. You are allowed to discuss anything with others, or just look up solutions online. There are also 3 exams, each recommended for a 2-hour individual virtual participation. Use the displayed order, e.g. take exam 1 after day 3. It all should take you 2 weeks of intense bootcamp-like work (or a few months if you take your time). The problems were originally used two years ago in a Saudi Arabia camp. It's a mix of around 70 existing CF problems and 30 new original problems, mainly prepared by [user:kostka,2021-11-18], with some help from me and [user:mustafabar,2021-11-18]. I asked them for permission to publish everything. I will put hints to some problems in this blog (or in the group? not sure). Expect a few v...
, and binary search. You are allowed to discuss anything with others, or just look up solutions

Full text and comments »

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

77.
By jeroenodb, 4 years ago, In English
Twelve cool problems about binary search If you're looking for some binary search practice, this blog might be for you. I have compiled a list (I've heard lists are very popular on CodeForces) of some problems I really liked. The only criteria I used is that the solution for the problem has to be vaguely related to binary search. And I also tried to have some variety in the problems I chose, so they are not all the same type of application of binary search. Here are 12 problems, in a roughly increasing order of difficulty, that are vaguely (or less vaguely) related to binary search: 1. [problem:1672E] 1. [Median of two sorted arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/description/) Although the time limit doesn't enforce it, try to make a $O(log(n+m))$ solution. 1. [IOI 2013 Cave](https://oj.uz/problem/view/IOI13_cave) or if you prefer the Codeforces archive: [IOI 2013 Cave](https://codeforces.me/group/32KGsXgiKA/contest/103763/problem/D) 1. [IOI 2020 routers](https://oj.uz/problem/view/IOI20_...
Twelve cool problems about binary search, vaguely) related to binary search:, If you're looking for some binary search practice, this blog might be for you. I have compiled a, It turns out the coolest uses (or variations) of binary search I know appeared in interactive

Full text and comments »

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

78.
By lrvideckis, history, 2 years ago, In English
[tutorial] string matching: binary search over suffix array in O(log(|s|)+|p|) Recently I was learning about how to binary search over suffix array to solve string matching (specifically, single text, multiple patterns, solve it online). Here ([1](https://codeforces.me/blog/entry/111380) ("Pattern Query" section), [2](https://codeforces.me/edu/course/2/lesson/2/3), [3](https://cp-algorithms.com/string/suffix-array.html#finding-a-substring-in-a-string)) describes how to solve it in `O(|s| * log(|p|))` but I'll describe how to improve this to `O(|s| + log(|p|))`. There already exists [resources](https://stackoverflow.com/a/11374737) online about this, but I will try to simplify it. ### visualizing suffix array Let's take the text s="banana", and consider all suffixes (written vertically): ~~~~~ a n a a n a n a n a a n a n a b a n a n a 0 1 2 3 4 5 ~~~~~ now let's sort it: ~~~~~ a a n n a a a a n n n n a a a a a a b n n 5 3 1 0 4 2 ~~~~~ s's suffix array is `[5, 3, 1, 0, 4, 2]`. Now take any substring of s...
[tutorial] string matching: binary search over suffix array in O(log(|s|)+|p|), ### visualizing the binary search, So back to our binary search, we have l,r,m=(l+r)/2., so we can start the binary search as usual with l=0,r=size(s),m=(l+r)/2, and compare p to s

Full text and comments »

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

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

Full text and comments »

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

80.
By Error_Yuan, history, 2 years ago, In English
Refact.ai Match 1 (Codeforces Round 985) Editorial Thank you all for participating in the round! We apologize for the wrong checker in problem E at the beginning of the contest, as well as the weak tests in problem B. To be honest, all the hacked submissions have similar logic and codes in B, which made me suspicious. Anyway, we are sorry for the inconvenience! >_< <spoiler summary="Rating Predictions"> | |A|B|C|D|E|F|G|H|I| |:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:| |[user:Error_Yuan,2024-11-7]|800|1200|**1600**|**2100**|**2300**|2600|**3000**|3400|**3500**| |[user:sszcdjr,2024-11-7]|800|1100|1600|2000|2300|**2600**|2900|**3300**|3500| |[user:wyrqwq,2024-11-7]|800|**1000**|1400|2200|**2300**|2600|**3000**|3500|3500| |[user:Otomachi_Una,2024-11-7]|**800**|1000|1600|2200|2400|2600|3200|3500|3500| |[user:dxqwq,2024-11-7]|900|1100|1700|2200|2400|2600|3200|3500|3500| |[user:Kubic,2024-11-7]|800|1000|1600|2400|2200|2800|3000|3500|3300| |[user:wsc2008qwq,2024-11-7]|800|1100|1600|1900|2200|2700|3100| | | |[user:chroma...
First, do binary search on the answer. Suppose we're checking whether, Binary search.

Full text and comments »

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

81.
By Proof_by_QED, history, 17 months ago, In English
EPIC Institute of Technology Round Summer 2025 (Codeforces Round 1036, Div. 1 + Div. 2) Editorial Thanks for participation! We hope you loved the contest. #### [problem:2124A] Problem Credits: [user:Lilypad,2025-07-01] <br> <spoiler summary="Hint"> When is there definitely *not* a solution? </spoiler> <spoiler summary="Solution"> First, note that since relative order is preserved no matter which elements are deleted, if $a$ is originally sorted in nondecreasing order, the array cannot be a derangement no matter which elements are deleted. If $a$ is not sorted, we can note that any two elements that form an inversion pair satisfies the requirements. The total runtime is $O(n)$. </spoiler> <spoiler summary="Code"> ``` #include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int> arr(n); for(auto &x : arr) cin >> x; for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(arr[i] > arr[j]){ cout << "YES\n2\n"; cout << arr[i] << " " << a...
binary search). We can now decompose $score(a)$ into the sum of the following four parts:

Full text and comments »

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

82.
By rui_er, 3 years ago, In English
Codeforces Round 942 (Div. 1, Div. 2) Editorial [problem:1972A] <spoiler summary="Hint 1"> Only add problems when they are needed. </spoiler> <spoiler summary="Tutorial"> [tutorial:1972A] </spoiler> <spoiler summary="Solution"> ```cpp //By: OIer rui_er #include <bits/stdc++.h> #define rep(x, y, z) for(int x = (y); x <= (z); ++x) #define per(x, y, z) for(int x = (y); x >= (z); --x) #define endl '\n' using namespace std; typedef long long ll; const int N = 105; int T, n, a[N], b[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); for(cin >> T; T; --T) { cin >> n; rep(i, 1, n) cin >> a[i]; rep(i, 1, n) cin >> b[i]; int diff = 0, ans = 0; rep(i, 1, n) { if(a[i - diff] > b[i]) { ++ans; ++diff; } } cout << ans << endl; } return 0; } ``` </spoiler> [problem:1972B] <spoiler summary="Hint 1"> Is there anything that _never...
Binary search on the answer of magics.

Full text and comments »

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

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

Full text and comments »

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

84.
By VladiG, 2 years ago, In English
Cool way to binary search: Fenwick search So yesterday I sent a code of this search in a group chat as a joke but surprisingly everyone praised it and [user:iframe_,2024-08-14] dubbed it as "Fenwick search" and now I am <s>farming contribution</s> making a blog about it. Fenwick Search ================== Lets say you want to search on the interval $[1, n)$ and lets say you want to find the minimal position that satisfy a certain property. Also let the minimal position that satisfies said property be $ans$ So, in regular binary search you keep a left bound and a right bound and you change them accordingly, but in Fenwick search you only keep track of the middle bound. Firstly initialize the middle bound as the highest power of 2 that is less than n. The gist of Fenwick search is transforming the middle bound into $ans$, we do that by manipulating the bits in the middle bound. Specifically for every set bit in $ans$ we set the bit after the last set bit in the middle bound and we shift it left until it matches the des...
Cool way to binary search: Fenwick search, So yesterday I sent a code of this search in a group chat as a joke but surprisingly everyone, So, in regular binary search you keep a left bound and a right bound and you change them

Full text and comments »

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

85.
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...
Binary searching takes $O(\log{N})$ time, so this is the complexity of the whole algorithm.

Full text and comments »

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

86.
By Black_Fate, history, 4 years ago, In English
[Educational] Binary Search Study Notes (1) **Hello Codeforces!** Binary search is useful in many situations. For example, interactive problems or minimizing the maximum problems. Binary search is a good choice when dealing with many situations, and for many binary search problems, monotonousness may be hard to find out and participants may not be able to focus on binary search. You may think that binary search is simple, but after this blog, you may think more about how binary search is working on competitive programming. ### **Part A** &mdash; What is binary search? Consider the following problem: you are going to guess a number between $0$ and $100$, and I'll tell you that the number you give is smaller than the number I thought about or not. How to minimize the number of your guessing? Well, you may guess $50$ first, if $50$ is too large, guess $25$, otherwise $75$, and so on. For each guess, you cut off half the possible numbers, since $x$ is small, the numbers smaller than $x$ are also small. If $x$ is large...
[Educational] Binary Search Study Notes (1), that the monotonousness of the problem is very clear. Due to this, let's do binary search:, the monotonousness. And then we can do binary search on the maxinum, and if the mininum needed, ### **Part A** — What is binary search?, ### **Part C** — Basic binary search situations, Binary search is useful in many situations. For example, interactive problems or minimizing the, This blog talked about basic binary search algorithm and also, we are going to talk about ternary, This is the motivation for doing binary search. Only if **monotonousness** is known,binary search, To maximize the mininum, we can consider binary search. To implement the checker, consider to do, To minimize the maxinum, we can consider binary search. And also we can do a greedy to implement, To minimize the maxinum, we can consider binary search. To implement the checker, consider to do it, Why are you using binary search when seeing the problem? Let's consider the following monotonous, You may think that binary search is simple, but after this blog, you may think more about how

Full text and comments »

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

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

Full text and comments »

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

88.
By Lyde, history, 3 years ago, In English
random quotes Oh hi! Welcome to 24 random quotes! I'm a competitive programmer, but I'm also pretty much a fan and often visit here to see some recent actions. I have a pretty unusual hobby: Collecting some sentences from blogs and comments and saving them as pictures, which I could use later for memes. Later I realized that I couldn't use it that much and after 4 years, it became a collection of well, memories. So I had the idea of sharing some of it with you guys for nostalgia! Most of them are light-hearted, and all of them are pretty memorable in my mind. If you are an experienced member here you might realize some of them, so I will make it a challenge: Guess where this is from! (No prizes sadly) The spoiler to the link of the comment/blog and my personal opinion (or s/p) will be right below the quote. Anyways, enjoy. > If newcomers find it confusing, then that's their bugaboo <spoiler summary="s/p"> [Link](https://codeforces.me/blog/entry/91480#comment-800196) Still rem...
> instead of doing 1 linear search you doing 2. Thats why its called binary search. Works 2 times

Full text and comments »

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

89.
By eugenechka.boyko.2_0-0, 19 months ago, translation, In English
Codeforces Round 1022 Editorial #### [problem:2108A] Author: [user: eugenechka.boyko.2_0-0,2025-04-30] <spoiler summary="Solution"> Let’s start with $p = [1, 2, 3, …, n]$. For this $p$, $f(p) = 0$. Let’s move $n$ to the beginning one position at a time. It’s easy to see that we increase the answer by $2$ at each step. Now, let’s move $n - 1$ to position $2$, then $n - 2$ to position $3$, and so on, until we reach $p = [n, n - 1, …, 2, 1]$. For this $p$, $f(p) = \lfloor \frac{n^2}{2} \rfloor$. While doing this, we obtained every even value from $0$ to $\lfloor \frac{n^2}{2} \rfloor$, since we were adding $+2$ at each step. Let’s prove that we can’t get any other values. First of all, it’s easy to see that we can’t obtain a value less than $0$ or greater than $\lfloor \frac{n^2}{2} \rfloor$. Second, we can only obtain even values, because each swap changes the answer by an even number. So the answer is $\lfloor \frac{n^2}{4} \rfloor + 1$ Time complexity : $\text{O}(1)$. </s...
apply **binary search on the answer**., Among them, we find boundary elements via **binary search** for $\log\frac{n}{k}$ queries:, In total, there are $\text{O}(\log n)$ iterations in the binary search over the answer and $\text{O, Using binary search, we find the boundary elements for $\log k$ queries:

Full text and comments »

90.
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...
solved using parallel binary search.

Full text and comments »

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

91.
By PrinceOfPersia, history, 11 years ago, In English
Codeforces Round #326 (Editorial) ### Div.2 A (Author: [user:Haghani,2015-10-01]) Idea is a simple greedy, buy needed meat for $i-th$ day when it's cheapest among days $1, 2, ..., n$. So, the pseudo code below will work: ~~~~~ ans = 0 price = infinity for i = 1 to n price = min(price, p[i]) ans += price * a[i] ~~~~~ ![ ](http://codeforces.me/predownloaded/64/4c/644c9930cf472ff1bdb48eb3a5f481cce5bbc04b.png) Time complexity: $\mathcal O(n)$ [C++ Code](http://ideone.com/fa7rF5) by [user:amd,2016-03-05] [Python Code](http://ideone.com/Sh0hPp) by [user:Haghani,2015-10-15] [Python Code](http://ideone.com/5J6Rew) by [user:Zlobober,2015-10-15] ### Div.2 B (Author: [user:amd,2016-03-05]) Find all prime divisors of $n$. Assume they are $p_1, p_2, ..., p_k$ (in $\mathcal O(\sqrt n)$). If answer is $a$, then we know that for each $1 \leq i \leq k$, obviously $a$ is not divisible by $p_i^2$ (and all greater powers of $p_i$). So $a \leq p_1 \times p_2 \times ... \times p_k$. And we...
Run binary search on the answer ($t$). For checking if answer is less than or equal to $x$ (`check, So, after binary search is over, we should run `check(t)` to get a sample matching.

Full text and comments »

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

92.
By bashkort, 2 years ago, In English
LI2 Contests Announcement — Free Programming Course Hi everyone! I'm thrilled to invite you to the **LI2 Contest &mdash; free collection of high-quality contests to master every topic** &mdash; here, on Codeforces! [Group Link! Click here!](https://codeforces.me/group/jtU6D2hVEi/blog) ### Current avialibale list of topics: Loops; Prefix Sums; Sortings; Binary Search; Recursion; Sweepline; Two Pointers; Linear Data Structers (stack, queue, etc); Graphs, DFS, BFS; Dynamic Programming; DSU; Shortest Paths; Minimum Spanning Tree; Greedy; ... ### Why this course? I believe that finding high-quality problems is the hardest part of practice, especially when you are only getting your feet wet with competitive programming. There are many lectures and articles, but not so many open collections of problems for each topic. ### Time-tested I guarantee you that this course is time-tested, **I used it myself**. LI2 is short for Boarding Lyceum №2 in Kazan &mdash; the school I study in. So we've been using this course for...
Loops; Prefix Sums; Sortings; Binary Search; Recursion; Sweepline; Two Pointers; Linear Data

Full text and comments »

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

93.
By dreamoon_love_AA, history, 11 years ago, In English
Codeforces Round #320 [Bayan Thanks-Round] Editorial ## [Problm 1 : Raising Bacteria](http://codeforces.me/problemset/problem/579/A) Write down $x$ into its binary form. If the $i^{th}$ least significant bit is $1$ and $x$ contains $n$ bits, we put one bacteria into this box in the morning of $(n+1-i)^{th}$ day. Then at the noon of the $n^{th}$ day, the box will contain $x$ bacteria. So the answer is the number of ones in the binary form of $x$. [code of author's friend: this](http://codeforces.me/contest/579/submission/13053439) ## [Problem 2 : Finding Team Member](http://codeforces.me/problemset/problem/579/B) Sort all possible combinations from high strength to low strength. Then iterator all combinations. If two people in a combination still are not contained in any team. then we make these two people as a team. [author's code: this](http://codeforces.me/contest/579/submission/13053526) ## [Problem 3 : A Problem about Polyline](http://codeforces.me/problemset/problem/578/A) If point ($a$,$b$) is located on t...
[author's code : this (using binary search )](http://codeforces.me/contest/578/submission/13053708)

Full text and comments »

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

94.
By avighnakc, history, 19 months ago, In English
Efficient iterative segment tree with binary search If you’re into competitive programming, you’ve probably come across [this fantastic blog](https://codeforces.me/blog/entry/18051). It introduces a super efficient, compact segment tree really shifted the way I thought about segment trees. So today, while experimenting with this idea, I thought: "Why not extend it to support binary search?" And that’s exactly what I did. Here’s my attempt at it, and I thought it was worth sharing. ## Quick recap: `std::partition_point` If you’re familiar with binary search, you might know about `std::partition_point`. It’s a C++ function that returns the first false value in a range. C++20 also added `std::ranges::partition_point` (see [one-line binary search](https://codeforces.me/blog/entry/134777)), which makes binary search even more concise: basically, a one-liner. Taking some inspiration from this (mainly for the name), here's how I adapted it for the segment tree: ## Implementation ```cpp template <typename T> class SegmentTree...
Efficient iterative segment tree with binary search, ## Quick recap: `std::partition_point` If you’re familiar with binary search, you might know about, ## The `partition_point()` function This is where I added binary search. The `partition_point, So today, while experimenting with this idea, I thought: "Why not extend it to supportbinary

Full text and comments »

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

95.
By kartik8800, 7 years ago, In English
CSES Range Queries section editorial **UPD:** some video editorials on range query data structures: [youtubePlaylist](https://www.youtube.com/playlist?list=PLb3g_Z8nEv1isaHPaXL1j-pSo60812JtY) Hello Codeforces, In this blog I will try to write a well detailed editorial for the CSES Range Queries section. The motivation for this editorial comes from https://codeforces.me/blog/entry/70018. Quoting [user:icecuber,2020-05-09] "I think [CSES](https://cses.fi/problemset/) is a nice collection of important CP problems, and would like it to have editorials. Without editorials users will get stuck on problems, and give up without learning the solution. I think this slows down learning significantly compared to solving problems with editorials. Therefore, I encourage others who want to contribute, to write editorials for other sections of CSES." So here I am writing an editorial for the range queries section. If you find any error or maybe have a better solution to some problem please do share. Range Sum Queries I =...
Binary Search. , So clearly, we can simply do a binary search to find the correct hotel and assign it to current, Time complexity is O(Mlog^2N), logN steps for the binarySearch and each step of thebinary search

Full text and comments »

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

96.
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...
based on my experiences. I assume you already have some knowledge and know simple things likebinary, binary search and figure out where in the code the outputs are first not what you'd expect. If you

Full text and comments »

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

97.
By SomethingNew, history, 3 years ago, translation, In English
CodeTON Round 6 (Div. 1 + Div. 2, Rated, Prizes!) Editorial We apologize for the technical difficulties in Task B. We hope you enjoyed the rest of the contest. We will add hints soon. [problem:1870A] <spoiler summary="Tutorial"> Note that if $min(n, x+1) < k$, then the answer is $-1$. Otherwise, there are two cases: - If $k=x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, \dots, k-1]$. - If $k \ne x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, x, \dots, x]$. In both cases, we can construct the array and calculate its sum in linear time. The overall complexity is $O(n \cdot t)$. </spoiler> [problem:1870B] <spoiler summary="Tutorial"> Note that after performing the operation on $b_j$, which has some bit set to 1, this bit will become 1 for all numbers in $a$ (and will remain so, as a bit cannot change from 1 to 0 in the result of an OR operation). If $n$ is even, then in the final XOR, this bit will become 0, as it will be equal to the XOR of an even number of ones. If $n$ is odd, then ...
The trie has a depth of $O(\log(n))$, binary search takes the same time, so the overall asymptotic

Full text and comments »

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

98.
By Sad_reacts_only, 6 years ago, In English
Changes in Codeforces problem style over 2020 Sorry for my poor English. I am talking only from Div2 perspective as I think Div1 contest are still ok from this point of view. During 2020 codeforces moved from having problems with variation over known algorithms and data structures to constructive heavy contests. I am not saying that having constructive problems are bad but their amount is way too high and I guess most of us will agree that now a days problems on topics like binary search, DP, Graphs or segment tree or other data structures etc are almost extinct in Div2 rounds. Lets take last Div2 [contest:1474] as an example someone who knows programming language and basic number theory could solve problems till E and can get 1st rank. So in theory someone could become a master or International Master with just number theory and programming language knowledge. I used to like constructive problems a lot (Actually one of my stronger topics) but now a days there are just so much constructive problems that they ...
like binary search, DP, Graphs or segment tree or other data structures etc are almost extinct in

Full text and comments »

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

99.
By toam, history, 4 years ago, In English
Introduce my masterpieces of math problem I sometimes make problems and post them in Japanese local contest [yukicoder](https://yukicoder.me/). I want many people to know math problems I made, so I introduce some of them. Let's try!! [LCMST](https://yukicoder.me/problems/no/1917) ------------------ #### Problem Statement Consider a complete graph $G$ on $N$ vertices. The weight of edge between vertex $i$ and $j$ is least common multiple of $A_i$ and $A_j$. Find the total weight of the edges contained in a minimum spanning tree of $G$. #### Constraints - $2\leq N \leq 10^6$ - $1\leq A_i\leq 10^5$ - Time Limit is 4000ms #### Sample Consider the case where $N=3$ and $A=(2,3,4)$. The answer is $10$. This is optimal to draw edges between $(1,2),(1,3)$. These have weights $\mathrm{lcm}(A_1,A_2)=\mathrm{lcm}(2,3)=6, \mathrm{lcm}(A_1,A_3)=\mathrm{lcm}(2,4)=4$, respectively. #### Hints <spoiler summary="Hint1"> If $A_i=A_j$, draw a edge between $(i,j)$. So you need only consider the case $A$ is distinct. </spo...
Binary search

Full text and comments »

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

100.
By thenymphsofdelphi, 4 years ago, In English
Codeforces Round #873 (Div. 1 & 2) Editorial ## [problem:1828A] Idea: [user:thenymphsofdelphi,2023-05-14] <br> Preparation: [user:Mike4235,2023-05-14] <spoiler summary="Hint 1"> Remember the sum of the first $n$ positive integers? </spoiler> <spoiler summary="Hint 2"> Every positive integer is divisible by $1$. </spoiler> <spoiler summary="Solution"> Consider the array $a = \left[1, 2, \ldots, n\right]$ that satisfies the second condition. It has the sum of $1 + 2 + \dots + n = \frac{n(n+1)}{2}$. One solution is to notice that if we double every element $(a=\left[2, 4, 6, \ldots, 2n\right])$, the sum becomes $\frac{n(n+1)}{2} \times 2 = n(n + 1)$, which is divisible by $n$. Another solution is to increase the value of $a_1$ until the sum becomes divisible by $n$. This works because every integer is divisible by $1$, and we only need to increase $a_1$ by at most $n$. Time complexity: $\mathcal{O}(n)$ </spoiler> <spoiler summary="Implementation 1"> ```c++ #include <bits/stdc++.h> using namespace s...
We can use two pointers or binary search to efficiently find the (number of $k$ such that $a_k

Full text and comments »

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

101.
By Intellegent, 14 months ago, In English
Codeforces Round 1060 (Div. 2) Editorial Thank you for participating! Special thanks to [user:reirugan,2025-10-16] for writing the analysis for **B, D, E** and to [user:Proof_by_QED,2025-10-16] and [user:LMeyling,2025-10-16] for helping to optimise **F1**, leading to the creation of **F2**. <spoiler summary="Rating Predictions"> | Problem | A | B | C1 | C2 | D | E | F1 | F2 | | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | ---: | | [user:reirugan,2025-10-19] | 800 | 1100 | 1200 | 1600 | 1700 | 2000 | 2200 | ¯\\_(ツ)_/¯ | | [user:eric899,2025-10-19] | 800 | 1000 | 1300 | ¯\\_(ツ)_/¯ | 1600 | ¯\\_(ツ)_/¯ | ¯\\_(ツ)_/¯ | ¯\\_(ツ)_/¯ | | [user:Proof_by_QED,2025-10-19] | 800 | 1100 | 1500 | 1900 | 1600 | 2100 | 2300 | 2600 | | [user:_istil,2025-10-19] | 800 | 1100 | 1400 | 1800 | 1800 | 2100 | 2000 | 2500 | | [user:anango,2025-10-19] | 800 | 1100 | 1300 | 1900 | 1800 | 2200 | 2400 | 2700 | | [user:FzArK,2025-10-19] | 800 | 1100 | 1400 | 1800 | 1900 | ¯\\_(ツ)_/¯ | 2400 | ¯\\_(ツ)_/¯ | | [user:intel...
all choices of $i$, then binary search for the optimal choice of $y$, which in total takes $O(n\log

Full text and comments »

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

102.
By sahaun, history, 10 months ago, In English
[Tutorial] Continuous Collision Detection in Video Games using Binary Search Hello Codeforces! [As promised almost three years ago](https://codeforces.me/blog/entry/116410#comment-1029354), I have finally found the time and scope to write about using CP techniques outside CP itself. My first post is about a **use case of binary search in video games**. Unfortunately, the post is written in MDX (with videos and custom elements that Codeforces doesn't support), so I have to post a link if you want to read the whole post. You can find it here: [Continuous Collision Detection in Video Games using Binary Search](https://sahaun.com/blog/continuous-collision-detection-in-video-games-using-binary-search/) Here is a summary. --- ### The Problem In a standard game loop, objects "teleport" from position $(x, y)$ to $(x + \Delta x, y + \Delta y)$ in a single frame. If a wall is thin enough, a fast-moving bullet can start on one side and end on the other in a single frame, completely skipping the collision check. This well-known bug is called _tunne...
[Tutorial] Continuous Collision Detection in Video Games using Binary Search, ### The Solution: Binary Search on Time, My first post is about a **use case of binary search in video games**. Unfortunately, the post is, Since the function is monotonic, we can Binary Search on the time $t$ to find the first moment of, Thanks for reading! Let me know if you use binary search for anything else., You can find it here: [Continuous Collision Detection in Video Games using Binary Search](https

Full text and comments »

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

103.
By dmkozyrev, history, 8 years ago, translation, In English
[Tutorial] Rolling hash and 8 interesting problems [Editorial] **UPD**: while I was translating this post from Russian to English, [user:dacin21,2018-07-06] wrote his post, more advanced, [link](http://codeforces.me/blog/entry/60442). I hope that my post will help beginners, but in my post more rough estimates. And in Russia we call **rolling hashes** as a **polynomial hashes**. Hello, codeforces! This blogpost is written for all those who want to understand and use polynomial hashes and learn how to apply them in solving various problems. I will briefly write the theoretical material, consider the features of the implementation and consider some problems, among them: 1. Searching all occurrences of one string of length $n$ in another string length $m$ in $O(n + m)$ time 2. Searching for the largest common substring of two strings of lengths $ n $ and $ m $ $(n \ge m) $ in $O((n+m \cdot log(n)) \cdot log(m))$ and $O(n \cdot log(m))$ time 3. Finding the lexicographically minimal cyclic shift of a string of length $ n $ in $ O(n \cdo...
palyndromes and use binary search for searching first position not equal symbol., /W18tw5) sorting and binary search in connection with the fact that this piece obeys the C++ standard

Full text and comments »

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

104.
By maomao90, 5 years ago, In English
Global Round 20 Editorial Hope that everyone enjoyed the round. Feel free to ask questions in the comments if you do not understand any part of the editorial [problem:1672A] Author: [user:errorgorn,2022-04-23] <spoiler summary="Hints"> <spoiler summary="Hint 1"> No matter what move each player does, the result of the game will **always** be the same. </spoiler> <spoiler summary="Hint 2"> Count the number of moves. </spoiler> </spoiler> <spoiler summary="Tutorial"> Let us consider the ending state of the game. It turns out that at the ending state, we will only have logs of $1$ meter. Otherwise, players can make a move. Now, at the ending state of the game, we will have $\sum\limits_{k=1}^n a_k$ logs. And each move we increase the number of logs by exactly $1$. Since we started with $n$ logs, there has been exactly $(\sum\limits_{k=1}^n a_k) - n$ turns. Alternatively, a log of length $a_k$ will be cut $a_k-1$ times, so there will be $\sum\limits_{k=1}^n (a_k-1)$ turns. If the...
for each height and the $\log(n \cdot 2000)$ comes from the binary search at the start., First, we can binary search for the minimum possible width for height $1$. This value is $(\sum_{i

Full text and comments »

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

105.
By bicsi, history, 4 years ago, In English
"Merging treaps" -- or how to merge sorted sets in good complexity... ... without doing much of anything. I've been obsessed for the last two days about problem [Data Centers](https://ubilo.tubitak.gov.tr/egoi2022/assets/tasks/DataCenters.pdf) from EGOI 2022. In particular, it has a subtask where $1 \leq N \leq 10^5$ and $1 \leq S \leq 5000$, where it seems $O(NS)$ wouldn't fit TL. I've been conjecturing that using treaps would amortize to good complexity, and after two days of burning grey matter, I've finally found a proof, and it's pretty cool to make a blog out of it. The problem basically starts with an array $[v_1, v_2, ..., v_N]$, where $1 \leq v_i \leq V$ for all $i$. It then asks us to iteratively simulate the operation: "Subtact $x_i$ from the biggest $m_i$ elements.". All this while keeping the array sorted. We'll show that just using treaps (or any BBST for that matter) yields a good amortized complexity. More exactly, we'll prove $O((N + Q) \log V \log N)$, and it should actually be better in practice. ### Naive solution with tr...
$O(k \log N)$ (via $k$ binary searches and $k$ splits)., Also, doing $\log N$ binary searches on treaps might be inconvenient. Another approach that is

Full text and comments »

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

106.
By peltorator, 6 years ago, translation, In English
Video about Disjoint Sparse Table or how to answer all queries in constant time Hi! I made a video on the disjoint sparse table. It's a generalization of a sparse table that expands the possibilities of its application. [Link to the video](https://youtu.be/NbAtm1j5gVA) The video is in Russian but English subtitles are available. I'd be glad if you watch the video and leave a comment below with your impressions, thoughts, and ideas for future videos. You may also want to text me on [telegram](https://t.me/peltorator) if you didn't understand something or you have any questions. I'll be glad to answer! ![ ](/predownloaded/a0/06/a0062d5909d856f50fe9e7d3cdc1acb4ffb45173.png) I'm gonna make more videos in the future. Both on basic algorithms such as prefix sums, binary search, sorting, etc., and also some advanced topics such as heavy-light decomposition, link-cut tree, lambda optimization, FFT, and so on. If you're interested, consider subscribing to my channel! My disjoint sparse table realizations: [Easy one](https://pastebin.com/wc1FsZri) [E...
I'm gonna make more videos in the future. Both on basic algorithms such as prefix sums,binary

Full text and comments »

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

107.
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...
Use binary search and prefix sums to rewrite the constraint on $\text, You can use binary search on the answer. Why ?

Full text and comments »

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

108.
By MikeMirzayanov, history, 11 years ago, translation, In English
Open Codeforces Rating System [updated on October 2015] Starting from October 2015 ratings formulas are open. They are given in the post. It is likely that from time to time we will change them slightly, it will be reflected here. The basic idea of Codeforces rating system is to generalize Elo rating to support games with multiple participants. Each community member is characterized by value $r_i$ &mdash; integer number. Roughly speaking, the higher value means better results in the contests. Rating is calculated/recalculated so that the equality strives to be correct: $$P_{i,j}=\frac{1}{1+10^{\frac{r_j-r_i}{400}}},$$ where $P_{i,j}$ is probability that the $i$-th participant has better result than the $j$-th participant. Therefore for two participants the probability to win/lose depends on subtraction of their ratings. For example, if the difference of ratings is equal to 200 then stronger participant will win with probability ~0.75. If the difference of ratings is equal to 400 then stronger participant will win with probabi...
binary search find such rating value $R$ which the $i$-th participant should have to have a $seed_i=m_i

Full text and comments »

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

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

Full text and comments »

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

110.
By polosatic, history, 2 years ago, In English
Formula VS binary search (precision issue on AtCoder) Recently I was upsolving [this problem](https://atcoder.jp/contests/abc356/tasks/abc356_g). My subtask was as follows: given three points: `A, B, C`, and I need to find the intersection point of 2 lines: AB and OC, where O has (0;0) coordinates. <spoiler summary="Code, 90/92 tests passed"> ~~~~~ #include <bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define fi first #define se second #define pb push_back #pragma GCC optimize("unroll-loops,O3") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #define cok cout << (ok ? "YES\n" : "NO\n"); #define dbg(x) cout << (#x) << ": " << x << endl; #define dbga(x,l,r) cout << (#x) << ": "; for (int ii=l;ii<r;ii++) cout << x[ii] << " "; cout << endl; #define int long long #define pi pair<int, int> const int N = 1e6+9; int n, q; struct pt { int x, y; pt operator-(pt b) {return {x - b.x, y - b.y};} int operator%(pt b) {return x * b.y - y * b.x;} int len() {return x * x + y *...
Formula VS binary search (precision issue on AtCoder), using binary search (`findgood()` function) and got AC. Then I submitted the solution above with `find, Can anybody explain what actually happened? How can formula be less precise than binary search?

Full text and comments »

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

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

Full text and comments »

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

112.
By Keshi, 5 years ago, In English
Codeforces Global Round 17 Editorial ###[problem:1610A] Idea: [user:Anti-Light,2021-11-24], Preparation: [user:DeadlyCritic,2021-11-24] <spoiler summary="Hints"> <spoiler summary="Hint 1"> $ans \le 2$ </spoiler> <spoiler summary="Hint 2"> If $n = 1$ and $m = 1$ then $ans = 0$. <a href="https://emoji.gg/emoji/5500-thosewhoknow"><img src="https://emoji.gg/assets/emoji/5500-thosewhoknow.png" width="20px" height="20px" alt="ThoseWhoKnow"></a> </spoiler> </spoiler> <spoiler summary="Solution"> [tutorial:1610A] </spoiler> <spoiler summary="Implementation"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(); cout.tie(); int t; cin >> t; while(t--){ int n, m; cin >> n >> m; if(n == 1 && m == 1){ cout << "0\n"; } else if(min(n, m) == 1){ cout << "1\n"; } else cout << "2\n"; } } ~~~~~ </spoiler> ###[p...
We use binary search to find the maximum $i$ that it's possible to

Full text and comments »

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

113.
By aryanc403, 2 years ago, In English
Codeforces Education Round 170 Discussion Stream (with Hints) [I'm currently live discussing the problems.](https://youtu.be/2x4DX4Wqrpo) I will add problemwise timestamp after the discussion stream, and also format the blog properly. You can join in if something in this blog is unclear or you have more questions. [problem:2025A] <spoiler summary="Idea"> We can do one of the following 2 things - - Either write both strings without using 2nd action - Or we first write longest common prefix string, then use 2nd action and then write the remaining strings. </spoiler> My submission &mdash; [submission:285842091] [problem:2025B] <spoiler summary="Hint 1"> Use pen and paper and write down table C. </spoiler> <spoiler summary="Hint 2"> Table C looks like this - ~~~~~ 1 1 1 1 2 1 1 2 4 1 1 2 4 8 1 1 2 4 8 16 1 ~~~~~ </spoiler> <spoiler summary="Hint 3"> If $k=n$, $C[n][k] = 1$, else $C[n][...
each fixed L, [binary search](https://usaco.guide/silver/binary-search) largest R such that you can

Full text and comments »

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

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

Full text and comments »

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

115.
By Maxim, 8 years ago, translation, In English
Binary search on real values What does a typical binary search in real values look like? Like this: ~~~~~ float l = 0.0f, r = 1e14f; for (int i = 0; i < iteration_count && l + eps < r; ++i) {     float mid = 0.5f * (l + r);     if (check(mid))         r = mid;     else         l = mid; } ~~~~~ Here `l` and `r` are the boundaries that depends on the condition, `check (x)` is a function that returns true starting from some x and false before x and we need to find this x. As a rule, `l` or `0.5 * (l + r)` is the answer. But there are several disadvantages: 1. The number of iterations must be choosed balancing between the precision and the execution time. 2. Answer with an error. ### What can be done with this? First, let's take a look at how real values are represented. You can read in detail, for example, [here] (https://en.wikipedia.org/wiki/Single-precision_floating-point_format) and [here] (http://www.volkerschatz.com/science/float.html). We use the fact that if we perform the operati...
Binary search on real values, What does a typical binary search in real values look like? Like this:

Full text and comments »

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

116.
By ouuan, history, 7 years ago, In English
Codeforces Round #564 Editorial [problem:1173A] Idea: [user:ouuan,2019-06-07] <spoiler summary="Tutorial"> Consider the two edge cases: all the $z$ persons upvote / all the $z$ persons downvote. If the results are the same in these two cases, it is the answer. Otherwise, the result is uncertain. </spoiler> <spoiler summary="Solution"> ```cpp #include <iostream> using namespace std; const char result[4] = {'+', '-', '0', '?'}; int solve(int x, int y) { return x == y ? 2 : x < y; } int main() { int x, y, z; cin >> x >> y >> z; cout << result[solve(x + z, y) == solve(x, y + z) ? solve(x, y) : 3]; return 0; } ``` </spoiler> [problem:1173B] Idea: [user:Sooke,2019-06-07] <spoiler summary="Tutorial"> - $m\ge\left\lfloor\frac n 2\right\rfloor+1$ Consider the chess pieces $1$ and $n$. $\because\begin{cases}|r_1-r_n|+|c_1-c_n|\ge n-1\\\\|r_1-r_n|\le m-1\\\\|c_1-c_n|\le m-1\end{cases}$ $\therefore m-1+m-1\ge n-1$ $\therefore m\ge\frac{n+1}2$ $\because m\...
And to answer the query, you can keep the current value of $x$ and then find withbinary search by

Full text and comments »

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

117.
By oversolver, 4 years ago, In English
Outstanding members of my cp library I like to build my [cp library](https://github.com/demidenko/olymp-cpp-lib). I am not aiming to fill it by each algo I have met, so content looks poor. Instead I am focusing on frequently used features or implement convenient api for powerful methods. Also I like to rate cp libraries of others and currently I noticed that my lib have enough implementations which I never seen before, so I want to share it with community. Hope it will inspire you to improve or rewrite your library and eventually rethink about some algorithms (which happens to me couple times). ## #5 Centroid decomposition [graphs/trees/centriod_decomposition.cpp](https://github.com/demidenko/olymp-cpp-lib/blob/master/graphs/trees/centriod_decomposition.cpp) This one is the perfect example of what I am calling convenient api. I've seen a lot of centroid decomposition snippets and almost all of them is template code or unfinished data structure with piece of code where you need to add your solution. I have s...
## #4 Parallel binary search

Full text and comments »

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

118.
By Theo830, 3 years ago, In English
Codeforces Round #912 (Div. 2) Editorial Problems A, B, C, D1 and E were authored by me and [user:Adam_GS,2023-11-30] authored D2 and F. [problem:1903A] <spoiler summary="Hint"> If $k$ is greater or equal to $2$ you can always swap adjacent elements. </spoiler> <spoiler summary="Solution"> [tutorial:1903A] </spoiler> <spoiler summary="Code (C++)"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n,k; cin>>n>>k; int arr[n]; for(int i = 0;i < n;i++){ cin>>arr[i]; } if(is_sorted(arr,arr+n) || k > 1){ cout<<"YES\n"; } else{ cout<<"NO\n"; } } return 0; } ~~~~~ </spoiler> <spoiler summary="Rate this problem"> Good Mid Bad </spoiler> [problem:1903B] <spoiler summary="Hint"> Think of each bit independently. </spoiler> <spoiler summary="Solut...
Use binary search the answer and 2-sat.

Full text and comments »

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

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

Full text and comments »

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

120.
By Geothermal, history, 3 years ago, In English
A Highly Experimental Training Plan for Beginners Very loosely inspired by some comments on [Thoughts on Reaching Cyan?](https://codeforces.me/blog/entry/101561) and [my recent AMA](https://codeforces.me/blog/entry/118845). Until now, I've avoided telling beginners to practice math before working on competitive programing problems because I haven't figured out a helpful way of doing so. This post is my attempt at telling grays to train math first in a way that might lead to improvement without an absurd time commitment. ## Introduction This section is largely motivation for why I'm proposing this training plan. If you just want to see the instructions for the training plan I'm proposing, you can skip this part. The first subsection in particular is not especially relevant to the rest of the post, but I wanted to have some documentation explaining why I still think the traditional "just solve problems" advice is good. ### The Conventional Advice on Improvement I'm frequently asked for advice on how to improve at co...
all, and I needed to learn e.g. what big-O notation is, what DP is, what it means tobinary search

Full text and comments »

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

121.
By cry, 4 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...
There are alternative solutions using binary search with complexity $O(k\log nk)$ or $O(k\log n\log

Full text and comments »

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

122.
By wuhudsm, history, 3 years ago, In English
My ultra-short problemset which can be read in 60s (Last updated time:$2023/8/31,14$ problems) Hi guys,here I'd like to share some of my problems(will continue to be updated, depending on your feedback). All the problems are created by myself. They contain my aesthetic of problems: the neater,the better. Interest and educational significance are also important. You can find the editorial for all the problems in the link,so I will only write down some interesting points under the statement. Let's go :) #### [1.Increasing and Decreasing](https://mirror.codeforces.com/contest/1864/problem/A) Construct an array $a$ consisting of $n$ integers which satisfies the following conditions: - $a_1=x,a_n=y$; - $a$ is **strictly** increasing; - if we denote $b_i=a_{i+1}-a_{i}$ for $1 \leq i \leq n-1$, then $b$ is **strictly** decreasing. <spoiler summary="Constraint"> $1 \le x < y \le 1000,3 \le n \le 1000$ </spoiler> <spoiler summary="Difficulty"> DIV2A </spoiler> <spoiler summary="Point"> One of the easi...
Including an experience (not accurate) that "most interaction problems involve binary search".

Full text and comments »

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

123.
By awoo, history, 7 years ago, translation, In English
Educational Codeforces Round 88 Editorial [problem:1359A] Idea: [user:BledDest,2020-05-29] <spoiler summary="Tutorial"> [tutorial:1359A] </spoiler> <spoiler summary="Solution 1 (BledDest)"> ~~~~~ t = int(input()) for i in range(t): n, m, k = map(int, input().split()) d = n // k a1 = min(m, d) a2 = (m - a1 + k - 2) // (k - 1) print(a1 - a2) ~~~~~ </spoiler> <spoiler summary="Solution 2 (BledDest)"> ~~~~~ t = int(input()) for i in range(t): n, m, k = map(int, input().split()) ans = 0 d = n // k for a1 in range(m + 1): for a2 in range(a1 + 1): if(a1 > d): continue if(a1 + a2 > m): continue if(a1 + (k - 1) * a2 < m): continue ans = max(ans, a1 - a2) print(ans) ~~~~~ </spoiler> [problem:1359B] Idea: [user:BledDest,2020-05-29] <spoiler summary="Tutorial"> [tutorial:1359B] </spoiler> <spoiler summary="Solution (pikmike)"> ...
You can also find the optimal $k$ with binary search but the formulas are exactly the same and you

Full text and comments »

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

124.
By humbertoyusta, history, 6 years ago, In English
K-th smallest edge on a tree's path, a tutorial about its approaches In this blog I will be talking about a problem that I consider instructive and interesting, because it has several solutions from which some tricks can be learned. ### Prerrequisites: * Tree basic theory * Binary Search * Euler Tour * Lowest common ancestor * Persistent Segment Tree. Note that you don't need all of them for each approach. ### Tricks or techniques that you can learn with the discussion of this problem: * Some square root application in descomposition of search space of queries * How to know in $O(1)$ if a node is an ancestor of some other node in a tree * Parallel Binary Search * The persistent segment tree can be builded over a tree ### Story: I created a version of this problem a while ago (which will be left as bonus challenge at the end of this blog), and I thought to put it in a contest that I am planning (Maybe not in the near future). But then ~dmga44,2021-04-11 (thanks to him for discussing this problem with me, and provide feed...
### Parallel binary search (with divide and conquer) approach:, * Parallel Binary Search, * Tree basic theory * Binary Search * Euler Tour * Lowest common ancestor * Persistent Segment

Full text and comments »

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

125.
By Lewin, 10 years ago, In English
Codeforces Round #385 Editorial Short solutions: - Div2A: How many times do we need to do a cyclic shift to consider all possible ones? Afterwards, what data structure allows us to easily check number of distinct elements? - Div2B: Imagine the process in reverse. What types of identical shapes can I get if I cut a rectangle into two pieces? Remember, pieces cannot be rotated or flipped. - Div2C / Div1A: How do we handle components with special nodes? What do we do with the ones without special nodes? - Div2D / Div1B: We don't get many questions, so is there a way to "parallelize" questions? Another approach, can we split up the condition i != j somehow using bits? - Div2E / Div1C: First, somehow reduce it so r_i,b_i <= n. Now, we can bound the excess tokens by a small number, so we can do bitmask dp from here. - Div1D: The optimal circle must touch a blue point. Now, either consider the inversion, or do a binary search - Div1E: What makes a list good? How fast can we do this check, and how many times do we n...

Full text and comments »

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

126.
By maomao90, history, 3 years ago, In English
Breaking the 100 point barrier for IOI 2010 Maze After 21 days and 56 submissions on [IOI 2010 Maze](https://oj.uz/problem/view/IOI10_maze?locale=en), I finally broke the 100 point barrier and achieved a score of 100.081 / 100. ![Score distribution](/predownloaded/3a/0a/3a0a7cf4905b5c66c3eac59c02f5215bdd9365e8.png) [cut] ![Page 3 of submissions](/predownloaded/a4/7e/a47e4cf96e4646b18bf9faaa26b0fd231a594c0f.png) ![Page 2 of submissions](/predownloaded/55/2f/552fe37390378626f2b2171a9e42bd61d6a5fc7b.png) ![Page 1 of submissions](/predownloaded/5a/82/5a82cb9bb180f3951dbeee7349507c983063de1a.png) # Methodology It's just simulated annealing + a lot a lot of time. The neighbour function to generate a new state was just randomly choosing one cell to change from '$\text{#}$' to '$\text{.}$' or from '$\text{.}$' to '$\text{#}$'. Remember to take care that there must be exactly one '$\text{.}$' at the edge of the maze at all times. The energy function that we are optimizing is the question itself, which is the maxim...
to ensure that enough exploration takes place. I binary search on the $\alpha$ to use based on how

Full text and comments »

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

127.
By Gellyfish, 3 years ago, In English
About Codeforces Round 901 (Div.1, Div.2) First of all, I'm sorry for the unreasonable difficulty. The problems are much harder than usual, so we choose 3 hours. But it seems that it didn't work :( About the problems: - [problem: 1874C] : It seems that the out-degree of the vertex is not maximized, [user:znstz2018,2023-10-01] prepared it for me, but I forgot to check the data, I'm sorry for the unfairness caused to the round. - [problem: 1874D] : There are some hacks appearing in this problem. Some adjustments in the approximate solution past the problem, but there's really nothing I can do about it. Hack can only make the adjustments you need to make larger, but if you have a good approximate solution and adjust up to about $[-50, +50]$. You can pass all the test cases satisfying $1 \leq n \leq m \leq 3000$. Also, different approximate solutions have different hacks for them, we really have no way to hack all of them. But luckily, no matter what solution you use, you must know $ans = n + 2 \times \sum_{i=1}^n\sum_{j=...
monotone while transiting, so we can use two pointers instead of binary searching.

Full text and comments »

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

128.
By TheScrasse, history, 3 years ago, In English
Problems that I authored so far Hi everyone, after [contest:1854], maybe it's time to collect all my problems here. For now, I've mainly invented easy-ish problems. I wish to invent a very hard problem sooner or later :) <spoiler summary="Update after Pinely Round 3"> Done :D </spoiler> I'm putting the story of each problem under spoiler, because it may contain parts of the solution. I invented many problems by just trying random setups until I came up with something solvable, but some problems (especially the harder ones, for example [problem:1854D]) may have more interesting stories. Fun facts: - I struggled a lot to find a suitable div2A for [contest:1654]. I proposed a lot of problems that turned out to be unsuitable (for example, because they were too hard), then I used them somewhere else. - While I was writing this blog, I realized that [problem:1849E] is identical to my problem [preoii_allenamento \- Allenamento su ChinaForces](https://training.olinfo.it/#/task/preoii_allenamento/statement),...
It's basically "implement parallel binary search". The coordinator

Full text and comments »

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

129.
By AlexLuchianov, 5 years ago, In English
[Tutorial]Using Segment Trees to solve Dynamic Programming problems Both segment trees and dynamic programming are common topics in competitive programming. Sometimes, they even appear together. In this blog, we will mostly use segment trees as a black-box. As such, it is not necessary (though it is highly recommended) to know segment trees to understand this blog. Let's begin. ###Longest Increasing Subsequence(LIS) _"You are given an array $v$ containing $N$ integers. Your task is to determine the longest increasing subsequence in the array, i.e., the longest subsequence where every element is larger than the previous one._ _A subsequence is a sequence that can be derived from the array by deleting some elements without changing the order of the remaining elements."_ This problem is most often solved using binary search. There are countless tutorials about this method, so I will not discuss it in detail. However, there exists a more general way to solve it using segment trees. Since we only care about the order of the elements and not a...
The main advantage of using the segment tree solution over the binary search one is that it can, This problem is most often solved using binary search. There are countless tutorials about this

Full text and comments »

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

130.
By cry, 3 years ago, In English
Codeforces Round 952 (Div. 4) Editorial This was our first time setting a Div.4 contest. We sincerely hope you enjoyed the problems! #####[problem:1985A] Problem Credits: [user:cry,2024-05-26] <br/> Analysis: [user:cry,2024-05-26] <spoiler summary="Solution"> To swap the first character of the strings, you can use the built-in method std::swap in C++, or for each string, separate the first character from the rest of the string and concatenate it with the other string. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ string a, b; cin >> a >> b; swap(a[0], b[0]); cout << a << " " << b << endl; } } ``` </spoiler> #####[problem:1985B] Problem Credits: [user:cry,2024-05-26] <br/> Analysis: [user:cry,2024-05-26] <spoiler summary="Solution"> To maximize the number of multiples of $x$ less than $n$, it optimal to choose a small $x$, in this case, $2$. The only exception is $n = 3$, where it is op...
sorry for it. Since our intended solution is not binary search, we didn't really take overflow, So we binary search for the first $t$ such that the total damage we do in time $t$ is greater than

Full text and comments »

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

131.
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...
can be processed in $O(\log n)$ time using binary search, or $O(1)$ time using precomputed arrays of

Full text and comments »

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

132.
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...
compression, (2) do some binary search or segment tree descend to find the two corresponding cuts, and (3

Full text and comments »

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

133.
By MikeMirzayanov, 8 years ago, translation, In English
Testlib and Polygon Updates [July, 2018] Hello, Codeforces. This is a short blog to introduce you recent updates in [Testlib](https://github.com/MikeMirzayanov/testlib) and [Polygon](http://polygon.codeforces.com). # Testlib ### Generate a Permutation Now, you can easily generate a permutation with codes like this: Code | Result -|- `vector<int> p = rnd.perm(n);`| Generates 0-indexed permutation of size $n$ `vector<int> p = rnd.perm(n, 1);`| Generates 1-indexed permutation of size $n$ ### Function `println` Now, you can easily print space-separated lines in a generator. A `println` uses `cout`, thus prefer faster method if you print huge data. Some examples: Code | Result -|- `println(5);` | Print 5 and line break `println(1, 2, 3);` | Print `1 2 3` (three space separated integers) and line break `println("one", "more", 5.5);` | Print `one more 5.5` (three space separated items) and line break `vector<int> a; ...; println(a);` | Print vector $a$ (separate elements with spaces) and line break...
), generators and stress tests * `example-interactive-binary-search`: simple interactive problem on abinary

Full text and comments »

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

134.
By Semyazi, history, 12 months ago, In English
Rethinking Binary Search with Non-Monotone Predicates Binary search is one of those algorithms that's easy to understand the idea of, but it's often hard to work out the implementation details. For example, should it be $\text{lo}=0$ or $\text{lo}=1$? Should I set $\text{lo}$ to $\text{mid}$ or $\text{mid}+1$? Is the answer going to be $\text{lo}$ or $\text{hi}$? The questions are endless. As a result, I'd like to share with you a perspective on binary search that makes it easier to implement without bugs (in my opinion), and also more general. It involves abstracting out the actual binary search step by thinking of it as a method of finding a $[0,1]$ subarray in an array of $0$'s and $1$'s. After doing this, we find that binary search can be applied to search predicates that aren't monotone, allowing it to be applied to more problems that wouldn't usually be considered binary search at a glance. I hope you find it helpful! Also, huge thanks to my friends: [user:Wobert,2026-01-16] and [user:andrewtam,2026-01-16] for proofreading! :) ...
Rethinking Binary Search with Non-Monotone Predicates, it be nice if **every** binary search problem could be solved just like this? It turns out that we, // otherwise, we binary search on our predicate auto P = [&](int i) -> int { return, // template binary search int l = 1; int r = n;, // template binary search ll l = 0; ll r = (1ll << n) - 2;, Binary search is one of those algorithms that's easy to understand the idea of, but it's often hard, Bonus Binary Search Trick ================== Lastly, I want to share a trick that has been useful, Conclusion ================== Thank you for reading! In my experience, this binary search

Full text and comments »

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

135.
By Noam527, history, 4 years ago, In English
Attempting to Extend Segment Trees to Arbitrary Subsets Throughout the last several weeks I have tried to invent and solve, a generalization of segment trees (although now it doesn't fit to name it "segment trees"... see for yourself). The results are very few (and not good, if you ask me), but the problem was very appealing and fun to think about. The purpose of this blogpost is to share my experience with this problem, in order to provide curiousity to at least a few people, and also to let bright-minded users tackle this problem together, and hopefully achieve better results. Since I want to share my experience, I will also put some possibly challenging parts under spoilers, if you want to attempt it yourself. So, there is no tl;dr. Sorry :) The Motivation and The Problem ------------------------------ As the title suggests, the motivation was from inspection of segment trees. Define the following problem, which we will try to solve throughout this post: Given $n$ elements $a_0, \ldots, a_{n-1}$, initially $0$, and $m$ subs...
with arithmetic mean, we can binary search with geometric mean, for $O(\log \log E)$ iterations: indeed, You can also binary search on $k$, and use Dinic's. This should end up being $O(E \sqrt{E} \log E

Full text and comments »

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

136.
By aryanc403, 2 years ago, In English
Codeforces Round 970 Video Editorial (with Hints) [I'm currently live discussing the problems.](https://youtu.be/pZlCq4e21Cs) I will add problemwise timestamp after the discussion stream. You can join in if something in this blog is unclear or there are more questions. [problem:2008A] <spoiler summary="Idea"> - No of ones must be even. - If no of ones is zero, then no of twos must be even. These are necessary and sufficient conditions. </spoiler> My submission &mdash; [submission:279068120] <spoiler summary="Video Editorial"> <iframe width="853" height="480" src="https://www.youtube.com/embed/pZlCq4e21Cs?start=130" title="Codeforces Round 970 Solution Discussion | ABCDEFGH" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </spoiler> [problem:2008B] <spoiler summary="Hint 1"> If it is a square matrix, then N must be a perfect square. </spoiler> <spoiler su...
[Binary search](https://usaco.guide/silver/binary-search) for the

Full text and comments »

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

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

Full text and comments »

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

138.
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...
(3) pairs. This can be done with binary search on the type (1) and (2) pairs, by balancing the

Full text and comments »

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

139.
By nik_exists, 10 months ago, In English
Codeforces Round 1074 (Div. 4) Editorial Thank y'all so much for participating in my first Codeforces round! Special thanks to [user:AksLolCoding,2026-01-19] for suggesting a major change to problem D and [user:Intellegent,2026-01-19] for helping to rewrite the statement of problem F. [problem:2185A] <spoiler summary="Hint 1"> Fix an integer $x$, how could you find out the value of $y$? </spoiler> <spoiler summary="Hint 2"> Square both sides of the equation, for what values of $x$ is $x^2$ an integer? </spoiler> <spoiler summary="Editorial"> [tutorial:2185A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 0; i < n; i++) cout << i+1 << " "; cout << "\n"; } } ~~~~~ </spoiler> [problem:2185B] <spoiler summary="Hint 1"> If we were to change the problem such that you could perform as many swaps as you wanted, th...
Prefix sums, binary search, and helper methods are your friend

Full text and comments »

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

140.
By Sharon, history, 8 years ago, In English
DO NOT READ THIS POST IN THE EU !!!!HIGHLY ILLEGALL!!!! **DISCLAIMER: DO NOT READ THIS POST IF YOU ARE IN PORTUGAL FOR WORLD FINALS OR LIVE IN THE EUROPEAN UNION** Attention World Finalists: ========================== As you may know, Article 13 has been voted on by the European Union and all memes are now illegal. It is imperative that when you travel to Portugal you must LEAVE YOUR MEMES AT HOME, or they will be deleted at airport security and you will be arrested. The contents of this post must be viewed at your own risk. <spoiler summary="European-SFW mode:"> ...![ ](https://i.kym-cdn.com/photos/images/original/001/381/981/c32.jpg) </spoiler> <spoiler summary="Normal mode:"> ...It is March 32, 2, and I'm back with more expert algorithm analysis that the legendary grandmasters don't want you to see. I have to take extra discretion with this one, since the government of an entire continent decided to ban my means of passing information. Ladies and gentlemen, I present to you: The Log Trick 2 --------------- [I...
Let's write a simple, classical binary search:

Full text and comments »

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

141.
By Vectors_Master, 21 month(s) ago, In English
Codeforces Round 1007 (Div. 2) Editorial We hope you enjoyed the problems! Thank you for participating in the contest! We would love to hear your feedback in the comments. <br> <spoiler summary="How did you find the contest?"> - Great: - Good: - Average: - Bad: - Trash: </spoiler> <spoiler summary="Which problem was your favorite?"> - A: - B: - C: - D1: - D2: - E: - F: </spoiler> <spoiler summary="Which problem did you find the least enjoyable?"> - A: - B: - C: - D1: - D2: - E: - F: </spoiler> <br> [problem:2071A] <spoiler summary="Hints"> <spoiler summary="Hint 1"> When Fofo is the spectator of the first match, what is the earl...
Binary search on $p$. After fixing $p$, find the maximum $p$-towering

Full text and comments »

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

142.
By MathModel, history, 13 months ago, In English
Codeforces Round 1061 (Div. 2) Editorial ### Thank you for participating ! Special Thanks to [user:hxu10,2025-10-24] for giving me the chance to write the editorial and for [user:maomao90,2025-10-24] for enhancing the editorial !. Editorial of Problems E and F are written by hxu10, and the rest are written by me. I hope they're insightful and concise, please let me hear your opinion about it or any feedback in general &#128153;. #### [problem:2156A] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Since $m_1 \le m_2$, the total number of slices Alice ate is always at least as much as the total number of slices Bob ate. What's optimal construction ? </spoiler> <spoiler summary="Hint 2"> We want to try to minimize the difference between the total number of slices Alice ate and the total number of slices Bob ate. </spoiler> <spoiler summary="Hint 3"> The optimal construction is to let both $m_1$ and $m_2$ to be equals to one. The sequence of operations, denoted by $(m_1, m...
As noted in Hint 1.2, we can binary search on the target beauty $g$., We can binary search on the goal $g$.

Full text and comments »

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

143.
By flamestorm, 4 years ago, In English
Codeforces Round #803 (Div. 2) Editorial Thank you for participating in our contest! We hope you enjoyed it. [problem:1698A] <spoiler summary="Hint"> $k \oplus k = 0$. </spoiler> <spoiler summary="Solution"> [tutorial:1698A] </spoiler> <spoiler summary="Implementation (C++)"> [submission:162159711] </spoiler> <spoiler summary="Implementation (Python)"> [submission:162158539] </spoiler> [problem:1698B] <spoiler summary="Hint"> What happens when two consecutive piles are increased? </spoiler> <spoiler summary="Solution"> [tutorial:1698B] </spoiler> <spoiler summary="Implementation (C++)"> [submission:162159774] </spoiler> <spoiler summary="Implementation (Python)"> [submission:162158852] </spoiler> [problem:1698C] <spoiler summary="Hint"> What happens if there exist $i, j, k$ such that $a_i + a_j + a_k > a_{max}$? </spoiler> <spoiler summary="Solution"> [tutorial:1698C] </spoiler> <spoiler summary="Implementation (C++)"> [submission:162159874...
Binary search.

Full text and comments »

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

144.
By cry, 2 years ago, In English
Codeforces Round 971 (Div. 4) Editorial Thanks for participating! Despite the round being unrated, we hope you've enjoyed the problemset. We put a lot of effort into this round :prayge: I want to give huge thanks to [user:Dominater069,2024-08-28] and [user:satyam343,2024-08-28] for their heavy contributions to the subtasks of G. If you're participating out of competition, we hope you enjoyed attempting these bonus subtasks. Otherwise, we hope you will enjoy upsolving them! [problem:2009A] Problem Credits: [user:cry,2024-08-28] <br> Analysis: [user:cry,2024-08-28] <spoiler summary="Solution "> We choose $c$ between $a$ and $b$ $(a \leq c \leq b)$. The distance is $(c - a) + (b - c) = b - a$. Note that the distance does not depend on the the position $c$ at all. </spoiler> <spoiler summary="Code (Python) (ntarsis30) "> ```py for _ in range(int(input())): a,b = map(int,input().split()) print(b-a) ``` </spoiler> [problem:2009B] Problem Credits: [user:cry,2024-08-28] <br> Analysis: [user:cry...
We can use binary search to search for the greatest $i$ such that $a_1 + \dots + a_i \leq a_{i+1

Full text and comments »

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

145.
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...
(pb), then we binary search for value a.

Full text and comments »

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

146.
By Burunduk1, 15 years ago, translation, In English
VK Cup 2012 Round 2 — Разбор ** UPD: Formulas are already fixed. ** **[problem:163A]** Solution summary: dynamic programming. Sample jury solution: [submission:1415300] (author = [user:levlam,2012-03-25]) The problem could be solved with the following dynamic programming. Let $f[i, j]$ be the number of distinct pairs ("substring starting at position $i$" and "subsequence of the substring $t[j\ldots |t|]$") Then: ~~~~~ f[i, j] = f[i, j + 1]; if (s[i] == t[j]) add(f[i, j], f[i + 1, j + 1] + 1) ~~~~~ Answer = $\sum$ f[i,0] **[problem:163B]** Solution summary: sorting + binary search. Sample jury solution: [submission:1415306] (author: [user:Burunduk1,2012-03-25]) We need to find the minimal time $T$. Let us find it using binary search. Once the time is fixed, one can arrange lemmings using greedy approach starting either from the top or from the bottom. In this solution we consider the way to start from the bottom. Among all lemmings, that can get on the first ledge, l...
So, the solution consists of sorting and a binary search with a linear search inside. The time is, Solution summary: events along the circle or binary search., Solution summary: sorting + binary search., We need to find the minimal time $T$. Let us find it using binary search.

Full text and comments »

Tutorial of VK Cup 2012 Round 2
  • Vote: I like it
  • +42
  • Vote: I do not like it

147.
By aryanc403, 2 years ago, In English
Codeforces Round 962 Video Editorial (with Hints) [problem:1996A] <spoiler summary="Hint"> Greedily take Cow as long as you can. </spoiler> <spoiler summary="Video editorial"> <iframe width="853" height="480" src="https://www.youtube.com/embed/VIxp7EkV1d8?start=77" title="Codeforces Round 962 Solution Discussion | ABCDEFG | All Problems" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen width="700" height="500"></iframe> </spoiler> [problem:1996B] <spoiler summary="Idea"> Just print all index $A[i*K][j*K]$ </spoiler> <spoiler summary="Video editorial"> <iframe width="853" height="480" src="https://www.youtube.com/embed/VIxp7EkV1d8?start=390" title="Codeforces Round 962 Solution Discussion | ABCDEFG | All Problems" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cros...
[Binary search FTW](https://codeforces.me/blog/entry/92248) , Binary search on the value you will add in $k^{th}$ operation

Full text and comments »

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

148.
By Sharon, history, 8 years ago, In English
A Public Apology (+Compensation) The Introduction ---------------- On March 32nd of this year I created a blog post to share some new coding techniques that are quite easy to code and serve as very powerful optimizations (Context: [https://codeforces.me/blog/entry/58667](https://codeforces.me/blog/entry/58667)). Now of course I know I single-handedly transformed the competitive programming meta as problems had to be done according to new standards now that it is possible to make O(N) code work O(1). Super fast. However, I have to share an upsetting discovery that I made. This blog post might be too sad for you, so discretion is advised. I have added certain checkpoints within this post where you can take a break if you get too sad and you may resume reading later. I have also added some cute pictures of animals to help out with your sadness. The Story --------- It all started yesterday, when I used my usual O(1) trick to O(N) trick on problem E2 from the last contest (It seems that Mirzayanov has not a...
The Binary Search Trick (The Compensation) -----------------------

Full text and comments »

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

149.
By ahmed_aly, 16 years ago, In English
Codeforces Beta Round #67 (Div. 2) Editorial <b>Problem A:</b><br>In this problem you need to do what is written in the statement. You can do it in the following 3 steps:<br>1- Calculate C.<br>2- Remove all zeros from A, B and C.<br>3- Check if the new values form a correct equation.<br><br><a href="http://pastebin.com/1cc1xKNW">C++ solution for problem A.</a><br><br><br><b>Problem B:</b><br>This problem is a direct simulation to the rules written in the problem statement.<br>You need to iterate over all actions and parse each one to know the type of the action, and the 2 names X and Y, and if your name is X or Y then update your priority factor with this person with the action corresponding value. And take care about some special names like "post", "wall", "commented" and "on".<br>Then sort all names according to the sorting criteria mentioned in the statement.<br>Just make sure to print all names which are mentioned in the input (excluding yourself), even if the priority factor with you is 0.<br><br><a href="http://pastebin.com...
C++ solution for problem C (with binary search). <http://pastebin.com/zcEGkKhw>

Full text and comments »

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

150.
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...
[Tutorial] Nearest Neighbor Search: Locality-Sensitive Hashing, K-Dimensional Tree, Vantage-Point, position of each queried point. At this moment, it should be obvious that any binary search tree

Full text and comments »

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

151.
By vovuh, history, 7 years ago, In English
Codeforces Round #574 (Div. 2) Editorial [problem:1195A] Idea: [user:Nebuchadnezzar,2019-07-18] Preparation: [user:Nebuchadnezzar,2019-07-18] <spoiler summary="Tutorial"> [tutorial:1195A] </spoiler> <spoiler summary="Solution"> ~~~~~ // Created by Nikolay Budin #ifdef LOCAL # define _GLIBCXX_DEBUG #else # define cerr __get_ce #endif #include <bits/stdc++.h> #define ff first #define ss second #define szof(x) ((int)x.size()) using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef unsigned long long ull; int const INF = (int)1e9 + 1e3; ll const INFL = (ll)1e18 + 1e6; #ifdef LOCAL mt19937 tw(9450189); #else mt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count()); #endif uniform_int_distribution<ll> ll_distr; ll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; } void solve() { int n, k; cin >> n >> k; map<int, int> have; for (int i = 0; i < n; ++i) { int num; cin >> num; have[num]++; }...

Full text and comments »

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

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

Full text and comments »

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

153.
By Monyura, history, 11 years ago, translation, In English
Looksery Cup 2015 Editorial **UPD** Editorial of problem E was added, I apologize for the delay. Hope you found it interesting. **A. Face Detection** Author: [user:Monyura,2015-06-06] One should iterate through each 2x2 square and check if it is possible to rearrange letters in such way they they form the word "face". It could be done i.e. by sorting all letters from the square in alphabetic order and comparing the result with the word "acef"(sorted letters of word "face"). **B. Looksery Party** Author: [user:Igor_Kudryashov,2015-06-06] In any cases there is such set of people that if they come on party and send messages to their contacts then each employee receives the number of messages that is different from what Igor pointed. Let's show how to build such set. There are 2 cases. There are no zeros among Igor's numbers. So if nobody comes on party then each employee receives 0 messages and, therefore, the desired set is empty. There is at least one zero. Suppose Igor thinks that i-th emp...
Let's find the answer — the number $d$ — by using binary search. Suppose we are

Full text and comments »

Tutorial of Looksery Cup 2015
  • Vote: I like it
  • +246
  • Vote: I do not like it

154.
By SpyrosAliv, 19 months ago, In English
Codeforces Round 1020 (Div. 3) Editorial Thanks for the participation. I hope you enjoyed the problems, or at the very least learned something new. <spoiler summary="Rate Contest Quality"> - Amazing - Good - Average - Bad </spoiler> <spoiler summary="Rate Contest Difficulty"> - Very Hard - Hard - Average - Easy - Very Easy </spoiler> <spoiler summary="Favorite Problem"> - A - B - C - D - E - F - G1 - G2 </spoiler> <spoiler summary="Worst Problem"> - A - B - C - D - E - F - G1 - G2 </spoiler> <s>The codes will be posted after the hacking...
- $p_m < x$ and $m < idx_x$: the binary search will continue on $[m+1, b]$, and since $idx_x

Full text and comments »

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

155.
By UnexpectedValue, history, 4 years ago, In English
A Time Complexity Guide **Introduction** Often in Competitive Programming, we have to choose between multiple algorithms/ approaches for a problem. How do we decide which algorithm is better and which algorithm to go for? Runnning an algorithm comes at the cost in the form of time taken or memory consumed. In this blog, we will try to compare algorithms or approaches based on their Time Complexity, which simply put is the time taken by them to run. So how do we compare the algorithms? Do we calculate the exact time taken by them to run? Or do we try to predict the time taken based on our input? These approaches to calculate Time Complexity can be called as _Experimental Analysis_ and _Theoretical Analysis_ respectively. [cut] **=========================================================================================================** **Big O Notation** The Big O Notation ($O()$) provides a mathematical notation to understand the complexity of an algorithm or to represent the complexity of an a...
- **Binary Search**, Binary search is a fast searching algorithm that finds the index of a given target element in a

Full text and comments »

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

156.
By PurpleCrayon, 5 years ago, In English
[Tutorial] Euler Tour Trees (maintaining dynamic trees through their euler tour) Good morning Codeforces! Today's post regards a well-known, but surprisingly hard to learn topic, Euler Tour Trees. Prerequisites: ------------------ - Basic tree knowledge, e.g. general vocabulary - Balanced Binary Search Tree Knowledge (e.g Treaps/Splay trees). In my opinion, learning treaps is the easiest, and [user:SecondThread,2022-02-03] has a great video/problemset on treaps, so go check it out [here](https://codeforces.me/blog/entry/84017)! The BBST must store parent pointers, so make sure your implementation supports it. #### Disclaimer This idea will definitely not show up in easy problems, and is pretty uncommon. Nevertheless, it's a cool concept and it can be used to “cheese” somewhat difficult problems, and I haven't found any resources that describe it well. Brief Description of Operations ------------------ A Euler Tour Tree is a representation of a dynamic forest of trees. This means that, as long as the graph never contains any cycles, you can su...
of the tree (hence the name) in some kind of balanced binary search tree (BBST). The split/merge, Binary Search Tree Knowledge (e.g Treaps/Splay trees). In my opinion, learning treaps is the easiest

Full text and comments »

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

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

Full text and comments »

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

158.
By k1r1t0, history, 4 years ago, In English
TheForces Round #4 Editorial [Mashup] Thanks you for participating in [**TheForces Round #4**](https://codeforces.me/contestInvitation/c3b322069561ec499aff012cc7c92ac106151bb6)! Here is the editorial: <spoiler summary="Problem A"> Answer is $floor(sqrt(r)) &mdash; floor(sqrt(l &mdash; 1))$. Alternatively you can use binary search to calculate square root. <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; #define int long long int get(int r) { int tt = 0; for (int uu = r; uu >= 1; uu /= 2) while ((tt + uu) * (tt + uu) <= r) tt += uu; return tt; } int32_t main() { iostream::sync_with_stdio(0); cin.tie(0); int q; cin >> q; while (q--) { int l, r; cin >> l >> r; cout << get(r) - get(l - 1) << '\n'; } } ~~~~~ </spoiler> </spoiler> <spoiler summary="Problem B"> You always can make all bits less or equal to the most significant bit set to $1$. Also you cant make most significant bit greater. Just go through numbers and find the minimal...
Alternatively you can use binary search to calculate square root.

Full text and comments »

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

159.
By Sul_A., history, 13 months ago, In English
Testing Round 20 Editorial (officially unofficial) As the highest non-red, non-alt-account person in the round, I feel it is my duty to supply the community with an editorial. ### [problem:2168A1] <spoiler summary="Editorial"> Since $1 ≤ a_i ≤ 26$, we can assign each value from $1$ to $26$ to a letter `a-z`. </spoiler> <spoiler summary="Code"> [submission:347267664] </spoiler> ### [problem:2168A2] <spoiler summary="Editorial"> Using $7$ characters, we can encode $26^7 \approx 8 \cdot 10^9$ possibilities. For each number in the array, encode into a $7$-digit base-$26$ number. It is important to make sure each number takes up the same number of characters. </spoiler> <spoiler summary="Code"> [submission:347268278] </spoiler> ### [problem:2168B] <spoiler summary="Editorial"> Let's try to solve the problem player B has to solve. Let the range of a subarray be $max(p_l, p_{l+1}, ..., p_r) - min(p_l, p_{l+1}, ..., p_r)$. A subarray has range $n-1$ iff it contains both $1$ and $n$. We can ...
subarray has range $n-1$ iff it contains both $1$ and $n$. We can binary search on the shortest _prefix_

Full text and comments »

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

160.
By Qualified, 6 years ago, In English
Useful functions that nobody uses With [user:pllk,2021-01-15] introducing 100 more problems to the [CSES problemset](https://cses.fi/problemset/), the race for shortest code is on. Here in this blog, I talk about the many different ways of shortening code to get that shortest code. <h2>std::any_of</h2> This is a very useful function that returns true iff any of the elements in the range `[first, last)` satisfies some condition. Let's say you want to figure out if an array contains at least one 9. You could just write the naive loop and waste time in contest. ~~~~~ bool ok = 0; for(int i = 0; i < (int)(a).size(); ++i) { if(a[i] == 9) { ok = 1; break; } } ~~~~~ but you could be smart and write this all in one line. ~~~~~ bool ok = any_of(a.begin(), a.end(), [](int x) { return x == 9; }); ~~~~~ <h5>Time Complexity</h5> This is linear aka $O(n)$. <h2>std::all_of</h2> This is another useful function that functions similar to `std::any_of`. The difference is that it returns true iff all...
Let's say that you want to find if the element *val* appears in the sorted array. Standardbinary

Full text and comments »

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

161.
By ADJA, history, 6 years ago, In English
Yet more thoughts on recent "adhoc/constructive" problems discussion. What is the ideal contest distribution? (this was originally intended as a comment to another post, but it turned out very lengthy, so I separated it into its own post) As it's often in debates, I think in this one there is too much polarization on both sides (people just attack each other), and a lot of ambiguity. I think there are some points to be made. Premise ------- 1. Let's be kind to each other. Like it or not, this is just a current trend in the history of Codeforces, and it too will pass. No need to attack anyone personally. If you want to criticize, let's provide constructive suggestions. 2. I've set contests before too, and I know that setting problems and coordinating is a very difficult job. It requires a lot of hard work, skill, experience, and patience. So like Anton's and other coordinators' style or not, let's not forget that they have done a lot of work, and let's thank them for that. Thank you! 3. It's also very mean to single out one person for the possible issue. While Anton may have...
search problems in every contest", then people would fight against binary search too. I think people

Full text and comments »

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

162.
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...
We can substitute enumerating $P$ with binary search, yielding $O(2^{\frac43n}\cdot\log n)$, or

Full text and comments »

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

163.
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...
Otherwise, since $S$ contains $0$ and $c$, we can use $n$ queries of the second type tobinary

Full text and comments »

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

164.
By PrinceOfPersia, 12 years ago, In English
Hello 2015 Editorial ### Div.2 A &mdash; [Cursed Query](/gym/100571/problem/A) You should make a sequence $s_1,s_2,...,s_n$ such that $s_i = a_1 + a_2 + ... + a_i$ and use a binary search to find the first element that is greater than $t$ % $s_n$ (or `upper_bound` function in C++ ). Source code : [Here](http://paste.ubuntu.com/9710602/) ### Div.2 B &mdash; [Troynacci Query](/gym/100571/problem/B) First of all, compute sequence $f$ (0-based), then consider we have a sequence $p$ (also 0-based) (partial sum), initially all members are $0$. For each query, if $l < r$, then do : ~~~~~ p[l] = (p[l] + f[0]) % mod; p[l+1] = (p[l+1] + f[1]) % mod; p[l+1] = (1LL * p[l+1] + mod - 1LL * ((1LL * b * f[0]) % mod)) % mod; p[r + 1] = (1LL * p[r+1] + mod - f[r - l + 1]) % mod; p[r + 2] = (1LL * p[r+2] + mod - 1LL * ((1LL * a * f[r-l]) % mod)) % mod; ~~~~~ otherwise, do this : ~~~~~ p[l] = (p[l] + f[0])%mod; p[r+1] = (1LL * p[r+1] + mod - ((1LL * b * f[0])%mod))%mod...
For a query of type 2 or 3, just use a simple binary search.

Full text and comments »

Tutorial of Hello 2015 (Div.1)
  • Vote: I like it
  • +90
  • Vote: I do not like it

165.
By AlphaMale06, 3 years ago, In English
Codeforces round #900 (Div.3) Editorial Thank you for participating in the first ever Serbian Div. 3 Codeforces round! <spoiler summary="Sorry"> Before the editorial, we are sorry for the big gap between problems C and D. This was the first round we ever created (except for [user:wxhtzdy,2023-09-27]). We are striving to become better problem-setters and create more balanced problems-sets in the future. </spoiler> Also a massive thanks to [user:Vladosiya,2023-09-27] for giving us a chance to create a divison 3 round! [problem:1878A] <spoiler summary="Problem was authored and prepared by"> Author: [user:wxhtzdy,2023-09-27] Prepared by: [user:ognjentesic,2023-09-27], [user:AndrewPav,2023-09-27], [user:AlphaMale06,2023-09-27] </spoiler> <spoiler summary="Hints"> <spoiler summary="Hint 1"> When is the answer definitely "NO"? </spoiler> <spoiler summary="Hint 2"> What happens if there is no element equal to $k$ in the array? </spoiler> <spoiler summary="Hint 3"> What happens if there is an...
Try binary search.

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

168.
By aryanc403, 2 years ago, In English
Codeforces Round 972 Video Editorial (With hints) Checkout [Codeforces Month of Blog Posts Pt. II (Win $500+!)](https://codeforces.me/blog/entry/133806) [Full video](https://youtu.be/-62rIr88JLU) [problem:2005A] <spoiler summary="Hint 1"> Lets fix the count of aeiou $C_a,C_e,C_i,C_o,C_u$ What is the minimum number of subsequence palindromes? </spoiler> <spoiler summary="Hint 2"> No of palindromes that consist of only a is $2^{C_a}-1$ and similarly for eiou. So lowerbound on no of palindrome is $2^{C_a}+2^{C_e}+2^{C_i}+2^{C_o}+2^{C_u}-5$ Does there exists a permutation where this lowerbound is achievable? </spoiler> <spoiler summary="Hint 3"> This lowerbound is achieved on strings of form aaaaaaaaaeeeeeeeeeeiiiiiiiiiioooooooooouuuuuuuuu </spoiler> <spoiler summary="Hint 4"> How to find optimal values of $C_a,C_e,C_i,C_o,C_u$? </spoiler> <spoiler summary="Hint 5"> In optimal answer $|C_x-C_y| \le 1$. You can try to prove it using [exchange argumen...
To find the nearest teachers, you can either use [binary search](https

Full text and comments »

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

169.
By Aziz_05, history, 19 months ago, In English
Operation Half-Life ( Binary Search ) Intro to Binary search ================== Given a sorted array $arr$ and a target number $k$, search for $k$ in $arr$. ### Naive approach Iterate over all $arr$ which would lead to $O(n)$ time complexity. ### Binary search approach If we were at index $i$ and $arr[i] > k$ , then there is no need to check for all $j$ such that $j > i$ ( every index that comes after $i$ ) since $arr[j] > arr[i]$ therefore we can ignore every index greater than $i$ ( right side ) and update the search space. If we were at index $i$ and $arr[i] < k$, then there is no need to check for all $j$ such that $j < i$ ( every index that comes before $i$ ) since $arr[j] < arr[i]$ therefore we can ignore every index less than $i$ ( left side ) and update the search space. If we were at the middle of the array search space then after one comparison, half of the array search space will be ignored, thus after each comparison, the current search space will be divided by two, which conclude...
Operation Half-Life ( Binary Search ), ### Binary search approach, Intro to Binary search ================== Given a sorted array $arr$ and a target number $k

Full text and comments »

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

170.
By Al.Cash, 10 years ago, In English
Geometry: Polygon algorithms I decided to share my implementations for the basic polygon algorithms. I see almost no problems on this topic and I hope this will change in the future. First, let's remind the definitions we will use: 1. **Polygon** is a plane figure that is bounded by a finite chain of straight line segments closing in a loop to form a closed chain or circuit. These segments are called its edges or sides, and the points where two edges meet are the polygon's vertices or corners ([wiki](https://en.wikipedia.org/wiki/Polygon)). 2. Polygon is **convex** if a line segment connecting any two points on its boundary lies inside the polygon. Equivalently, all its interior angles are less than or equal to 180 degrees. 3. Polygon is **strictly convex** if in addition no three vertices lie on the same line. Equivalently, all its interior angles are less than 180 degrees. 4. Polygon is **simple** if its boundary doesn't cross itself. I will present two algorithms for each problem: one for **ar...
between them using binary search. Care must be taken, because one of these chains passes through 0 vertex

Full text and comments »

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

171.
By mukel, 13 years ago, In English
C++11 for programming contests... Updated: 30 December 2013 3:27 CEST (Added a brief introduction to Lambda Functions). The [new C++ standard](http://en.wikipedia.org/wiki/C++11), also known as C++11 and also as C++0x is here, with some sugars for programming contest. I'll update this thread soon with new contents (and better structure). You can use C++11 on Topcoder, Codeforces, HackerRank ... This thread is based on my own experience, so you don't need to dig on the whole C++11 specification to find some useful feature you can use in programming contests. ### The "auto" keyword: Type inference is included in many modern programming languages, and C++ is not behind, the "auto" keyword works like "var" in C#, it only tells the compiler to infer the type for us: So, ~~~~~ map< string, pair< int, int > > somyLongTypeName = map< string, pair< int, int > >(); ~~~~~ Can be shortened to, with no impact on speed, since the type is inferred at compile time: ~~~~~ auto longTypeNamesAreHistory = map< strin...
Let's implement a simple binary search to find the square root:, See also the binary search implemented using lower_bound in the "Range based for loops" section.

Full text and comments »

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

172.
By Senku, 15 months ago, In English
Alternative to Binary Lifting (kind of) Recently, I was solving a tree problem that required finding the k-th ancestor of a node in a rooted tree and LCA (lowest common ancestor) of any two nodes quickly. I knew binary lifting does both of those things in O(log n) time, but I didn't know exactly how it worked. So I tried to think of a different approach, and came up with the following algorithm. The algorithm uses the concept of DFS arrival times and binary search, which I find easier to think about than binary lifting. **It finds the k-th ancestor of any node in O(log n) time and LCA of any two nodes in O(log<sup>2</sup> n) time** (hence the "kind of" in the title). **Implementation**: Let us use the following example tree. <img src="https://i.ibb.co/bMBgFCNC/image.png" alt="image" border="0"> In this example, the DFS arrival times and node indices are the same for simplicity. #### Setup: Run DFS from the root. On arriving each node record the arrival time of that node (`tin`), the reverse mapping from arr...
Alternative to Binary Lifting (kind of), Given these facts, the `k`th ancestor can be found using binary search as given below:, Just one binary search operation, so it takes O(log n) time.

Full text and comments »

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

173.
By zscoder, history, 7 years ago, In English
Valentine's Day Contest 2020 Editorial I hope you enjoyed the contest! Expected problem difficulty is F < A < (G ~ D) < (C ~ E) < B (though it might be different for different people). I will mainly focus on explaining the full solution to the problems but I will briefly mention how to pass certain subtasks. ### Problem A &mdash; Leakage <spoiler summary="Solution"> This is unfortunately the most standard problem of the set. Obviously, we can model the friends as vertices and friendships as edges in an undirected graph. The problem basically asks us to answer queries of the form: "For a pair of vertices $u, v$, find the number of vertices $w \neq u, v$ such that removing $w$ from the graph disconnects $u$ and $v$". Removing vertices and disconnecting graphs should remind one of articulation points. The data structure to solve this problem is [block-cut tree](https://en.wikipedia.org/wiki/Biconnected_component#Block-cut_tree). Each biconnected component is considered as a block. An articulation point might be...
using binary search on segment tree of sorted vectors which should solve up to Subtask 4.

Full text and comments »

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

174.
By Wandoka, 2 years ago, In English
Manhattan trick [Tutorial] (also I have never traveled to Manhattan) **_Consider rotating coordinate plane by $45$ degrees when you encounter Manhattan distance problem_** Before I learned this trick, I had heard [this](https://codeforces.me/blog/entry/52280?#comment-363386) [phrase](https://codeforces.me/blog/entry/57534) [several](https://codeforces.me/blog/entry/62641?#comment-465966) [times](https://codeforces.me/blog/entry/116363?#comment-1028842), but I never understood what it means. Turns out it is a pretty cool and easy trick. In this blog, I explain the trick in $2$ different ways, and show how to use it in practice on one of the recent problems. I tried to make this blog approachable, tested it on a $1200$~ rated [participant](https://codeforces.me/profile/dOyana) Let's look at this [problem](https://codeforces.me/contest/1979/problem/E). I recommend thinking about it on your own for $10$-$15$ minutes. Summary of the statement: you are given **n** = $2e5$ points. You have to find $3$ points, so that the Manhattan distance be...
, and using binary search to search for a suitable $s_3$ value., -d$ and $t+d$ with binary search. The same goes for the reverse case.

Full text and comments »

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

175.
By icecuber, 7 years ago, In English
CSES DP section editorial Edit: More dp tasks have been added to CSES since this blog was created. For solutions to those problems, check out [user:UnexpectedValue,2023-02-14]'s blog [here](https://codeforces.me/blog/entry/111675). I'm using bottom-up implementations and pull dp when possible. Pull dp is when we calculate each dp entry as a function of previously calculated dp entries. This is the way used in recursion / memoization. The other alternative would be push dp, where we update future dp entries using the current dp entry. I think [CSES](https://cses.fi/problemset/list/) is a nice collection of important CP problems, and would like it to have editorials. Without editorials users will get stuck on problems, and give up without learning the solution. I think this slows down learning significantly compared to solving problems with editorials. Therefore, I encourage others who want to contribute, to write editorials for other sections of CSES. Feel free to point out mistakes. ## Dice Combin...
increasing array. So we can locate x position by binary search (std::lower_bound in C++ directly

Full text and comments »

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

176.
By fcspartakm, history, 11 years ago, translation, In English
Codeforces Round #350 (Div.2) Editorial ### [problem:670A] There are many ways to solve this problem. Let's talk about one of them. At first we need to write a function, which takes the start day of the year and calculate the number of days off in such year. To make it let's iterate on the days of the year and will check every day &mdash; is it day off or no. It is easy to show that if the first day of the year equals to the first day of the week (i.e. this day is Monday) in this year will be minimum possible number of the days off. If the first day of the year equals to the first day off of the week (i.e. this day is Saturday) in this year will be maximum possible number of the days off. ### [problem:670B] To solve this problem we need to brute how many identifiers will called robots in the order from left to right. Let's solve this problem in one indexing. Let the current robot will call $i$ identifiers. If $k - i > 0$ let's make $k = k - i$ and go to the next robot. Else we need to print $a[k]$, where $a$ is the arr...
If the objective function returned $true$ we need to move the left end of the binary search to the

Full text and comments »

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

177.
By paulzrm, history, 4 months ago, In English
Codeforces Round 1116 (Div. 1, Div. 2) Editorial [2256A-Three Numbers on the Blackboard](https://codeforces.me/contest/2256/problem/A) Idea: [user:paulzrm,2026-08-10] <spoiler summary="Hint 1"> Sort the numbers as $a\le b\le c$. </spoiler> <spoiler summary="Hint 2"> After at least one operation, consider the median. </spoiler> <spoiler summary="Hint 3"> Doing nothing gives $c-a$; replacing $c$ with $a+b$ gives $b$. </spoiler> <spoiler summary="Tutorial"> Suppose the current numbers are $x\le y\le z$. An operation keeps two numbers and replaces the third with their sum. Since all values are nonnegative, the new sum is no smaller than either retained number. Thus the new median is the larger retained number, which is at least the old median $y$. The median never decreases. After an operation that retains $u\le v$, the numbers are $u,v,u+v$. Their range is exactly $v$, also their median. Hence every nonempty sequence of operations ends with a range of at least the initial median $b$. With no opera...
reaches zero. Thus $T\ge n$. Also $a_i<2^{30}$, so $T=n+30$ is always sufficient.Binary-search $T

Full text and comments »

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

178.
By aryanc403, 2 years ago, In English
Codeforces Round 966 Discussion Stream (with Hints) [I'm currently live discussion the problems.](https://youtu.be/98gMxTz0nwY) I will add problemwise timestamp after the discussion stream. You can join in if something in this blog is unclear or there are more questions. [problem:2000A] <spoiler summary="Idea"> Split the string such that A is interger formed using first 2 char. Split the string such that B is interger formed using remaining. A should be equal to 10, $2 \le B$, and 3rd char must not be 0. One can use built in string to int functions. [stoll](https://en.cppreference.com/w/cpp/string/basic_string/stol) </spoiler> My submission &mdash; [submission:276111053] [problem:2000B] <spoiler summary="Idea"> Maintain set of seats occupied so far. Then x is valid, if set is empty, or x-1 or x+1 is present in set. </spoiler> My submission &mdash; [submission:276114559] [problem:2000C] <spoiler summary="Hint ...
[Binary search FTW](https://codeforces.me/blog/entry/92248)

Full text and comments »

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

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

Full text and comments »

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

180.
By Um_nik, history, 11 years ago, translation, In English
Codeforces Round #315 Editorial [problem:569A] Suppose we have downloaded $S$ seconds of the song and press the 'play' button. Let's find how many seconds will be downloaded when we will be forced to play the song once more. $\frac{x}{q} = \frac{x-S}{q-1}$. Hence $x=qS$. Solution: let's multiply $S$ by $q$ while $S<T$. The answer is the amount of operations. Complexity &mdash; $O(\log T)$ [problem:569B] Let's look at the problem from another side: how many numbers can we leave unchanged to get permutation? It is obvious: these numbers must be from $1$ to $n$ and they are must be pairwise distinct. This condition is necessary and sufficient. This problem can be solved with greedy algorithm. If me meet the number we have never met before and this number is between $1$ and $n$, we will leave this number unchanged. To implement this we can use array where we will mark used numbers. After that we will look over the array again and allocate numbers that weren't used. Complexity &mdash; $O(n)$. ...
can produce via two binary search query to array $b$.

Full text and comments »

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

181.
By physics0523, history, 3 years ago, In English
TheForces Round #27 Editorial [problem:104855A] <spoiler summary="Editorial"> First,it's not hard to come up with query `? 1`.Assume we have got $t$,the answer is either $2t$ or $2t-1$. Then we can query `? 2t`.It can be proven the answer of `? 2t` is always different from `? 2t-1`. Another approach:query `? 2` or `? 2m-1`.Although it doesn't work in some small cases,you can do another query to avoid conflict. </spoiler> <spoiler summary="Rate the problem"> Good problem! : Average problem : Bad problem... : </spoiler> [problem:104855B] <spoiler summary="Editorial"> Every time choosing adjacent cell to blue cell is optimal because it can stop the growth of blue cell in that particular direction, so obviously if $k>=4$ we can surround the blue cell so answer will be $nm-1$. For $k=1$ we will take the portion (up side, down side, left side, right side) of cells to initial blue cell containing maximum white cells, similarly for $k=...
Let's focus back to the binary search iteration. If $\max_{1 \leq i \leq n}(d_i) > s$, then we

Full text and comments »

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

182.
By Error_Yuan, 15 months ago, In English
Codeforces Round 1046 (Div. 1, Div. 2) Editorial <spoiler summary="Rate the Contest!"> - Amazing round: - Good round: - Average round: - Bad round: - Horrible round: </spoiler> [problem:2136A] Idea: [user:Alan_dong,2025-08-25] Preparation: [user:Register,2025-08-25] <spoiler summary="Hint"> If one team got a score of $x$ in the first half, what is the maximum score the other team could get? </spoiler> <spoiler summary="Solution"> We can consider the first half and the second half separately. The dream might come true if and only if the scores in both halves are possible. In the second half, the RiOI team scored $(c - a)$ goals, while the KDOI team scored $(d - b)$ goals. Suppose the RiOI team scored $x$ goals in some half. Denoting the score of the KDOI team as $y$, one can see that the maximal value of $y$ is $2\cdot x + 2$, under the goal order $\tt{\color{red}K\color{red}K\color{black}RK\color{red}K\color{black}R...RK\color{red}K\color...
binary search, or do some math work to get

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

185.
By Hamed_, history, 9 months ago, In English
Trick Bites: Daily CP Tricks & Video Upsolves Hello Codeforces! This is my very first blog post here, Lately I've been working on a series called **Trick Bites**. ### The Idea I wanted to share some special CP tricks. Some of them are uncommon but surprisingly easy (like Dinkelbach's algorithm), while others are just common tricks that everyone needs to know. I've started releasing a new problem every day to highlight a specific trick. With each problem, I upload a short, straight-to-the-point Arabic video explaining the trick and the optimal solution. ### Why this blog? I wanted to create this blog to be a permanent archive. I will be updating this exact post daily with the new problem links and video solutions. My hope is that by saving all this content in one organized place, it can become a useful resource for anyone looking to learn some tricks! --- ### The Trick Bites Archive (Updated Daily) [Group Link](https://codeforces.me/group/reRlOrZJrU/contests) *(I will update this list every day with the late...
* **Trick:** Parallel Binary Search

Full text and comments »

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

186.
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...
The paper explicitly stores the convex hull in a balanced binary search tree that supports split

Full text and comments »

187.
By Errichto, 11 years ago, In English
IndiaHacks Finals 2016 — Editorial Problems ABCG will be described better soon. problem A &mdash; watch out for test like "1 1 1 2 2 2 2 3 3 3". It shows that it's not enough to sort number and check three neighbouring elements. You must remove repetitions. The easier solution is to write 3 for-loops, without any sorting. Do you see how? problem B &mdash; you should generate all $6^n$ possible starting strings and for each of them check whether you will get "a" at the end. Remember that you should check two first letters, not last ones (there were many questions about it). [problem:653C] &mdash; Let's call an index $i$ bad if the given condition about $t_i$ and $t_{i+1}$ doesn't hold true. We are given a sequence that has at least one bad place and we should count ways to swap two elements to fix all bad places (and not create new bad places). The shortest (so, maybe easiest) solution doesn't use this fact but one can notice that for more than $4$ bad places the answer is $0$ because swapping $t_i$ and $t_j$ ...
the initial binary search, and the second part comes from doing k fattest path computations.

Full text and comments »

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

188.
By TheScrasse, history, 5 years ago, In English
[Tutorial] Problems about swapping adjacent elements Hello everyone,<br> problems about swapping adjacent elements are quite frequent in CP, but they can be tedious. In this tutorial we will see some easy ideas and use them to solve some problems of increasing difficulty. I tried to put a lot of examples to make the understanding easier.<br> The first part of the tutorial is quite basic, so feel free to skip it and jump to the problems if you already know the concepts. Target: rating $[1400, 2100]$ on CF<br> Prerequisites: greedy, Fenwick tree (or segment tree) Counting inversions ------------------ Let's start from a simple problem. _You are given a permutation $a$ of length $n$. In one move, you can swap two elements in adjacent positions. What's the minimum number of moves required to sort the array?_ #### Claim The result $k$ is equal to the number of inversions, i.e. the pairs $(i, j)$ ($1 \leq i < j \leq n$) such that $a_i > a_j$. #### Proof 1 Let $f(x)$ be the number of inversions after $x$ moves.<br> In one...
/advanced-data-structures/fenwick-binary -indexed-trees/practice-problems/algorithm/move-minimization

Full text and comments »

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

189.
By FetFot, 19 months ago, In English
Codeforces Round 1025 (Div. 2) Editorial Thank you for your participation! We hope you enjoyed the problems! We would love to hear your feedback! Please share your thoughts in the comments. <br> <spoiler summary="How did you find the contest?"> - Great: - Good: - Average: - Bad: - Trash: </spoiler> <spoiler summary="Which problem was your favorite?"> - A: - B: - C1: - C2: - C3: - D: - E: - F: </spoiler> <spoiler summary="Which problem did you find the least enjoyable?"> - A: - B: - C1: - C2: - C3: - D: - E: - F: </spoiler> <br> [problem:2109A] Idea by [user:MOUFLESS,2025-05-17], prepared by [user:MO...
perform a binary search on the value of $x$.

Full text and comments »

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

190.
By aryanc403, 2 years ago, In English
Codeforces Educational Round 168 Video Editorial (with Hints) [problem:1997A] <spoiler summary="Hint"> When you insert a new character, cost of only 2 elements changes. </spoiler> <spoiler summary="Video editorial"> <iframe width="853" height="480" src="https://www.youtube.com/embed/ek2PBI3NeSM?start=160" title="Codeforces Educational Round 168 Solution Discussion (ABCDE)" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </spoiler> [problem:1997B] <spoiler summary="Idea"> Type of cells that can split into 3 components has a fixed pattern. </spoiler> <spoiler summary="Video editorial"> <iframe width="853" height="480" src="https://www.youtube.com/embed/ek2PBI3NeSM?start=780" title="Codeforces Educational Round 168 Solution Discussion (ABCDE)" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpo...
[Binary search FTW](https://codeforces.me/blog/entry/92248)

Full text and comments »

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

191.
By wuhudsm, history, 16 months ago, In English
Codeforces Round 1040 (Div. 1, Div. 2) Editorial Thank you for participation and we hope you enjoy this round :) <spoiler summary="How did you find the contest?"> - Great: - Good: - Average: - Bad: - Trash: </spoiler> <spoiler summary="Which problem is your most favourite?"> - D2A: - D2B: - D1A: - D1B: - D1C1: - D1C2: - D1C3: - D1D: - D1E: - D1F1: - D1F2: </spoiler> <spoiler summary="Which problem you hate the most?"> - D2A: - D2B: - D1A: - D1B: - D1C1: - D1C2: - D1C3: [likes:favorite,2039E3_...
Try to Perform binary search to find a $\texttt{'('}$ and a $\texttt

Full text and comments »

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

192.
By riadwaw, 11 years ago, translation, In English
AIM Tech Round Tutorial [problem:624A] Width of free space is decreasing by $v_1 + v_2$ per second. It means that it'll decrease from $L$ to $d$ in $t = \frac{L - d}{v_1 + v_2}$ seconds. The moment when width gets a value of $d$ is the last when Luke is alive so $t$ is the answer. [problem:624B] Sort array in descending order. Iterate over all letters, First letter is added $c_1 = a_1$ times, each other letter is added $c_i = min(a_i, c_{i - 1})$. Don't forget that if some letter is not added at all, then all next letters are not added too. [problem:623A] Note that all vertices "b" are connected with all other vertices in the graph. Find all such vertices and mark them as "b". Now we need to find any unlabeled vertex $V$, mark it with "a" character. Unlabeled vertices connected with $V$ should be also labeled as "a". All other vertices we can label as "c" Finally we need to check graph validity. Check that all vertices "a" are only connected with each other and "b" vertices. After that we...
We will use a binary search. Now we will need to check if it's possible to project point in a such

Full text and comments »

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

193.
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...
arithmetic operations used. Firstly, a binary search is used, which is $\log 32 = 5$ operations. Then, we

Full text and comments »

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

194.
By meooow, 8 years ago, In English
[Tutorial] Convex Hull Trick — Geometry being useful ### The problem Let us consider the problem where we need to quickly calculate the following over some set $S$ of $j$ for some value $x$. $$\max_{j \in S} \{m_j \cdot x + c_j\}$$ Additionally, insertion of new $j$ into $S$ must also be efficient. This will most likely be encountered with DP problems. For example, the recent problem [problem:1083E] from Round #526 has the following DP formulation after sorting the rectangles by $x$. $$f(i) = x_i \cdot y_i - a_i + \max_{1 \le j < i}\{-x_j \cdot y_i + f(j)\}$$ The problem requires quick calculation of the above define maximum for each index $i$. How can this be done? ### The idea Notice the special form of $m_j \cdot x + c_j$. This is identical to the equation of a straight line with slope $m_j$ and Y-intercept $c_j$. So the problem is equivalent to being given a set of lines and asked for the maximum $y$ value any of those lines can give at a particular $x$. If you draw a bunch of straight lines on a plane, you'll...
particular $x$ we can use binary search to find the line where the value will be maximum.

Full text and comments »

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

195.
By rama_pang, 4 years ago, In English
NUS CS3233 Final Team Contest 2023 Editorial The contest announcement and invitation link is [here](https://codeforces.me/blog/entry/114880). The contest link is [here](https://codeforces.me/gym/104296). ## [A. Artistic Masterpiece](https://codeforces.me/gym/104296/problem/A) <spoiler summary="Tutorial"> Since $(x,y)$ is covered by the brush iff $(x - x_c)^2 + (y - y_c)^4 \leq r$, that means we can decompose the area of the brush into $O(\sqrt[4]{r})$ independent 1-dimensional intervals (a contiguous block with the same $y$-coordinate). For each center $(x_c,y_c)$ traversed by the brush, add the 1-dimensional intervals for $y \in [y_c - \sqrt[4]{r}, y_c + \sqrt[4]{r}]$. After adding these intervals, the problem is now reduced to computing the area union of 1-dimensional intervals for each separate $y$-coordinate. </spoiler> ## [B. Broken Calculator](https://codeforces.me/gym/104296/problem/B) <spoiler summary="Tutorial"> First, we consider the minimum cost to get from an integer $X$ to another integer $Y$ us...
When we binary search for both $v_{\min}$ and $v_{\max}$, we initially set our valid range of

Full text and comments »

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

196.
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...
PS. You can use binary search tree to solve it in $O( m\log n )$ time.

Full text and comments »

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

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

Full text and comments »

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

198.
By aryanc403, 2 years ago, In English
Codeforces Round 963 Video Editorial (with Hints) [problem:1993A] <spoiler summary="Video editorial"> <iframe width="853" height="480" src="https://www.youtube.com/embed/TO8PszXGEz8?start=210" title="Codeforces Round 963 Solution Discussion | ABCDF1E" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </spoiler> [problem:1993B] <spoiler summary="Hint 1"> Sum of odd and even is odd. So we will have to remove even nos if array does not contain same parity in starting. </spoiler> <spoiler summary="Hint 2"> Most of the times we should do this type of operation - Pick maximum odd no and minimum even no and do the operation. </spoiler> <spoiler summary="Hint 3"> If you cannot do the above operation pick maximum odd no and maximum even no and do the operation. Now, you can always do the previous mentioned operation...
[Binary search FTW](https://codeforces.me/blog/entry/92248)

Full text and comments »

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

199.
By PrinceOfPersia, 12 years ago, In English
Codeforces Round #305 Editorial ### [problem:548A] Consider characters of this string are number 0-based from left to right. If $|s|$ is not a multiply of $k$, then answer is "NO". Otherwise, let $len = \frac{|s|}{k}$. Then answer is "Yes" if and only if for each $i$ that $0 \leq i < |s|$, $s_i = s_{(i/len) * len + len - 1 - (i \% len)}$ where $a\%b$ is the remainder of dividing $a$ by $b$. ![ ](http://viber.tsymbal.su/data/stickers/02229.png) Time complexity: $\mathcal O(|s|)$. [C++ Code](http://ideone.com/HpYQHZ) by [user:PrinceOfPersia,2015-05-24] [Python Code](http://ideone.com/A6yhex) by [user:Haghani,2015-05-24] [Python Code](http://ideone.com/PHiL7p) by [user:Zlobober,2015-05-24] ### [problem:548B] Consider this problem: We have a binary sequence $s$ and want to find the maximum number of consecutive 1s in it. How to solve this? Easily: ~~~~~ ans = 0 cur = 0 for i = 1 to n: if s[i] == 0 then cur = 0 else cur = cur + 1 ans = max(ans, cur)...
binary search and sparse table on sequence $lc$) such that $a \leq i \leq b$ and $min(lc_a, lc_{a+1

Full text and comments »

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