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 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 - [...
don't know (imagine how many things I haven't even heard of): - Li-Chao Segment Tree - Segment, - Li-Chao Segment Tree - Segment Tree Beats - RMQ in $O(n)$/$O(1)$ - Any self-balancing

Full text and comments »

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

2.
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...
/blog/entry/83170) - [[Video Tutorial] Majority Element Range Queries (Segment Tree)](https, Tree)](https://codeforces.me/blog/entry/89880) - [Do we actually need lazy propagation onsegment

Full text and comments »

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

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

Full text and comments »

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

4.
By Um_nik, history, 4 years ago, In English
Pro Tips - get them while they are free More tips to use while studying under my tutoring [here](https://um-nik.notion.site/Pro-Tips-8b923b0dc7c94770824bdf4184afc43c). ## Stop caring about the rating Unless there are prizes involved, your position in the standings makes no difference. I can feel awful after winning a contest if I know that I could solve one more problem. Or I can feel OK losing a bunch of rating points knowing that I solved everything I could.  Because rating is just a number. It is highly volatile and it depends on other people, not only on your skill. But solving problems is totally up to you. And you should evaluate yourself not based on some random metric, but on your honest feeling whether you performed up to your expectations. Your sense of self should be under your control, don't get hung up on some imaginary value, you cannot reduce your progress to a single number. ## Don't use more than one account Rating is just a number. Do not be afraid to lose your colour. You’ll get it back in no t...
anything to bring the whole toolbox to the problem. Do not write a segment tree if you don’t know, Do not write a segment tree if you don’t know how to calculate the answer for one query with $n

Full text and comments »

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

5.
By pashka, 6 years ago, In English
EDU: Segment Tree, part 1 Hello everyone! I just published a [new lesson](https://codeforces.me/edu/course/2/lesson/4) in the EDU section. This is the first part of the lesson about the segment tree. <img src="/predownloaded/ad/f8/adf89a39c4a3c646e9b047bc1e24e894a01034d4.png"/> In this lesson, we will learn how to build a simple segment tree (without mass modifications), and how to perform basic operations on it. We will also discuss some tasks that can be solved using the segment tree. <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: Segment Tree, part 1, . This is the first part of the lesson about the segment tree., In this lesson, we will learn how to build a simple segment tree (without mass modifications), and

Full text and comments »

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

6.
By jiry_2, history, 9 years ago, In English
A simple introduction to "Segment tree beats" Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this comment](http://codeforces.me/blog/entry/54750?#comment-387957). Sorry for the long delay, as a sophomore in Peking University, I've just finished a tired semester and a painful final exam. And now I finally have enough time to do a simple introduction to this interesting algorithm. It may be a huge project for me since my English is not good. I think I will finish this blog in several steps and I will try to finish it as soon as possible :) In China, all of the 15 candidates for the Chinese National Team are asked to write a simple research report about algorithms in informatics Olympiad, and the score will be counted in the final selection. There are many interesting ideas and algorithms in these reports. And I find that some of them are quite new for competitors in CF although they are well known in China from the final standings of some recent contests. For example, In the last co...
A simple introduction to "Segment tree beats", Task 2 is $O(n \log n)$. And this proof will show the relationship between " segment tree beats" and, Task 6 can be regarded as two layer nested “segment tree beats”. It's time complexity can be proved, choose is a little strange: let $d(t)$ ( $t$ is a tag ) be the depth of $t$ in thesegment tree and, is to use balanced tree such as splay/treap to maintain the continuous segments with the same $A_i, nodes and extra nodes. Ordinary nodes are those nodes which an ordinary segment tree also visit in an, this algorithm with the original segment tree: We will visit more nodes when `second_value[node, , and the name “Segment tree beats” is given by [user:C_SUNSHINE,2018-01-24] which is from a famous, And now, we can easily describe the main idea of "segment tree beats". For each node, we maintain, But if we use segment tree, we can get a much simpler solution: let `break_condition` be `l > rr, Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this, Since there are at most $n$ tags in the segment tree, so the initial value of $\Phi(x)$ is $O(n, That's the main idea of the first part of "segment tree beats". It is very simple, right? And it, The left picture shows the maximum value of each node in a segment tree of array $[1,2,4,3]$. And, The main idea is to transform max value into tags. Let the tag of each node in segment tree be the, Thus, we can just use tags and ordinary segment tree to solve this problem in $O(n \log n, To make the description clearer, I think it’s better to introduce an extended segment tree template., To solve this task, ordinary segment tree is enough. But It's not easy to deal with the

Full text and comments »

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

7.
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...
The problem is, that even the simplest Data Structure (say, Segment Tree), makes the first part

Full text and comments »

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

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

Full text and comments »

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

9.
By Tony2_CF, history, 11 months ago, In English
The Time Complexity Lower Bound for Segment Tree Beats is log^2 Original Post: https://jiry-2.blog.uoj.ac/blog/1404 The following content is translated by Gemini 2.5 Pro. ## Part 1: Introduction to the Hacking Method ### How to Map the Hack Sequence to a Segment Tree First, we are given a Hack sequence of length $len$. After $O(1)$ range addition operations and $\Theta(\log len)$ global $\text{chkmax}$ operations, this sequence becomes a cyclic shift (rotation) of the original sequence. Since a cyclic shift does not affect our range addition and global $\text{chkmax}$ operations (we can simply shift the indices for the range addition accordingly), we can consider the sequence as unchanged. If we have such a sequence, let $len=n^{\frac{1}{3}}$, and place such a sequence at intervals of $n^{\frac{2}{3}}$. Each sequence corresponds exactly to a segment tree interval. A subtree of size $n^{\frac{2}{3}}$ contains exactly one such segment tree interval. For the Hack sequence, the range addition operations are performed one by one on eac...
The Time Complexity Lower Bound for Segment Tree Beats is log^2, a circle-square tree, and I could immediately see the hope for a hack. It was around these few days, aforementioned "shackle" nodes. At this point, a model emerged: the tree has some shackle nodes and original, can use these size relationships to build a Cartesian tree (or forest). Why a forest? Because range, causes the Cartesian tree to split, its two positions' values are confirmed to be equal by a $\text, moment **that makes their Cartesian tree the same**, which is when $(p_1,p_2)$ belong to the same, ### How to Map the Hack Sequence to a Segment Tree, , accessing at least $\Omega(n^{\frac{1}{3}}\log n)$ segment tree nodes each time. Since the $\text{chkmax, A miracle occurs: after the deletion, the left side of the tree forms the shape of a new $(n-1)_g, About a day or two later, I thought about the idea of building a Cartesian tree forest for the, After getting this model, I was very confident that Segment Beats could be hacked. The next thing I, Another day or two passed, and I came up with the complete Cartesian tree. Now the change in the, Any node in the tree clearly corresponds to an x-interval $[l,r]$., First, we need to understand the line segments as an $f$-type node in a tree. Each $f_n$ creates an, Here, the triplet $(x_1,x_2,y)$ represents a line segment from $(x_1,y)\sim (x_2,y)$. The operation, Next comes the most crucial part: splitting the tree into two parts and reassembling it. We split, Note that here $n_f,n_g$ is just a classification, representing a type of node. Atree can have, Observation reveals that disintegration pairs form a tree-like relationship. Step one is actually, Segment Tree First, we are given a Hack sequence of length $len$. After $O(1)$ range addition, The Segment tree beats algorithm was proposed by jry in 2016. I can't seem to find the ppt I saw, The left part of the tree is easy to understand. Since $(n-1)_f,(n-2)_f,...$, are left, these nodes, This is the structure of $3_f$. Each line segment represents the root of an $f$-type node. The $g, This process of alternating iteration generates a tree. Assuming the root of the tree is $n_f, When the tree is cut, we find that the left side is completely a $2_g$ structure. Although $(0,8,13, Why are the manually added line segments on the right side of the tree valid? In fact, when $n_f, ^{\frac{2}{3}}$. Each sequence corresponds exactly to a segment tree interval. A subtree of size $n

Full text and comments »

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

10.
By maomao90, 3 years ago, In English
Editorial for Hello 2024 ### [problem:1919a] Author: [user:maomao90,2024-01-02] <spoiler summary="Hint 1"> When does the game end? </spoiler> <spoiler summary="Solution"> Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choices will still be valid. The only way that the game ends is when both players have $0$ coins. Since each operation decreases the total amount of coins by exactly $1$, the only way for Alice to win the game is if $a + b$ is odd. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if ((a + b) % 2 == 0) { cout << "Bob\n"; } else { cout << "Alice\n"; } } ...
Code ReLU segment tree. A similar method can be used to solve the, ReLU is a common activation function used in neural, Speed up finding the minimum cut using a segment tree. , Speed up the transition by storing the state in a segment tree, )$ after composing the functions that fall in the range of the segment tree node. For the merge function, To handle updates, we can use a segment tree. Each node of the segment tree stores the minimum, To speed this up, we use a segment tree to store the value of $dp_{i - 1, p}$ at position $p$. To, \limits_{i = k}^n v_i$. We can use a segment tree where position $p$ of the segment tree stores

Full text and comments »

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

11.
By Errichto, 6 years ago, In English
Matrix Exponentiation tutorial + training contest tl;dr &mdash; video tutorial https://www.youtube.com/watch?v=eMXNWcbw75E and codeforces GYM training https://codeforces.me/gym/102644 (register by finding this contest in GYM instead of using the link directly) video editorial: [part 1 (ABCDEF)](https://www.youtube.com/watch?v=kQuCOFzWoa0) and [part 2 (GHI)](https://www.youtube.com/watch?v=RA_SpxP2t54) codes to all 9 problems: https://github.com/Errichto/youtube/tree/master/matrix-exponentiation Prerequisites: binary exponentiation and iterative dp (you don't need to know matrices) The youtube tutorial ([link](https://www.youtube.com/watch?v=eMXNWcbw75E)) focuses on intuition and graph-like visualization . Or, if you prefer, below is a shorter (less detailed) text tutorial instead. You can practice by solving a set of 9 educational problems in GYM https://codeforces.me/gym/102644. ABCD are easy, EF medium, GHI are hard. If you are stuck, see hints below or watch the full solution analysis &mdash; [part 1 (ABCDEF)](https:...
Segment tree!

Full text and comments »

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

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

Full text and comments »

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

13.
By YouKn0wWho, 3 years ago, In English
A Huge Update on The Ultimate Topic List Hi, around 3 years ago I compiled most of the Competitive Programming topics in one place [here](https://codeforces.me/blog/entry/95106) with relevant resources, templates, and problems. It got great responses, it now has 4000+ upvotes and the blog website has been visited 200k+ times! But it contained links to only 1-2 resources and problems per topic and it didn’t contain basic topics for beginners. Also, there was no way of tracking your progress. This time I decided to improve it, by a lot. I took this project one month ago and it took me on average 6h-10h per day for the last one month to complete this project (also I was doing a full-time job). I hope it was worth it! The new version is not just a blog, it is a full-fledged website with multiple features (I have hosted it on one of my existing websites): ![topic_list](/predownloaded/7e/20/7e2045c57574d37e170ea3eb1fdc5516ff68bc0e.png) - **Topics:** The website contains around 500 topics and tricks. Not all topics are ...
have divided a parent topic into multiple subtopics. For example, under Segment Tree, you will find, parent topic into multiple subtopics. For example, under Segment Tree, you will find NormalSegment

Full text and comments »

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

14.
By rama_pang, history, 6 years ago, In English
[Tutorial] Li Chao Tree Extended Hello everyone! I discovered a new (?) trick on how to apply lazy propagation on the Li Chao Tree and decided to write a blog about it. I've personally never seen it before (outside of myself), nor have I seen a problem that needs the Extended Li Chao Tree specifically, but it *can* overkill some problems. Of course, I might not be looking hard enough... You can learn about the basics of Li Chao Tree from [cp-algorithms](https://cp-algorithms.com/geometry/convex_hull_trick.html) or [this simple blog](https://robert1003.github.io/2020/02/06/li-chao-segment-tree.html). The Extended Li Chao Tree can do the following problems (and other variations): ## Problem 1 There is an array $A$ of size $N$. There are $Q$ online operations: - Range Line Insertion. Given $l$, $r$, $a$, $b$, do $A_i = \max(A_i, a \cdot i + b)$, $\forall i \in [l, r]$ in $O(\log^2 N)$ - Range Line Addition. Given $l$, $r$, $a$, $b$, do $A_i += a \cdot i + b$, $\forall i \in [l, r]$ in $O(\log^2 N)$. - Po...
[Tutorial] Li Chao Tree Extended, interval $[2, N - 1]$. What happens in a usual segment tree is that we directly recurse to $[1, M, maintain the values of $A$. To check for operation $3$, we need to maintain a segment tree of the array, on segment $[L, R]$. Now we only need to calculate $opt_{L, L}, opt_{L, L + 1}, \dots, opt_{L, R, range $[l, r]$. Just as in the usual segment tree, we first split the interval $[l, r]$ into $O(\log N, reachable in $\leq t$ time form a segment $[l, r]$. Thus, after we reached all nodes $\in [l, r]$, the next, $. That way, we can simply maximize $b$ with a classic segment tree which takes only $O(\log N)$ time per, **Solution.** First, we build a Cartesian Tree over the array $H$ (for all comparisons, we use a, . We can do a range sum addition on the segment tree of $B$, then easily update $B_L$ and $B_{R + 1, At first glance, we will need an Extended Li Chao Tree, but you don't actually need to. Since we do, You can learn about the basics of Li Chao Tree from [cp-algorithms](https://cp-algorithms.com, segment tree, we first split the interval $[l, r]$ into $O(\log N)$ segments. After that, we can do the

Full text and comments »

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

15.
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...
There are many more topics like that: segment trees, square root decomposition, MSTs, etc.

Full text and comments »

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

16.
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...
If you want to build a segment tree where each node contains a sorted list of values from the

Full text and comments »

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

17.
By peltorator, 6 years ago, translation, In English
Video: Segment Tree Beats Hi! In the new video, we’re going to talk about the amazing data structure called Segment Tree Beats, which allows us to support a huge number of operations that a regular segment tree can’t handle. We will learn how to take numbers on a segment modulo some number, apply the min= and max= operations, add += to them, and also find GCD on a segment with these operations. And all the proofs are gonna be super simple, so don’t be scared, it will be easy! In the next video, we will cover even more awesome queries, so stay tuned. [Link to the video](https://youtu.be/NwkO73jGSPA) You can check out my previous videos on [my channel](https://www.youtube.com/c/peltorator) Contest on Segment Tree Beats (and others) is [here](https://codeforces.me/group/1rv4rhCsHp/contests) Also, there's the Russian version of this video if you speak Russian [here](https://youtu.be/58csqxAD8vM) ![ ](/predownloaded/47/25/47253e8a4d9533f695452d8c4b52b0332ca5e4bb.png) [Original article in En...
Video: Segment Tree Beats, Видео: Segment Tree Beats, Contest on Segment Tree Beats (and others) is [here](https://codeforces.me/group/1rv4rhCsHp, Hi! In the new video, we’re going to talk about the amazing data structure calledSegment Tree, In the new video, we’re going to talk about the amazing data structure called Segment Tree Beats, [%= on a segment, = in a point, sum on a segment](https://pastebin.com/wabDfjKi), [Everything from the previous implementation but also GCD on a segment ](https://pastebin.com, [Everything from the previous realisation but also GCD on a segment ](https://pastebin.com/jDMC5R2T), [Ji Driver Segment Tree (min= on a segment, sum on a segment )](https://pastebin.com/bEEQsDr7), [Ji Driver Segment Tree (min= на отрезке, сумма на отрезке)](https://pastebin.com/bEEQsDr7), [min= on a segment, max= on a segment, += on a segment, = on a segment, sum on a segment, minimum, [Контест](https://codeforces.me/group/1rv4rhCsHp/contests) с задчами на Segment Tree Beats.

Full text and comments »

  • Vote: I like it
  • +374
  • 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...
/14854) on all the words from the input and use some segment/Fenwick tree to make the new strings

Full text and comments »

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

19.
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...
Tutorial on Permutation Tree (析合树), are interested in using segment tree range minimum queries., elements in the stack which are smaller than it and update their maximum values using asegment tree, segment tree range add update. This amortizes to $O(n)$ as each value is pushed into the stack once.

Full text and comments »

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

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

Full text and comments »

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

21.
By purplesyringa, history, 6 years ago, In English
crazySegmentTree: Segment Tree implementation with 5x faster queries than bottom-up tree Hello, Codeforces! A few days ago [user:MohammadParsaElahimanesh,2021-04-06] posted a blog titled [Can we find each Required node in segment tree in O(1)?](https://codeforces.me/blog/entry/89377) Apparently what they meant was to find each node in $\mathcal{O}(ans)$, according to [ecnerwala's explanation](https://codeforces.me/blog/entry/89377?#comment-777885). But I was too dumb to realize that and accidentally invented a parallel node resolution method instead, which speeds up segment tree a lot. A benchmark for you first, with 30 million RMQ on a 32-bit integer array of 17 million elements. It was run in custom test on Codeforces on Apr 6, 2021. - **Classic implementation from cp-algorithms:** 7.765 seconds, or 260 ns per query - **Optimized classic implementation:** (which I was taught) 4.452 seconds, or 150 ns per query (75% faster than classic) - **Bottom-up implementation:** 1.914 seconds, or 64 ns per query (133% faster than optimized) - **Novel parallel implement...
crazySegmentTree: Segment Tree implementation with 5x faster queries than bottom-uptree, Required node in segment tree in O(1)?](https://codeforces.me/blog/entry/89377) Apparently what they, obfuscate your code so that no one would understand you used a segment tree so that no one hacks you *(just, titled [Can we find each Required node in segment tree in O(1)?](https://codeforces.me/blog/entry/89377, ![Segment tree ](https://www.researchgate.net/profile/Nicolae-Tapus/publication/45924823/figure/fig1, Finally, these lines in `main()` are something you should *not* touch. They build thesegment tree, Implement point update queries in a similar way. This should be very fast for segment-tree-on-sum, In a segment tree, a range query is decomposed into 'red' nodes. Classic segment tree, In bottom-up segment tree, we find the node corresponding to the leftmost element of the query, i.e, In parallel segment tree, we jump to i-th parent of $N+l$ and $N+r$ for all $i$ *simultaneously, The following line configures the count of elements in segment tree. It must be a power of two, so, The parallel implementation is an optimization of bottom-up tree. Probably you all know how bottom, This is the benchmark, along with the four segment tree implementations I checked and a prefix sum, Unfortunately BIT/fenwick tree cannot be optimized this way, it turns out 1.5x slower., segment tree in [submission:112168469] which runs in 155 ms. The bottom-up implementation runs in 93, static_assert((N & (N - 1)) == 0, "Segment tree size must be a power of two"); static_assert, static_assert(sizeof(T) == 4, "Segment tree elements must be 32-bit");

Full text and comments »

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

22.
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...
Algorithm Gym :: Everything About Segment Trees, $a_i > k$, then we can easily answer the query $(i,j,k)$ in $O(log(n))$ using a simplesegment tree, of segment trees ., of the node in new version of segment tree s[ID] = s[id] + 1; if(r - l < 2) return ID; int, #### $2D$ Segment trees, #### Segment trees with DSU, #### Segment trees with Fenwick, #### Segment trees with tries, Another example : [Component Tree](/gym/100513/problem/C), As I said in the last lecture, we have an array $root$ and the root of the empty segment tree, $ir, As you know, segment tree is for problems with array. So, obviously we should convert the rooted, Classic Segment Tree --------------------, Classic, is the way I call it. This type of segment tree, is the most simple and common type. In, For this problem, we use a segment tree where each node has a `multiset`, node $i$ with interval, For this problem, we use a segment tree where each node has a `vector`, node $i$ with interval $[l, In the last lecture, I talked about this type of segment trees, now I just want to solve an, In this type of segment tree, for each node we have a Fenwick (we may also have some other, In this type of segment tree, for each node we have a `set` or `multiset` or `hash_map` ([here, In this type of segment tree, for each node we have a disjoint set (we may also have some other, In this type of segment tree, for each node we have a trie (we may also have some other variables, In this type of segment tree, for each node we have a vector (we may also have some other variables, In this type of segment tree, for each node we have another segment tree (we may also have some, Persistent Segment Trees ------------------------, Segment tree on a rooted tree -----------------------------, Segment tree types :, Segment tree with other data structures in each node ----------------------------------------------------, Segment tree with sets ----------------------, Segment tree with vectors -------------------------, Segment trees., So for each node of segment tree, we will have two variables $hkx = \sum x + h \times k$ and $sk, We have an array $b_1,b_2,...,b_n$ (initially 0) and a persistent segment tree on it., et An update function for when we want to st `b[p[po]] = 0` to update the segment tree:, ~~~~~ typedef pairpii; typedef pair node; node segment(int x,int y,int id

Full text and comments »

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

23.
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$ ...
of the node in new version of segment tree if(r - l < 2){ s[ID] = (a[p] += v); return ID, #### Persistent segment tree, )$ ) after performing each query and a number $ir = 0$ which is its index in the initialsegment tree, Each update query, changes the value of $O(log(n))$ nodes in the segment tree, so you should keep, First of all we need to build the segment tree, for each node we keep the sum of its interval, for, First of all, you need to build the initial segment tree :, If the size of the root's interval is $n$, segment tree could have up to $4n$ nodes., In each of these chains, we can contain a container or another data structure likesegment tree or, Segment tree ------------, Segment tree does that for you. Segment tree is a tree that each of it's nodes belongs to an, Segment tree is the most useful data structure and every problem solvable by Fenwick is also, The most useful data structure for this propose is segment tree, I will explain persistentsegment, Update function : (its return value, is the index of the interval in the new version ofsegment

Full text and comments »

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

24.
By Al.Cash, 12 years ago, In English
Efficient and easy segment trees This is my first attempt at writing something useful, so your suggestions are welcome. Most participants of programming contests are familiar with segment trees to some degree, especially having read this articles http://codeforces.me/blog/entry/15890, http://e-maxx.ru/algo/segment_tree (Russian only). If you're not &mdash; don't go there yet. I advise to read them after this article for the sake of examples, and to compare implementations and choose the one you like more (will be kinda obvious). Segment tree with single element modifications ================== Let's start with a brief explanation of segment trees. They are used when we have an array, perform some changes and queries on continuous segments. In the first example we'll consider 2 operations: 1. modify one element in the array; 2. find the sum of elements on some segment. [cut] . ### Perfect binary tree I like to visualize a segment tree in the following way: [image link](http://i.imgur.com/GGBmcEP....
Efficient and easy segment trees, bottom row we have our array (0-indexed), the leaves of the tree. For now suppose it's length is a power, from node 5 down the tree. Note that our modifications could affect `t[i]` values up thetree as well, interested in some kind of explanation, here's how the tree for $n = 13$ looks like: [image link](http, introduces earlier that processes the whole tree in $O(n)$, and one from the last example that, some interval in the tree, we can write code like this:, the tree, which is $O(log(n))$. We only need to update values in the parents of given node. So we, values directly into the tree where they belong., ### Perfect binary tree, $h$ is a height of the tree, the highest significant bit in $n$. `d[i]` is a delayed operation to, 1. Segment tree uses exactly $2*n$ memory, not $4*n$ like some other implementations offer. 2, 1. modify one element in the array; 2. find the sum of elements on some segment . [cut] ., 2. Before doing any queries we need to build the tree, which is quite straightforward and takes $O, 3. _push_ propagates changes from all the parents of a given node down the tree starting from the, For now we talked only about an array with size equal to some power of 2, so the binarytree was, I like to visualize a segment tree in the following way: [image link](http://i.imgur.com, It's not actually a single tree any more, but a set of perfect binary trees: with root $2$ and, Let's start with a brief explanation of segment trees. They are used when we have an array, perform, Most participants of programming contests are familiar with segment trees to some degree, One could notice that we do 3 passed in _modify_ over almost the same nodes: 1 down thetree in, Previously we could say that `t[i]` is a value corresponding to it's segment. Now it's not entirely, Segment tree with single element modifications ==================, ` in order to calculate parents properly. Since we process our tree level by level, is't easy to, void build() { // build the tree for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] + t[i<<1|1]; }

Full text and comments »

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

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

Full text and comments »

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

26.
By Phantasmagorias, history, 5 years ago, In English
Codeforces Round #745 Editorial I'm very sorry about all the inconvenience, and I would like to bear the blame. Much thanks to those who help me prepare this round. It's not their fault. And much thanks to your participation. [problem:1581A] ------------------ idea: [user:interlude,2021-09-30] preparation: [user:CQXYM,2021-09-30] tutorial: [user:CQXYM,2021-09-30] Assume a permutation $p$, and $\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\forall 1 \leqslant i \leqslant 2n, q_i=2n-p_i$. We can know that $\forall 2 \leqslant i \leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ should be counted. All in all, the half of all the permutaions would be counted in the answer. Thus, the answer is $\frac{1}{2}(2n)!$. The time complexity is $O(\sum n)$. If you precalulate the factors, then the complexity will be $O(t+n)$. ----- <spoiler summary="solution"> ~~~~~ #include<stdio.h> int f[100001]; int m...
times, but we will find that it won't change $val$ at all. So we can do them at a time usingsegment, Using std::set and segment tree, all of these operations could be done in $O(logn)$ at a time. Thus

Full text and comments »

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

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

Full text and comments »

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

28.
By pajenegod, 3 years ago, In English
The Ultimate Reroot Template Hi Codeforces! Have you ever had this issue before? ![ ](https://cdn.discordapp.com/attachments/572613134020247562/1191774699110285392/image.png?ex=65a6a9ae&is=659434ae&hm=aeb62b0d97a84c226709b88bc3db7647f4509eef7c3a757a798ffe37e7e91c2b&) If yes, then you have come to the right place! This is a blog about my super easy to use template for (reroot) DP on trees. I really believe that this template is kind of revolutionary for solving reroot DP problems. I've implemented it both in [Python](https://codeforces.me/contest/1324/submission/240129139) and in [C++](https://codeforces.me/contest/1324/submission/240131453) (the template supports `Python2`, `Python3` and `>= C++14`). Using this template, you will be able to easily solve > 2000 rated reroot problems in a couple of minutes, with a couple of lines of code. A big thanks goes out to everyone that has helped me by giving feedback on blog and/or discussing reroot with me, [user:nor,2024-01-03], [user:meooow,2024-01-03], [u...
Each node in the exclusive, `exclusive` run in $O(\sum \text{deg} \log{(\text{deg})})$ time is to create something similar to asegment, exclusive(A, zero, combine, node): n = len(A) exclusiveA = [zero] * n # Exclusivesegment, # Build exclusive segment tree for bit in range(n.bit_length())[::-1]: for i in range, ## 5. The exclusive segment tree, (A, zero, combine, node): n = len(A) exclusiveA = [zero] * n # Exclusive segment tree, Suppose you have a segment tree where each node in the segment tree accumulates all of the values, The exclusive segment tree is naturally built from top to bottom, taking $O(n \log n)$ time. Here

Full text and comments »

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

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

Full text and comments »

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

30.
By Syloviaely, history, 8 years ago, In English
A simple introduction to "Segment tree beats" **This blog is just a back up of [http://codeforces.me/blog/entry/57319](http://codeforces.me/blog/entry/57319) to prevent this tutorial from discarding after [user:jiry_2,2018-10-17] is banned.** Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this comment](http://codeforces.me/blog/entry/54750?#comment-387957). Sorry for the long delay, as a sophomore in Peking University, I've just finished a tired semester and a painful final exam. And now I finally have enough time to do a simple introduction to this interesting algorithm. It may be a huge project for me since my English is not good. I think I will finish this blog in several steps and I will try to finish it as soon as possible :) In China, all of the 15 candidates for the Chinese National Team are asked to write a simple research report about algorithms in informatics Olympiad, and the score will be counted in the final selection. There are many interesting ideas and algorit...
A simple introduction to "Segment tree beats", Task 2 is $O(n \log n)$. And this proof will show the relationship between " segment tree beats" and, Task 6 can be regarded as two layer nested “segment tree beats”. It's time complexity can be proved, choose is a little strange: let $d(t)$ ( $t$ is a tag ) be the depth of $t$ in thesegment tree and, is to use balanced tree such as splay/treap to maintain the continuous segments with the same $A_i, nodes and extra nodes. Ordinary nodes are those nodes which an ordinary segment tree also visit in an, this algorithm with the original segment tree: We will visit more nodes when `second_value[node, , and the name “Segment tree beats” is given by [user:C_SUNSHINE,2018-01-24] which is from a famous, .** Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this, And now, we can easily describe the main idea of "segment tree beats". For each node, we maintain, But if we use segment tree, we can get a much simpler solution: let `break_condition` be `l > rr, Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this, Since there are at most $n$ tags in the segment tree, so the initial value of $\Phi(x)$ is $O(n, That's the main idea of the first part of "segment tree beats". It is very simple, right? And it, The left picture shows the maximum value of each node in a segment tree of array $[1,2,4,3]$. And, The main idea is to transform max value into tags. Let the tag of each node in segment tree be the, Thus, we can just use tags and ordinary segment tree to solve this problem in $O(n \log n, To make the description clearer, I think it’s better to introduce an extended segment tree template., To solve this task, ordinary segment tree is enough. But It's not easy to deal with the

Full text and comments »

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

31.
By galen_colin, 6 years ago, In English
Hybrid Tutorial #-1: Heavy-Light Decomposition **[Here](https://www.youtube.com/watch?v=_G_LMuLWMaI&list=PLDjGkpToBsYDx4GWu2u87sTqt6ICELz-T) is a playlist of all hybrid tutorials I've done.** # "Intro" _Timestamp: [00:00](https://youtu.be/_G_LMuLWMaI)_ Hi! Definitely not inspired by [this comment](https://codeforces.me/blog/entry/81086?#comment-675431), I've decided to try something that seems relatively novel &mdash; combining a blog and video tutorial into one, in a "hybrid" fashion. Both should be usable independently, but they will have the same "flow" and structure so you can reference both for concepts that are harder to grasp, and the two will supplement each other. The goal of these is to be **complete** &mdash; beneficial for both video and blog lovers, as well as full of enough information that anyone without much of an idea of what the concept is should be able to fully understand. There will be code as well, however, I very highly recommend not looking at it, but rather working out the implementation for yours...
classic segment tree problem with two types of queries:, input vertex. `seq_query_header` is the query function for my segment tree., sequences of numbers, so they can be easily queried with the segment tree., simply a wrapper for the update function in my segment tree, and that call to it sets the position, that should be changed depending on the problem — such as segment tree combination (in the, * Basic tree algorithms (such as dfs) * Segment trees (at the very least, what their purpose is, * The `seg_combine` function is the function you want to use to combine values on thesegment tree, **Building a segment tree on each heavy chain**, **The segment tree**, For convenience (so I or someone else can stick a segment tree template in), I choose to use a, Now, anyone familiar with a segment tree will recognize that it can be easily applied to solve this, So... what? How do we turn a tree into something we can use a segment tree on? Well, we can't

Full text and comments »

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

32.
By TheScrasse, history, 5 years ago, In English
[Tutorial] Diameter of a tree and its applications Hello everyone,<br> finding the diameter is one of the most frequent ways to solve problems about trees. In this tutorial we will see how to find a diameter and some of its properties, and we will use them to solve some problems of increasing difficulty.<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, 2300]$ on CF<br> Prerequisites: basic graph theory, greedy The diameter ------------------ Given an unweighted tree, let's define $\text{dist}(a, b) =$ the number of edges in the simple path $a \rightarrow b$. A diameter of the tree $a \rightarrow b$ is the longest path, i.e., the one that maximizes $\text{dist}(a, b)$ over all pairs of nodes. If there are multiple diameters, let's pick any of them. The same definition is valid for a weighted tree with nonnegative weights (with $\text{dist}(a, b) =$ the sum of the weights of the edges in the simple path $a \rightar...
[Tutorial] Diameter of a tree and its applications, In order to support subtree updates, let's use a segment tree where each leaf represents a node of, tree (same with $b$, in another segment tree). You have to support range multiply by $-1$, range max

Full text and comments »

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

33.
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...
Sqrt-tree: answering queries in O(1) with O(NloglogN) preprocessing., Now we can answer the queries in $O(\log \log n)$. We can go down on the tree until we meet a, So, we get a tree. Each node of the tree represents some segment of the array. Node that represents

Full text and comments »

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

34.
By nikgaevoy, 4 years ago, In English
Push-Free Segment Tree ![ ](/predownloaded/95/ad/95ad3397de22cc8b20c52a1eccc87ac0c34e76cb.jpg) Figure 1: Tiffany A pdf version of this text could be found [here](https://acm.math.spbu.ru/trains/push_free_segment_tree.pdf). Prerequisites ------------- First of all, who this article is aimed at. This article assumes you already know what a segment tree is. Have you never heard about the segment tree, the Fenwick tree (aka binary indexed tree, BIT) or the RMQ problem, you should better read about it [somewhere else](https://codeforces.me/catalog) and then come back here right after to learn a bunch of cool stuff. The model target audience is the people able to solve [this problem](https://judge.yosupo.jp/problem/range_affine_range_sum) at least in theory. But even if you can't, this article could still be helpful. However, I think this article contains some ideas that were never published before, thus making it interesting even for people who are closely familiar with different variants o...
Push-Free Segment Tree, assumes you already know what a segment tree is. Have you never heard about the segment tree, the, definitely being viable for a segment tree. However, it would work if we add the size of a, inner segment trees be pushable, thus, we have to invent a segment tree without pushes. And it is, linear functions representing how values in the array $B$ change over time with the lastsegment, push-free segment tree does not require them! Even though the idea is not really too smart, it took, whatever the regular recursive segment tree with lazy propagation can do, but in time and space of the, ) \cdot a = x \cdot a + y \cdot a$. This is the distributive property! If we examine thesegment tree a, , it seems like a segment tree can do all of that and even much more beyond. But, in fact, it does, - Almost any other variant of the segment tree named after some red Chinese participant. The only, - Historical sums! If you are unfamiliar with this idea, it is a trick over segment trees that, . You may say that the multidimensional segment tree is not anything new: you just store asegment, As you probably know, there are two main ways to implement a segment tree. Downwards: recursive, But in one-dimensional case, the push-free segment tree (this is how I named it about $3.5$ years, But what do we actually need from the segment tree for this trick to work? Commutative property of, Here we discuss some algebra behind the operations on a segment tree. But don't be afraid, On a side note, if you are a huge fan of Fenwick tree or using some trees for solving RMQ, the vast, What Segment Trees Can Actually Do ----------------------------------, What do we need from our operations of addition and multiplication in order for oursegment tree to, tree is. Have you never heard about the segment tree, the Fenwick tree (aka binary indexedtree, BIT

Full text and comments »

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

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

Full text and comments »

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

36.
By codetiger927, history, 5 years ago, In English
My Quest to Answer the Ultimate Question Through Machine Learning: If a hamster was born in aquarium, does it become a fish? `If a hamster was born in aquarium, does it become a fish?` &mdash; Rotavirus 2021 When the hour hand is way past twelve and the sky is dark, I often find myself pondering about this question, alone. Of course, a hamster is a hamster, and it cannot just become a fish right? But then again, if its mother gave birth to it inside an aquarium, then who's to say the hamsters didn't acquire a critical mutation that gifted them the ability to breathe underwater, transforming them into fish? I would be awake at 3 am in the morning, frustrated and defeated by this cruel dilemma that I cannot seem to solve. But, Rotavirus must know, right? After all, he was the person that proposed this rhetorical question, so he must have the answer to his own question! If I could just ask him, maybe, just maybe... Yet fate cheated me once again: Codeforces has permanently banned Rotavirus &mdash; I can no longer ask him. All I have left are only pieces of clues and hints scattered around his commen...
"I believe that means stupid must complain about the segment tree." (The AI seemed to really pick, "segment tree is very indian" (interesting take O_o, talk about the importance of being careful

Full text and comments »

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

37.
By bicsi, history, 6 years ago, In English
Compressed segment trees and merging sets in O(N logU) Hello! Today I will present a data structure that I have worked on for my Bachelor thesis a while ago, called (by me) a PreTree ([link to thesis](https://github.com/bicsi/pretree)). This is a type of "compressed" trie that is arguably easier to implement than a regular compressed trie, and it achieves merging in amortized $O(N L)$ complexity for $N$ keys of equal length $L$. I will present an implementation as a segment tree, though, as it is easier to understand. **Prerequisite: know segment trees, and "sparse" segment trees (a.k.a. bitwise tries).** ### Main idea We will keep a regular segment tree, with the twist that *the root contains the minimum key*. Basically, a PreTree on keys in the universe $[b, e)$ is a binary tree $T$ where either $T$ is empty, or the following conditions hold: 1. $T$ holds the lowest key present in the range $[b, e)$ 2. $T$'s left son is a PreTree on values $[b, \frac{b + e}{2})$ 3. $T$'s right son is a PreTree on values $[\frac{b + e}{2...
Compressed segment trees and merging sets in O(N logU), ' value, yielding a very elegant and short implementation) - [B. Segment Tree for the Minimum](https, **Prerequisite: know segment trees, and "sparse" segment trees (a.k.a. bitwise tries).**, Could you tell me about some other problems involving some form of sparse segment trees and other, We will keep a regular segment tree, with the twist that *the root contains the minimum key

Full text and comments »

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

38.
By prvocislo, history, 4 years ago, In English
I Reached GM after 5 years Hello Codeforces! I did it! My main goal for 2022 was to reach red and I succeeded in the last contest of the year by getting +1 delta and going from cursed 2399 to 2400! I was very happy but scared to celebrate because I was worried that my rating would go down to 2399 again after the cheater removal. But now it’s 2401, so I think I’m safe now. Why am I writing this blog? I'm very excited about this achievement, it means a lot to me and I want to share my happiness with Codeforces. Also people ask me in DM quite often about how I got onto this level or who I am in general, so I think it's time to summarize it all into one blog post. Oh, wait… You don’t even know me, so why should you keep reading this blog post? Let me introduce myself a little first. I’m a high schooler from a small European country where few people do Codeforces. I love competing in OI and MO, I always did. One day, my father found the Codeforces website and suggested that I should start practicing there. At ...
, MST, hashing, inverse elements, gcd caluculation, fast nCk calculation algorithm, andsegment

Full text and comments »

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

39.
By Monogon, history, 21 month(s) ago, In English
[Unsolicited Analysis] On Segment Tree Branching Factor Recently I've been wondering, why do we always use a branching factor of $2$ in segment trees, and are there situations where it would actually be better to use a different branching factor? First, by branching factor I mean the number of children of each node. As we all know, in a segment tree each node represents an interval $[l, r]$ and splits into two children, representing the intervals $[l, m]$ and $[m+1, r]$, respectively, where $m=\lfloor(l+r)/2\rfloor$. But what if we instead split each interval into $k$ intervals, so that each node of the segment tree has $k$ children? In an extreme example, you can set $k=\sqrt n$ and this is essentially the Sqrt tree. In this blog I'd like to explore the analysis of choosing an optimal branching factor, effectively questioning whether we've been doing segment trees wrong all this time. ## First Analysis For simplicity, let's just say that we must support range queries and point updates (no range updates). If our branching factor ...
[Unsolicited Analysis] On Segment Tree Branching Factor, I mean. In many segment tree operations, it's easy to apply an update to each of its parents, with a normal segment tree. Boring!, , by branching factor I mean the number of children of each node. As we all know, in asegment tree, But what if we instead split each interval into $k$ intervals, so that each node of thesegment, Finally, the total complexity of all segment tree operations is $$\frac{m\log n}{\log (m/q)}+\frac, First, by branching factor I mean the number of children of each node. As we all know, in asegment, Recently I've been wondering, why do we always use a branching factor of $2$ in segment trees, and

Full text and comments »

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

40.
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...
[Tutorial]Using Segment Trees to solve Dynamic Programming problems, advanced variations of segment trees to solve them., update a value at a certain position. A simple segment tree is perfect for this job., ![Simulation of segment Tree ](/predownloaded/0e/2e/0e2e29cf1410980710f89df227c5a24709ae876f.png ), Both segment trees and dynamic programming are common topics in competitive programming. Sometimes, Now, this looks certainly more approachable. We can do this transition using segment tree. As for, The main advantage of using the segment tree solution over the binary search one is that it can, segment trees.

Full text and comments »

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

41.
By TLE, history, 10 years ago, In English
using merging segment tree to solve problems about sorted list Two months ago, I came across a problem. Initially there are n elements, they are in n tiles. There are 3 kinds of queries: 1. merge two tiles into one tile. 2. split one tile into two tiles. (Formally for a tile of size k, split it into two tiles of size k1 and k2, k=k1+k2, the first tile contains the smallest k1 elements and the second tile contains the rest) 3. find the k-th smallest element in one tile. Recently I found this technique http://blog.csdn.net/zawedx/article/details/51818475 (in Chinese) which can be used to solve this problem. This blog is my own explanation :p First, let's suppose the values in the sorted lists are integers between 1~n. If not, you may just sort and map them. Let's build a segment tree for every sorted list, segment trees are built based on values (1~n). In every node of a segment tree stores how many numbers are in this range, let's call this the value of a node. It seems that it requires O(nlogn) space to store every segment t...
using merging segment tree to solve problems about sorted list, Let's investigate the total number of allocated segment tree nodes., just sort and map them. Let's build a segment tree for every sorted list, segment trees are built, of allocated segment tree nodes will decrease by 1 (t2 isn't useful anymore). Obviously 'nothing to, It seems that it requires O(nlogn) space to store every segment tree, but we can simply ignore the, Let's build a segment tree for every sorted list, segment trees are built based on values (1~n). In, So the total number of allocated segment tree nodes will at most be only O(nlogn)., When we split a segment tree (sorted list), simply split two children recursively:, the total number of allocated segment tree nodes is O(nlogn), for every useful merge it will, ~~~~~ //merge trees t1&t2, return merged segment tree (t1 in fact) int merge(int t1,int t2

Full text and comments »

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

42.
By PurpleCrayon, 4 years ago, In English
[Tutorial] XOR Segment Tree hi Today's post continues my theme of niche but sometimes useful topics in CP. This idea was brought to my attention by [user:magnus.hegdahl,2022-08-07], so thanks to him! ### General Description The motivation behind the technique is to solve the following problem: Given a static array $a$ of $n$ elements (for convenience, I'll assume $n$ is a power of $2$, if not, the array can be padded with null elements), answer $q$ queries of the form $($$l$, $r$, $x$$)$ where you have to print $\sum\limits_{k = l}^r a_{k \oplus x}$. In particular, a query where $x = 0$ is just a normal segtree query. If $x$ is non-zero, the array indices that are being queried are no longer contiguous, making this impossible to solve with a normal segtree. Note: the only requirement is that the "addition" operation is associative (commutativity is not required). The solution provided in this blog solves the problem in $\mathcal{O}(n \log{} n + q \log{} n)$ with $\mathcal{O}(n \log{} n)$ memory. The mem...
[Tutorial] XOR Segment Tree, About the name: I've seen it called XOR segment tree in 2 different places, so I assume that's what, For the rest of this tutorial, I will assume that you use a recursive implemenetation ofsegment

Full text and comments »

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

43.
By errorgorn, 4 years ago, In English
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
make a segment tree on each heavy chain. But there are a few things I want to talk about here., ### HLD + Segment Tree, #### Really Fast Segment Trees, Below is code for segment tree that handles range increment updates and range max queries., So, we need to create a data structure that is similar to HLD+segment tree but instead of having a, There are $2$ styles of implementing this "segment tree on each heavy chain" part. One way, which, When looking for fast segment tree implementations, most people would probably direct you to the, With our normal HLD+segment tree query, we can easily handle both path and subtree queries $[7]$., tree easily forces the implementation of having a single segment tree to go into its worse case of $O, | | HLD + segment tree (single segment tree) | Balanced HLD 2, | | HLD + segment tree (single segment tree) | HLD + segment tree (many segment

Full text and comments »

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

44.
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, Георгий Корнее...
and thus new critical numbers will appear. We need segment tree of sorted suffixes to quickly go, renumerating values to range $[1, n]$ and then doing a segment tree, or by sorting values and then, If possible in your solution, use BIT/Fenwick instead of a segment tree to get the full score. You

Full text and comments »

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

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

Full text and comments »

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

46.
By TheScrasse, history, 3 years ago, In English
Editorial of Pinely Round 3 (Div. 1 + Div. 2) The official implementations of all the problems are [here](https://drive.google.com/file/d/1q2PHS9nJt84FRwfMoiMslQULFE4dTMU4/view?usp=sharing). <spoiler summary="Timeline of the round proposal (may contain spoilers)"> (problems D', H', etc. were not used) - Feb 19, 2022: I proposed problem D' to [contest:1654], but it was not used. - Mar 13, 2023: I invented problem A. - May 16: I invented problem H'. - May 19: I realized problem G can be solved in $O(n)$ time and we used it in the Italian team selection test for IOI. - Jul 04: I opened a Div. 1 proposal containing A, D', G, H' and other problems which are not going to be used. - Aug 09: I invented problem I, with intended solution in $O(n^3)$. - Sep 27: I invented problem C. - Oct 14: [user:errorgorn,2023-12-23] replied to my contest proposal. - Nov 02: I invented problem D''. [user:errorgorn,2023-12-23] solved problem I in $O(n^2 \log n)$. - Nov 08: I invented problems E and F. I didn't propose problem F because I th...
For example, you can use a segment tree with the following information, - We maintain a segment tree. The $i$-th position of the segment tree contains information about

Full text and comments »

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

47.
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...
segment tree to maintain updates.

Full text and comments »

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

48.
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/115/problem/E (5) //[VERY NICE][SEGMENT TREE], http://codeforces.me/contest/911/problem/G (7) //Segment tree over queries, http://codeforces.me/gym/101801 [D] (6) //[VERY NICE][SEGMENT TREE ][SORTING][NORMALIZE], http://codeforces.me/gym/101806/problem/T (5) //[NICE][SEGMENT TREE][SORTING], http://www.spoj.com/problems/HAYBALE/ (3) //Basic sum + sort (segment tree would work too), http://www.spoj.com/problems/PRMQUER/ (5) //2 segment trees + sieve, https://toph.co/p/mario-and-princess-peach (5) //[NICE][DP][SEGMENT TREE][MAX]

Full text and comments »

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

49.
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...
Attempting to Extend Segment Trees to Arbitrary Subsets, + a_{p_v}$. Everything is $O(1)$. The similarity to the segment tree optimization is that, we, motivation was from inspection of segment trees. Define the following problem, which we will try to solve, For implicit subsets as ranges, segment trees work :). Here's an interesting implicit case that I, The construction is just setting $n'$ as the number of nodes in the segment tree , setting $S_i$ for, Throughout the last several weeks I have tried to invent and solve, a generalization ofsegment

Full text and comments »

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

50.
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...
Target: rating $[1400, 2100]$ on CF Prerequisites: greedy, Fenwick tree (or segment tree)

Full text and comments »

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

51.
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...
problems that deal with segments, we're going to use a segment tree.

Full text and comments »

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

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

Full text and comments »

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

53.
By Noam527, 6 years ago, In English
[Tutorial] Supporting Queue-like Undoing on DS In many data structures, the operation of "undo" on the last update can be implemented easily: we can (usually) maintain a stack of the updates, where each update on the stack holds the memory cells it changed, and their original values. To undo an operation, just revert all changes from the top update on the stack. To maintain good complexity, we require the updates to operate in non-amortized time. I've seen this being used multiple times on DSU (without path compression). If we imagine the updates as a sequence, then we can push an update to the end, and pop an update from the end by undo. Then, this sequence is a stack of updates. Here we discuss the idea of having a queue of updates: we can add a new update, or undo the oldest update still active. Specifically, this blogpost attempts to solve the following problem: Given a data structure that can support some updates, some queries and an "undo" operation (each with their own time complexity), how can we create a data structu...
maximum in range. These updates are commutative so we could apply the idea on a lazysegment tree., A data structure this won't work on is, for example, a segment tree with the update of "set in

Full text and comments »

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

54.
By Ashwanth.K, history, 2 years ago, In English
Segment tree for graph problems - Recently I came across a new idea to solve graph-related problems using segment trees, I would like to discuss the same with a problem. #### Problem: Given a graph $G$ with $N$ nodes and many edges (around $O(N^2)$), Goal is to perform the Dijkstra algorithm on this dense graph and find out the shortest path cost from node 1 to all other nodes. The edges are given in a compressed format. The input follows $M$ lines. Each of the $M$ lines consists of 4 integers `U Lx Rx C` meaning there are edges from node `U` to all other nodes in range `[Lx , Rx]` with cost `C`. Edges are **uni-directional**. **Example:** For `N = 6` , the edge-group `U = 1 , [Lx,Rx] = [3,5] , C = 10` looks like: ![ ](https://i.ibb.co/yp7Shdf/segtree-drawio-2.png) #### Constraints: - $1 \le N \le 10^5$ - $1 \le M \le 10^5$ - $1 \le U \le N$ - $1 \le Lx \le Rx \le N$ - $...
Segment tree for graph problems, problem. - In our solution, We only use the structure and ideas of segment tree (complete, #### Solution: Segment Tree as a structure, - Recently I came across a new idea to solve graph-related problems using segment trees, I would

Full text and comments »

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

55.
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, techniques like segment trees, policy based data structures, treaps, etc. which can perform

Full text and comments »

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

56.
By AmShZ, history, 7 months ago, In English
Two Lazy Segment Tree Mental Models I and [user:Amoo_Safar,2026-04-26] always discuss our lazy segment tree logic. The difference is this: When I enter a node, I first apply its pending lazy value to the node itself. But Amoo_Safar's assumption is that when he enters a node, the lazy value has already been applied before. Below I show how this difference appears in implementation. [user:Amoo_Safar,2026-04-26]'s style In this style, the node is considered already updated correctly. The lazy value only means that this effect still has to be pushed to the children later. So before going deeper, we call `shift(id)`. ~~~~~ void upd(int id, int val) { seg[id] += val; lazy[id] += val; } void shift(int id) { if (!lazy[id]) return; upd(id << 1, lazy[id]); upd(id << 1 | 1, lazy[id]); lazy[id] = 0; } void update(int id, int l, int r, int ql, int qr, int val) { if (qr <= l || r <= ql) return; if (ql <= l && r <= qr) { upd(id, val); return...
Two Lazy Segment Tree Mental Models, I and [user:Amoo_Safar,2026-04-26] always discuss our lazy segment tree logic.

Full text and comments »

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

57.
By Sulfox, 7 years ago, In English
Codeforces Round #635 Editorial [problem:1337A] Idea: [user:Sooke,2020-04-16] <spoiler summary="Tutorial"> [tutorial:1337A] </spoiler> <spoiler summary="Solution by Sooke"> ~~~~~ #include <bits/stdc++.h> using namespace std; int t, a, b, c, d; int main() { for (cin >> t; t; t--) { cin >> a >> b >> c >> d; cout << b << " " << c << " " << c << endl; } return 0; } ~~~~~ </spoiler> [problem:1337B] Idea: [user:EternalAlexander,2020-04-16] <spoiler summary="Tutorial"> [tutorial:1337B] </spoiler> <spoiler summary="Solution by EternalAlexander"> ~~~~~ #include <bits/stdc++.h> int x,n,m,t; void solve(){ scanf("%d%d%d",&x,&n,&m); while (x>0&&n&&x/2+10<x){n--;x=x/2+10;} if (x<=m*10)printf("YES\n"); else printf("NO\n"); } int main(){ scanf("%d",&t); while(t--)solve(); return 0; } ~~~~~ </spoiler> [problem:1336A] Idea: [user:EternalAlexander,2020-04-16] <spoiler summary="Tutorial"> [tutorial:1336A] </spoiler> <spoiler...
We can use a segment tree on the DFS-order to maintain all $y$s in the subtree and merge them with

Full text and comments »

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

58.
By magnus.hegdahl, 5 years ago, In English
[Tutorial] Commutative Segment Trees # Commutative Segment Trees ## Preface This blog is about an alternative way to implement segment trees. Knowing segment tree already should not be necessary to understand this blog, but it is mostly targeted towards people who already know segment trees but don't know how to for example create a merge sort tree that supports updates. <span style="color:green">Pros:</span> - You don't need a fast merge function (which allows you to for example extend to 2D) - Very easy to implement - Fast <span style="color:red">Cons:</span> - Merging has to be commutative - Can't easily be turned lazy (meaning only update or query can be on a range, not both) Disclaimer: This way of implementing segment tree may be what you think of as "a standard segment tree". But the reason I made this blog is that I talked to people who were very familiar with segment trees but did not know how to make a 2D segment tree (which is a trivial modification of this way to implement segment t...
[Tutorial] Commutative Segment Trees, in this problem, so instead of a commutative segment tree of BSTs we can create a commutative, # Commutative Segment Trees, A merge sort tree is just a regular merging segment tree where the merge operation is to weave, Disclaimer: This way of implementing segment tree may be what you think of as "a standardsegment, This blog is about an alternative way to implement segment trees. Knowing segment tree already

Full text and comments »

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

59.
By VladiG, history, 8 months ago, In English
Segment tree on Time First of all, this technique isn't anything new, it's a fairly known one, but I couldn't find any resources on this topic other than [this comment](https://codeforces.me/blog/entry/15296?#comment-203606) which is somewhat hard to find, so I decided to write a full blog. With that being said, let's begin with the blog. The problem ================== Lets consider the following problem: A graph is given with $N$ nodes and $Q$ queries. Each query is one of the following: - Add edge $(u,v)$ - Remove edge $(u,v)$ - Query the number of connected components in the graph The timeline ================== Lets imagine a timeline, from time $1$ to time $Q$, at each moment either some edge gets added, removed, or a query gets asked. Now the main idea of this technique is instead of dealing with deletions, for each edge we determine some intervals during which it exists. Namely if edge $(u, v)$ gets added at time $A$ and then later removed at time $B$ then that edge will ob...
Segment tree on Time, Each interval gets decomposed into $O( \log Q)$ segments in the tree, and for each of those, Now we've turned the problem into a range update problem, which suggests using a segment tree. We, The Segment Tree on time ==================

Full text and comments »

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

60.
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...
tree. Now when we considered the segment $i$ we set $1$ in the Fenwick tree on position $r_i$.

Full text and comments »

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

61.
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...
[Tutorial] Reachability Tree / DSU-tree, represented as a segment, then we can use a segment tree to process all our queries., Perform DFS, then we can order the leaves of the reachability tree according to their preorder

Full text and comments »

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

62.
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 $...
Now, we should fins $T(b_{x}…T_{y})$. For this purpose, we need a segment tree. In each node of the

Full text and comments »

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

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

Full text and comments »

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

64.
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 ...
Build a segment tree to answer queries in $O(\log n)$. What should be

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

67.
By taha06, history, 3 years ago, In English
SD Segment Tree Variation, A Shorter And More Efficient Segment Tree Segment Tree is a powerful data structure in programming, that is why it can still be optimized way more. In this blog I will explain one optimization that can make a basic segment tree slightly faster and easier to write. (idea and the code by me) This does not work on range update range query segment trees. Introduction: ================== Let's consider a point update range query segment tree, while querying we visit many of useless Nodes along the way in order to answer the query moving from the root downwards. ![ ](/predownloaded/ef/4d/ef4d1dcb34f2560f3ddad1fa2f1dd9947e13ebce.png) As you can see, there are nodes (marked in red) that are not needed during the recursion, and we only need to visit the important nodes (marked in green). This is only true when querying in a point update segment tree or updating in a point query segment tree. Main Idea: ================== We can solve a query range $[l, r]$ by noticing we can make it a smaller range $[l + X , r]$, ...
SD Segment Tree Variation, A Shorter And More Efficient Segment Tree, This is only true when querying in a point update segment tree or updating in a point querysegment

Full text and comments »

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