Можно ввести несколько слов — все они попадут в требования к поиску. Кроме того, осуществляется поиск по словоформам и, если повезет, по синонимам. Поддерживается поиск по названию, автору и специальный синтаксис запросов. Примеры:

  • 305 — ищет все посты, содержащие 305, найдет посты про Раунд 305
  • andrew stankevich contests — можно писать сразу много слов, будут искаться все
  • user:mikemirzayanov title:сазанка — ищет все посты в названии со словом "сазанка" авторства MikeMirzayanov
  • "vk cup" — можно использовать кавычку, чтобы искать точные совпадения
  • title:educational — искать в названии

Результаты

1.
Автор rng_58, история, 6 лет назад, По-английски
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 withlazy propagation, lazy propagation in our contests. However this way we can't use otherwise interesting problems and it

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1385
  • Проголосовать: не нравится

2.
Автор parveen1981, история, 5 лет назад, По-английски
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...
Tree)](https://codeforces.me/blog/entry/89880) - [Do we actually need lazy propagation on segment, ://codeforces.com/blog/entry/85420) - [Sqrt-tree (part 2): modifications in O(sqrtN),lazy, ://codeforces.com/blog/entry/89880) - [Do we actually need lazy propagation on segment trees?](https

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1500
  • Проголосовать: не нравится

3.
Автор PrinceOfPersia, 12 лет назад, По-английски
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$ ...
when we need. This trick is called **Lazy Propagation**, so we should have another array $lazy, #### Lazy propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • +608
  • Проголосовать: не нравится

4.
Автор rama_pang, история, 6 лет назад, По-английски
[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...
is no line yet. Thus we can use a basic Li Chao Tree with normal lazy propagation on top., update through normal lazy propagation., Hello everyone! I discovered a new (?) trick on how to apply lazy propagation on the Li Chao Tree, Now we need to implement a lazy propagation method. But implementing it naively won't work. As an

Полный текст и комментарии »

  • Проголосовать: нравится
  • +608
  • Проголосовать: не нравится

5.
Автор PrinceOfPersia, 12 лет назад, По-английски
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...
++]); ans[x] = sum(i[x], j[x] + 1); // the interval [i[x], j[x] + 1) } ~~~~~ Lazy Propagation, = \sum k$ (we don't need lazy propagation, because we only update maximal nodes)., update the nodes using lazy propagation., A function for shifting the updates to a node, to its children using lazy propagation :, I told you enough about lazy propagation in the last lecture. In this lecture, I want to solve ans, Lazy Propagation ----------------

Полный текст и комментарии »

  • Проголосовать: нравится
  • +323
  • Проголосовать: не нравится

6.
Автор Al.Cash, 11 лет назад, По-английски
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....
about lazy propagation for more information., Lazy propagation ================== Next we'll describe a technique to perform both range queries

Полный текст и комментарии »

  • Проголосовать: нравится
  • +354
  • Проголосовать: не нравится

7.
Автор galen_colin, 6 лет назад, По-английски
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...
case of the USACO problem, xor), sentinel values, and how to handle lazy propagation. Of course, feel, trees (at the very least, what their purpose is), with lazy propagation * Binary lifting (useful for, ), with lazy propagation * Binary lifting (useful for my implementation, other implementations may not, , and with sum or xor it should be `0`. * `seg_lazy_sentinel` is a flag for lazy propagation, saying

Полный текст и комментарии »

  • Проголосовать: нравится
  • +404
  • Проголосовать: не нравится

8.
Автор smax, 4 года назад, По-английски
[Tutorial] Fully Dynamic Trees Supporting Path/Subtree Aggregates and Lazy Path/Subtree Updates Hey everyone! Usually when I post stuff on CF I just drop an external link to my blog, but this time I would like to also paste the same content natively on CF to see if it leads to more engagement. You can read the exact same article on my blog [here](https://mzhang2021.github.io/cp-blog/ds5/). Also, special thanks to [user:alien_lover,2022-06-10] and [user:gabrielwu,2022-06-10] for proofreading. --- ## Motivation We will solve **[this problem](https://dmoj.ca/problem/ds5)**. ## Prologue The original name of this problem is [SONE1](https://darkbzoj.cc/problem/3153), originating from the fiery depths of Chinese OI. Amazingly, the Chinese have figured out how to augment the link/cut tree to solve this problem (ref [1](https://www.cnblogs.com/clrs97/p/4403244.html), [2](https://blog.csdn.net/iamzky/article/details/43494481)). Maintaining subtree aggregates with a LCT isn't difficult, and there's a well-known [Codeforces article](https://codeforces.me/blog/entry/67637) ...
[Tutorial] Fully Dynamic Trees Supporting Path/Subtree Aggregates and Lazy Path/Subtree Updates, This code uses a style of lazy where the values are correctly updated at, node is either a **preferred child** or a **virtual child**. The issue with doinglazy propagation, splays. - When doing lazy propagation, pushing down lazy tags to children is referred to as a **push, ## How to Do the Lazy Propagation, . - When doing lazy propagation, pushing down lazy tags to children is referred to as a **push, A first thought on doing lazy propagation is to simply maintain 2 lazy values: one for the path

Полный текст и комментарии »

  • Проголосовать: нравится
  • +259
  • Проголосовать: не нравится

9.
Автор bicsi, история, 7 лет назад, По-английски
Do we actually need lazy propagation on segment trees? There seems to be a lot of encouragement for new people to learn segment trees, and in particular the lazy propagation technique, and it seems to me that most of the time it is not actually needed. As a quick refresher (although I feel most of you would already know), lazy propagation is a technique in segment trees that lets you do updates on whole ranges of elements, by first only updating the smallest factoring of the update range in the tree. For example, in order to update range $[2, 5]$, what you do is you update only ranges $[2, 2], [3, 4], [5, 5]$ in the segment tree, and next time node $[3, 4]$ is accessed you "propagate" the updates downward into ranges $[3, 3]$ and $[4, 4]$. This allows you to effectively aggregate (combine) multiple updates on a given range, to save extra work. Usually when people talk about lazy propagation, some tasks like "add on range" &mdash; "minimum on range" or "add on range" &mdash; "sum of range" naturally come to mind. However, I feel lik...
Do we actually need lazy propagation on segment trees?, I've encountered need some sort of "lazy" value that holds an aggregate of operations that affect the, comparison if people are interested, but from my experience I found that lazy propagation yields a, operations inside $lazy$ while going down in the tree. The technique is similar to something called, the lazy propagation technique, and it seems to me that most of the time it is not actually needed, why any of these kind of problems would use lazy propagation instead of this technique., ### So, you still store lazy array, but you just don't propagate. Why should we care?, An alternative way one could approach these kind of problems is to keep an extra array $lazy$ with, As a quick refresher (although I feel most of you would already know), lazy propagation is a, Usually when people talk about lazy propagation, some tasks like "add on range" — "minimum on

Полный текст и комментарии »

  • Проголосовать: нравится
  • +70
  • Проголосовать: не нравится

10.
Автор errorgorn, история, 5 лет назад, По-английски
Codeforces Round #723 (Div. 2) Editorial [problem:1526A] ------------------ Setter: [user:antontrygubO_o,2021-05-28] Preparer: [user:errorgorn,2021-05-28] <spoiler summary="Hint 1"> Notice that the array size is even length. Usually in such problems, we would split the array into $2$ equal parts. Can you figure out what those $2$ parts are? </spoiler> <spoiler summary="Hint 2"> We sort the array and split it into the big half and the small half. </spoiler> <spoiler summary="Solution"> The main idea is that we can split the numbers into the two halves, the big half and small half, we can place the bigger half at the odd positions and the smaller half at the even positions. This works because the smallest big number is larger than the biggest small number. Hence, the mean of any two small numbers is smaller than any big number, and the mean of any two big numbers is bigger than any small number. </spoiler> <spoiler summary="Code (C++)"> ```c++ //雪花飄飄北風嘯嘯 //天地一片蒼茫 #include <bits/stdc++.h> #inc...
Doing this naively is $O(n^2)$ as well. However, using a range add range max lazy propagation

Полный текст и комментарии »

Разбор задач Codeforces Round 723 (Div. 2)
  • Проголосовать: нравится
  • +199
  • Проголосовать: не нравится

11.
Автор gepardo, история, 8 лет назад, По-английски
Sqrt-tree (part 2): modifications in O(sqrtN), lazy propagation Hello, Codeforces! Some time ago I created a blog post about [Sqrt-tree](http://codeforces.me/blog/entry/57046). If you didn't read this post, please do it now. But earlier, we were able just to answer the queries on a static array. Now we will make our structure more "dynamic" and add update queries there. So, let's begin! # Update queries Consider a query $\text{update}(x, val)$ that does the assignment $a_x = val$. We need to perform this query fast enough. ## Naive approach First, let's take a look of what is changed in our tree when a single element changes. Consider a tree node with length $l$ and its arrays: $\text{prefixOp}$, $\text{suffixOp}$ and $\text{between}$. It is easy to see that only $O(\sqrt{l})$ elements from $\text{prefixOp}$ and $\text{suffixOp}$ will change (only inside the block with the changed element). $\text{between}$ will change $O(l)$ elements. Therefore, total update count per node is $O(l)$. We remember that any element $x$ is pre...
Sqrt-tree (part 2): modifications in O(sqrtN), lazy propagation, # Lazy propagation, As we can see, sqrt-tree can perform update queries and do lazy propagation. So, it provides the, I am too lazy (like a node in an sqrt-tree :) ) to write the implementation of lazy propagation on, So we can do $\text{massUpdate}$ fast. But how lazy propagation affects queries? They will have the, We will do lazy propagation in the same way as it is done in segment trees: we mark some nodes as

Полный текст и комментарии »

  • Проголосовать: нравится
  • +98
  • Проголосовать: не нравится

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

Полный текст и комментарии »

  • Проголосовать: нравится
  • +248
  • Проголосовать: не нравится

13.
Автор PrinceOfPersia, история, 11 лет назад, По-английски
Codeforces Round #326 (Editorial) ### Div.2 A (Author: [user:Haghani,2015-10-01]) Idea is a simple greedy, buy needed meat for $i-th$ day when it's cheapest among days $1, 2, ..., n$. So, the pseudo code below will work: ~~~~~ ans = 0 price = infinity for i = 1 to n price = min(price, p[i]) ans += price * a[i] ~~~~~ ![ ](http://codeforces.me/predownloaded/64/4c/644c9930cf472ff1bdb48eb3a5f481cce5bbc04b.png) Time complexity: $\mathcal O(n)$ [C++ Code](http://ideone.com/fa7rF5) by [user:amd,2016-03-05] [Python Code](http://ideone.com/Sh0hPp) by [user:Haghani,2015-10-15] [Python Code](http://ideone.com/5J6Rew) by [user:Zlobober,2015-10-15] ### Div.2 B (Author: [user:amd,2016-03-05]) Find all prime divisors of $n$. Assume they are $p_1, p_2, ..., p_k$ (in $\mathcal O(\sqrt n)$). If answer is $a$, then we know that for each $1 \leq i \leq k$, obviously $a$ is not divisible by $p_i^2$ (and all greater powers of $p_i$). So $a \leq p_1 \times p_2 \times ... \times p_k$. And we...
This problem can be solved easily with a simple segment tree using lazy propagation.

Полный текст и комментарии »

Разбор задач Codeforces Round 326 (Div. 1)
  • Проголосовать: нравится
  • +171
  • Проголосовать: не нравится

14.
Автор kartik8800, 6 лет назад, По-английски
CSES Range Queries section editorial **UPD:** some video editorials on range query data structures: [youtubePlaylist](https://www.youtube.com/playlist?list=PLb3g_Z8nEv1isaHPaXL1j-pSo60812JtY) Hello Codeforces, In this blog I will try to write a well detailed editorial for the CSES Range Queries section. The motivation for this editorial comes from https://codeforces.me/blog/entry/70018. Quoting [user:icecuber,2020-05-09] "I think [CSES](https://cses.fi/problemset/) is a nice collection of important CP problems, and would like it to have editorials. Without editorials users will get stuck on problems, and give up without learning the solution. I think this slows down learning significantly compared to solving problems with editorials. Therefore, I encourage others who want to contribute, to write editorials for other sections of CSES." So here I am writing an editorial for the range queries section. If you find any error or maybe have a better solution to some problem please do share. Range Sum Queries I =...
We will use a segment tree with lazy, Nice question which can be directly solved with a segment tree with lazy propagation but that is an, To better understand lazy propagation, I recommend reading this : [Super amazing theory in 1

Полный текст и комментарии »

  • Проголосовать: нравится
  • +181
  • Проголосовать: не нравится

15.
Автор Errichto, 10 лет назад, По-английски
Codeforces Round #356 — Editorial # [problem:680A] Iterate over all pairs and triples of numbers, and for each of them check if all two/three numbers are equal. If yes then consider the sum of remaining numbers as the answer (the final answer will be the minimum of considered sums). Below you can see two ways to implement the solution. <spoiler summary="code1"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t[5]; int s = 0; for(int i = 0; i < 5; ++i) { scanf("%d", &t[i]); s += t[i]; } int best = s; // discard 2 cards for(int a = 0; a < 5; ++a) for(int b = a + 1; b < 5; ++b) if(t[a] == t[b]) best = min(best, s - 2 * t[a]); // or discard 3 cards for(int a = 0; a < 5; ++a) for(int b = a + 1; b < 5; ++b) for(int c = b + 1; c < 5; ++c) if(t[a] == t[b] && t[a] == t[c]) best = min(best, s - 3 * t[a]); printf("%d\n", best); return 0; } ~~~~~ </spoiler> <spoiler summary=...
can make a tree with operations (possible with lazy propagation):

Полный текст и комментарии »

Разбор задач Codeforces Round 356 (Div. 1)
Разбор задач Codeforces Round 356 (Div. 2)
  • Проголосовать: нравится
  • +99
  • Проголосовать: не нравится

16.
Автор kiwii, 3 года назад, По-английски
Luvliest Lub Lub Dynamic Diameter and Euler Tour?? ωeecently, I've encountered this pωoblem in a local contest in my coωountωy and I find this pωobωem has a ωeeeaωy cuωul tωick, i aωso found out that this has a s-s-similar idea, and the pωoblem can be fuωuωutheω be ωeduced to &#10024; **Dynamic Diameter** &#10024; [https://oj.uz/problem/view/CEOI19_diameter](https://oj.uz/problem/view/CEOI19_diameter) ## Pωobωem S-S-Statement (,,> &#7447; <,,) Ur given a&#127795; with $N$ n-n-nodes and $N - 1$ e-edges connecting each of the nodes. Each edge is a tu&omega;u&omega;u&omega;uple $(u[i], v[i], c[i])$, connecting node $u[i]$ and $v[i]$ with weight $c[i]$ $(0 \leq i \leq n - 2)$. &#127968;&#127947;&#65039; You're given $Q$ quewees: - `1`, output the RAWWRGESTTT &#129409;&#129409;&#129409;&#129409; diameter of the t&omega;ee, fo&omega;o&omega;ed with T&omega;o&#9996;&#65039; nodes $x$ and $y$ de-de-denoting the endp&omega;oints of the diameterr. &#128726; - `2 x`, output the distance between $x$ and $y$, where $y$ is the node w...
= max(head.diameter, r.maxDepth + l.suffixDeep); } ``` ### Update and Lazy Propagation ‧, ### Update and Lazy Propagation ‧₊˚🖇️✩ ₊˚🎧, ].second$ and ends with index $order[3].second < R$. - The lazy propagation for that certain

Полный текст и комментарии »

  • Проголосовать: нравится
  • +204
  • Проголосовать: не нравится

17.
Автор Endagorion, 12 лет назад, перевод, По-русски
Codeforces Round #265 Editorial I'll upload my example solutions and will post links to them as soon as it becomes possible. Some of the problems editorials contain an additional challenge which is apparently harder to comprehend than the original problem. Feel free to share and discuss your ideas in the comments. =) [problem:465A] If we add 1 to a number, its binary representation changes in a simple way: all the least significant $1$'s change to $0$'s, and the single following $0$ changes to $1$. It suffices to find the length of largest suffix which contains only $1$'s, suppose its length is $l$. Then the answer is $l+1$ except for the case when all the string consists of $1$, when the answer is $l$. It is amusing that div1E problem is concerned with addition of 1 to a binary integer as well. =) [problem:465B] Optimal strategy is as follows: for every segment of consecutive $1$'s open the first letter in segment, scroll until the last letter in segment, if there are more unread letters left, retu...
simplifies implementation. It allows to get rid of lazy propagation completely. Here it comes: initially, $ and assigning $0$'s to all the positions in between. Usual segment tree with lazy propagation can, . Usual segment tree with lazy propagation can do it, so persistent tree is able to do it as well.

Полный текст и комментарии »

Разбор задач Codeforces Round 265 (Div. 1)
Разбор задач Codeforces Round 265 (Div. 2)
  • Проголосовать: нравится
  • +172
  • Проголосовать: не нравится

18.
Автор bicsi, история, 6 лет назад, По-английски
Link Cut Tree implementation Hello! Recently I have been trying to learn link cut trees (and splay trees, for that matter). I have tried to polish an implementation that is short (for our ICPC notebooks), and also easy to use and extend. I might be extending this blog post towards a tutorial on how link cut trees are used and, more so, how this template can be used. The implementation is here: <spoiler summary="Implementation"> ``` struct SplayTree { struct Node { int ch[2] = {0, 0}, p = 0; long long self = 0, path = 0; // Path aggregates long long sub = 0, vir = 0; // Subtree aggregates bool flip = 0; // Lazy tags }; vector<Node> T; SplayTree(int n) : T(n + 1) {} void push(int x) { if (!x || !T[x].flip) return; int l = T[x].ch[0], r = T[x].ch[1]; T[l].flip ^= 1, T[r].flip ^= 1; swap(T[x].ch[0], T[x].ch[1]); T[x].flip = 0; } void pull(int x) { int l = T[x].ch[0], r = T[x].ch[1]; push...
`GetPath(u, v)` and to potentially modify the `push` and `pull` methods (`push` islazy propagation, potentially modify the `push` and `pull` methods (`push` is lazy propagation, whereas `pull` is regular tree

Полный текст и комментарии »

  • Проголосовать: нравится
  • +235
  • Проголосовать: не нравится

19.
Автор himanshujaju, история, 10 лет назад, По-английски
Parallel Binary Search [tutorial] [Click here to download the pdf](https://www.dropbox.com/s/cndim2lv872dzen/parallel-binary-search.pdf?dl=0) Pre Requisites -------------- Binary Search &mdash; How it works and where can it be applied! Motivation Problem ------------------ We aim to solve this problem : [Meteors](http://www.spoj.com/problems/METEORS/) The question simply states : There are $N$ member states and $M$ sectors. Each sector is owned by a member state. There are $Q$ queries, each of which denote the amount of meteor shower in a $[L,R]$ range of sectors on that day. The $i^{th}$ member state wants to collect $reqd[i]$ meteors over all its sectors. For every member state, what is the minimum number of days it would have to wait to collect atleast the required amount of meteors? Solution -------- The naive solution here is to do a binary search for each of the $N$ member states. We can update in a range using segment trees with lazy propagation for each query. The time complexity of such a ...
states. We can update in a range using segment trees with lazy propagation for each query. The time

Полный текст и комментарии »

  • Проголосовать: нравится
  • +294
  • Проголосовать: не нравится

20.
Автор bicsi, история, 4 года назад, По-английски
"Merging treaps" -- or how to merge sorted sets in good complexity... ... without doing much of anything. I've been obsessed for the last two days about problem [Data Centers](https://ubilo.tubitak.gov.tr/egoi2022/assets/tasks/DataCenters.pdf) from EGOI 2022. In particular, it has a subtask where $1 \leq N \leq 10^5$ and $1 \leq S \leq 5000$, where it seems $O(NS)$ wouldn't fit TL. I've been conjecturing that using treaps would amortize to good complexity, and after two days of burning grey matter, I've finally found a proof, and it's pretty cool to make a blog out of it. The problem basically starts with an array $[v_1, v_2, ..., v_N]$, where $1 \leq v_i \leq V$ for all $i$. It then asks us to iteratively simulate the operation: "Subtact $x_i$ from the biggest $m_i$ elements.". All this while keeping the array sorted. We'll show that just using treaps (or any BBST for that matter) yields a good amortized complexity. More exactly, we'll prove $O((N + Q) \log V \log N)$, and it should actually be better in practice. ### Naive solution with tr...
Using treaps, it's easy to see that steps 1 and 2 can be done in $O(\log N)$ via split andlazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +150
  • Проголосовать: не нравится

21.
Автор gojira, 5 лет назад, По-английски
A look at Competitive Programming post-hibernation Hello friends! As I've recollected in a previous [post](https://codeforces.me/blog/entry/97566), I am an old competitor who hadn't really participated since ~2014, and recently got a bout of nostalgia to return to Competitive Programming. So, I did a couple Topcoder SRMs, suffered through some SNWS rounds, participated in [three regional 5hr competitions](https://contest.yandex.ru/3QF2021) on three consecutive days, and dozed off at every Codeforces contest I tried to wake up for. A lot of things are still the same as 8 years ago: [user:tourist,2022-01-26] is still at the top, grey coders still ask for how many minutes to solve a problem before reading the editorial, Russian university teams [continue winning](https://icpc.global/worldfinals/results) ACM ICPC, and Snarknews never gives up on his alternate competition formats. But in this post, I want to focus on the new patterns that emerged since my last time around. #### #1: Codeforces rounds timing Did you know that t...
own min-cost max-flow over a network generated by lazy propagation segment tree with 2-SAT FFT

Полный текст и комментарии »

  • Проголосовать: нравится
  • +371
  • Проголосовать: не нравится

22.
Автор saketh, история, 11 лет назад, По-английски
Modular Segment Tree with Lazy Propagation Here is a modular segment tree implementation with range query and lazy range update. I have borrowed heavily from [user:Al.Cash,2015-09-26]'s segment tree post a few months ago, so first, a big thanks to him! You can find the code [here](http://pastebin.com/Df5kfyFZ). The main feature is that it takes template arguments to specify its behavior: ~~~~~ template<typename T, typename U> struct seg_tree_lazy ~~~~~ so that it is usable without any modification to the pre-written code. Instead, it takes a type T for vertex values, and a type U for update operations. Type T should have an operator `+` specifying how to combine vertices. Type U should have an operator `()` specifying how to apply updates to vertices, and an operator `+` for combining two updates. As an example, let's see how to use it to support the follow operations: - Type 1: Add amount V to the values in range [L, R]. - Type 2: Reset the values in range [L, R] to value V. - Type 3: Query for the sum of ...
Modular Segment Tree with Lazy Propagation, Here is a modular segment tree implementation with range query and lazy range update. I have

Полный текст и комментарии »

  • Проголосовать: нравится
  • +96
  • Проголосовать: не нравится

23.
Автор DNR, 11 месяцев назад, По-английски
Alternate solution for 2152-G (a cute use of HLD subtree queries) First, if you haven't read [this](https://codeforces.me/blog/entry/53170) blog, do so. Second, if you haven't immediately updated your HLD template to support subtree queries, do so. The problem trivially reduces to finding the number of nodes with value $1$ that have no other node with value $1$ in their subtree. Further, an update on node $u$ clearly corresponds to xoring the values for all nodes in the subtree of $u$ with $1$. Now, let's think of a slow solution for this problem. We define the following terms: - A node $u$ is "good" if no other node in its subtree has the value $a_u$. - $f_u(x)$ is the number of good nodes in the subtree of $u$, with value $x$. - $c_{u}(x)$ is the number of nodes in the subtree of $u$, with value $x$. Then the answer is clearly $f_{1}(1)$, and all values of $f$ and $c$ can be computed in $O(n)$ in the following manner: ``` dfs(u): c[u][a[u]] = 1 for v in adj[u]: dfs(v) for x in [0, 1]: f[u][x] += f[v][x] c[u][...
Lazy propagation here might be slightly non-trivial for some readers, so I'll try to explain the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +44
  • Проголосовать: не нравится

24.
Автор c0d3junki3, 13 лет назад, По-английски
Fenwick Tree Lazy Propagation Hello, I'd like to share a cool trick, i came across recently. No doubt some people will be familiar with this, but i believe many won't be, simply because when it comes to Lazy Propagation most people use segment trees in contest. This method, although not as flexible, is far simpler. Not to mention a lot easier to code with a lot less lines of code. Also while Fenwick Tree and Segment Tree have the same complexities, in practice Fenwick Tree is usually faster. Before we begin, I'd like to say that you should have at least a decent understanding of binary indexed trees (BITs). We know by now, that $BIT$ can be used to support following two operations: 1) $Query(i)$ &mdash; queries element at position $i$. 2) $Update(i, j, d)$ &mdash; adds $d$ to the elements from $i$ to $j$. Some people call this "range update, single query", what we would like to accomplish is "range Update, range Query". 1) $RangeQuery(i, j)$ &mdash; returns the sum from $i$ to $j$. 2) $RangeUp...
Fenwick Tree Lazy Propagation, familiar with this, but i believe many won't be, simply because when it comes toLazy Propagation most, Finally to put it all together here is how we are going to implement lazy propagation:

Полный текст и комментарии »

  • Проголосовать: нравится
  • +20
  • Проголосовать: не нравится

25.
Автор Enigma27, 7 лет назад, По-английски
Manthan, Codefest'19 Editorial ### [1208A &mdash; XORinacci](https://codeforces.me/contest/1208/problem/A) The sequence is $a$, $b$, $a\oplus b$, $a$, $b$, $a\oplus b$ $\cdots$ Since, the sequence has a period of $3$, $f[i] = f[i \mod 3]$. <br> <spoiler summary="Code"> ``` #include<bits/stdc++.h> using namespace std; int main() { int test,a,b,n; cin>>test; while(test--){ cin>>a>>b>>n; switch (n%3){ case 0: cout<<a<<endl; break; case 1: cout<<b<<endl; break; default: cout<<(a^b)<<endl; } } return 0; } ``` </spoiler> ### [1208B &mdash; Uniqueness](https://codeforces.me/contest/1208/problem/B) After removing a sub-segment, a prefix and a suffix remain, possibly of length $0$. Let us fix the prefix which does not contain any duplicate elements and find the maximum suffix we can get without repeating the elements. We can use map/set ...
lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +133
  • Проголосовать: не нравится

26.
Автор QCFium, 6 лет назад, По-английски
[Tutorial] Subtree lazy propagation on the link-cut tree The link-cut tree is a data structure that can maintain dynamic forest (that is, we can add/remove edges as long as the graph remains a forest) and handle various types of queries efficiently. It can handle not only path aggregation/update queries but also [subtree aggregation queries](https://codeforces.me/blog/entry/67637). Let's go further and try subtree lazy propagation ! Note that there is a limitation of the lazy propagation operator to be used in this link-cut tree trick : invertibility. For example, subtree add query meets this condition, but subtree bitwise-or update doesn't. Alternative ways ------------------ The top tree can perform subtree update queries quite naturally, without requiring invertibility, but it's a bit hard to implement and has a relatively big constant in running time. The euler tour tree can perform subtree update/aggregation queries efficiently but can't handle path queries. Terms ------------------ auxiliary tree : the splay tree used t...
[Tutorial] Subtree lazy propagation on the link-cut tree, ://codeforces.com/blog/entry/67637). Let's go further and try subtree lazy propagation !, Note that there is a limitation of the lazy propagation operator to be used in this link-cut tree

Полный текст и комментарии »

  • Проголосовать: нравится
  • +56
  • Проголосовать: не нравится

27.
Автор cadmiumky, история, 5 лет назад, По-английски
Infoleague Autumn 2021 Round 2 Division 1 Editorial [problem:103423A] ------------------ Idea and Solution: [user:Gheal,2021-11-20] <spoiler summary="Solution"> <spoiler summary="Subtask 1"> The basic naive approach would be to iterate through every subarray and naively check for each one if it is bordered. Time complexity: $O(N^3)$ </spoiler> <spoiler summary="Subtask 2"> All bordered subarrays are either constant, or begin with a $1$ and end with a $2$. The answer can be found in $O(N)$ with prefix sums. Time complexity: $O(N)$ </spoiler> <spoiler summary="Subtask 3"> Similarly to the first subtask, we'll iterate through every subarray. A subarray $[a_l,a_{l+1}, \ldots a_r]$ is bordered if $a_l \le min_{i=l}^r(a_i)$ and $ max_{i=l}^r(a_i) \le a_r$. Calculating $min_{i=l}^r$ and $max_{i=l}^r$ for every pair of indices $(l,r)$ can be solved via RMQ or via dp in $O(N^2)$. Time complexity: $O(N^2)$ </spoiler> <spoiler summary="Subtask 4"> $O(N \cdot \sqrt N)$ or inefficient $O(N log N)$ s...
This can be solved using a Segment Tree with lazy propagation.

Полный текст и комментарии »

Разбор задач Infoleague Autumn 2021 Round 2 Div. 1
  • Проголосовать: нравится
  • +30
  • Проголосовать: не нравится

28.
Автор PrinceOfPersia, история, 10 лет назад, По-английски
Codeforces Round #362 (Editorial) [Here](https://gitlab.com/amirmd76/cf-round-362/tree/master) is git repository to solutions of problems of this contest. ### Div.2 A You should check two cases for YES: 1. $x\ mod\ s = t\ mod\ s$ and $t \leq x$ 2. $x\ mod\ s = (t + 1)\ mod\ s$ and $t+1 < x$ ![ ](http://espresso.codeforces.com/72731d179aee0e03fb8a446ab4bb2d2c333953b9.png) Time Complexity: $\mathcal O(1)$ [Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/2A) ### Div.2 B Nothing special, right? just find the position of letters `.` and `e` with string searching methods (like `.find`) and do the rest. ![ ](http://espresso.codeforces.com/67436d52032041dc54647c27e506f956e344f5cb.png) Time Complexity: $\mathcal O(n)$ [Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/2B) ### A Do what problem wants from you. The only thing is to find the path between the two vertices (or LCA) in the tree. You can do this in $\mathcal O(lg(n))$ since the height of the tree is...
This can be done using the previous segment tree plus lazy propagation (an additional value in each

Полный текст и комментарии »

Разбор задач Codeforces Round 362 (Div. 1)
  • Проголосовать: нравится
  • +80
  • Проголосовать: не нравится

29.
Автор Xellos, 10 лет назад, По-английски
Indexed set / array with wide functionality: treap ~~~~~ const int * int const * int * const int const * const const int * function (const arg) const return void(l = r = 0); ~~~~~ [link to repo](https://gitgud.io/Xellos/treapset) **VERSION 2.0 RELEASED!** Now with 100% less memory leaks or MLE verdicts. Project moved from Github. _The following text is for version 1.0._ Based on the e-maxx implementation and other stuff I found online, I pieced together a powerful treap. It can be used as a set<>, array, segment tree or (within limits) all of them at once. Consider a set<> represented as a sorted array of distinct elements. You can insert/remove elements just like in a set<>. You can also find the index of any element in this array, remove an element by index &mdash; or insert an element at an index, but that will probably break the sortedness and you can't use the operations which rely on it anymore (you can still insert/remove elements by index). As long as the array is sorted, you can query lower bound / upper ...
(like min/max) or combined range updates (paint+add) like in a segment tree. Since we needlazy, (paint+add) like in a segment tree. Since we need lazy propagation, everything is immutable (you can

Полный текст и комментарии »

  • Проголосовать: нравится
  • +103
  • Проголосовать: не нравится

30.
Автор Shisuko, 9 месяцев назад, По-английски
2025 ICPC Asia Manila Regional (Gym) Editorial [problem:106262A] <spoiler summary="Hint"> There is only one way for the leftmost piece and the rightmost piece to refer to the same object. </spoiler> <spoiler summary="Solution"> If $n=0$, then Alice and Bob will not fight. Since they eat $2$ pieces at a time, that means $n=2, 4, 6, 8, 10, ...$ (i.e. the even numbers) will also have them not fight. If $n=1$, then Alice and Bob will fight over that once piece. Since they eat $2$ pieces at a time, that means $n=3, 5, 7, 9, 11, ...$ (i.e. the odd numbers) will have them fight. Since an equal number of pieces are eaten from the left and the right, we know it is the center piece that remains (when $0$-indexed, this is at index $\lfloor n/2 \rfloor$). So, the problem is just a parity check. </spoiler> [problem:106262B] <spoiler summary="Hint"> For some letter, how many times does this letter occur in the substring of $t$ that begins at position $i$ and has some length $\mathrm{len}$? You can answer this in $O(1...
This is a standard use of a segment tree with lazy propagation.

Полный текст и комментарии »

Разбор задач 2025 ICPC Asia Manila Regional
  • Проголосовать: нравится
  • +20
  • Проголосовать: не нравится

31.
Автор MarcosK, 3 года назад, По-английски
2022-2023 ICPC Latin American Regional Programming Contest — Unofficial editorial Hi everyone! The [2022-2023 ICPC Latin America Regional Programming Contest](https://codeforces.me/gym/104252) was held last weekend. Given that (as far as I know) there is no official editorial for the problems, I decided to create one. Please notice that, given that these are not the official solutions, there can be typos/mistakes in the explanations. Feedback is always appreciated :) I would like to thank [user:lsantire,2023-03-22] for reviewing the editorial and providing valuable feedback. Don't hesitate to reach out to me if you have any questions/suggestions. Thank you! [problem:104252A] <spoiler summary="Hint"> Think in which case a person loses money. Remember we can choose the order in which events happen. </spoiler> <spoiler summary="Solution"> Let's fix a person $p$ and call $a$ and $b$ to the people $p$ will ask for money. It's easy to see that $p$ loses money if $a$, $b$ and $p$ are asked for money before $p$ requests $a$ or $b$ to pay. This ...
/data_structures/segment_tree.html#range-updates-lazy-propagation) or even a [Fenwick tree](https://cp

Полный текст и комментарии »

  • Проголосовать: нравится
  • +120
  • Проголосовать: не нравится

32.
Автор hiddentesla, история, 6 лет назад, По-английски
ICPC Indonesia COMPFEST 12 Multi-Provincial Contest Online Mirror Editorial Hi everyone, sorry for the considerable delay. It turns out, we were exhausted yesterday from supervising two contests back-to-back. We are surprised by the number of participants in the online mirror. And I hope you enjoy the problems :) Our big surprise was problem B. We were setting it to be a medium problem. Turns out, maybe the observation is not that obvious. **fun fact:** Initially, we don't plan to have any particular naming theme other than the obligatory first letter matches the problem order. However, when naming 6 out of 9 problems, one of my committee member noticed that **5 problems** have A of B theme. So, we decided to continue using this theme. Here are the authors and first solvers for all problems: **A &mdash; Arena of Greed** Author: [user:julianfernando,2020-09-28] Expected difficulty: Medium Tag: greedy First solver: [user:kotamanegi,2020-09-28] **B &mdash; Blue and Red of Our Faculty!** Author: [user:dewa251202,2020-09-28], [user:...
Code (with lazy propagation): [submission:94152123], Code (without lazy propagation): [submission:94152055]

Полный текст и комментарии »

  • Проголосовать: нравится
  • +67
  • Проголосовать: не нравится

33.
Автор grecil, история, 4 месяца назад, По-английски
Blackboxing Lazy Segment Trees, the right way For the longest time, I only knew how to use the lazy segtree for Range Add / Range Sum queries. It would take me painstakingly long to solve problems which had lazy propagation in a slightly different form. I then discovered the [Atcoder Lazy Segment Tree template](https://atcoder.github.io/ac-library/production/document_en/lazysegtree.html) ([C++](https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp) / [Python](https://github.com/not522/ac-library-python/blob/master/atcoder/lazysegtree.py)), which would allow you to solve any Lazy Propagation problem by just defining 6 mathematical parameters: `S`, `op`, `mapping`, `composition`, `e` and `id`. This blog is an attempt to explain the math behind Lazy Propagation in an intuitive manner using Socratic dialogue. I would recommend that you guys ponder over the questions before you read the answers. **Prerequisites:** You know how a standard segment tree works. You know how to build it, how to perform point updates, ...
Blackboxing Lazy Segment Trees, the right way, The golden rule of lazy propagation is absolute: **You only push a tag, it to finally push the updates down? Define the golden rule of lazy propagation and the exact steps, would take me painstakingly long to solve problems which had lazy propagation in a slightly

Полный текст и комментарии »

  • Проголосовать: нравится
  • +21
  • Проголосовать: не нравится

34.
Автор SummerSky, 5 лет назад, По-английски
A little thought about segment tree with lazy propagation, inspired by three problems Recently, I have met three problems which all need segment tree with interval updating (lazy propagation). I did not solve any of them on my own, but got inspired a lot from their solutions. I would like to share some of my thought about the ideas behind these three problems. If you are learning segment tree as well, hope that this could help a little. Thought 1. It might seem from the first sight that the problem needs a huge number of interval updating, however it turns out that only O(N) or O(NlogN) is enough. 1) Problem https://codeforces.me/contest/438/problem/D. This problem asks to update an interval by module of some integer P while the query is to find the sum of any given interval. I really get stuck here. I think that, for any given interval, for the worst case, we have to deal with every element, and thus lazy propagation never works. However, there exists a wonderful trick! For any x and p(both positive integers), if p<=x, then x%p < x/2 holds, meaning that any el...
A little thought about segment tree with lazy propagation, inspired by three problems, element, and thus lazy propagation never works. However, there exists a wonderful trick! For any x and p, have to deal with every element, and thus lazy propagation never works. However, there exists a, interval, while lazy propagation saves complexity if the "updating information" could be represented, , where we could use an extra variable to store this integer, i.e., lazy propagation. But, this is, Recently, I have met three problems which all need segment tree with interval updating (lazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +31
  • Проголосовать: не нравится

35.
Автор oversolver, 5 лет назад, По-английски
[Tutorial] Fast and simple RSQ with range addition (not segment tree!) #### TL;DR: `range_sum_range_add` with only two BITs. Suppose we have (sub)task to proceed following queries: - `range_sum(l, r)` - `range_add(l, r, x)` Most familiar solution is segment tree with lazy propagation. And maybe you didn't knew, but such segment tree **does not needs pushes**! <spoiler summary="code of segment tree without pushes"> ~~~~~ template<class T> struct rsq_add_segt { explicit rsq_add_segt(size_t sz = 0, const T &val = 0) { for(d=1; d<sz; d<<=1); t.assign(d*2, {val, {}}); } rsq_add_segt(const vector<auto> &vals): rsq_add_segt(size(vals)) { for(size_t i=0; i<size(vals); ++i) t[i+d].first = vals[i]; for(size_t i=d; i-->1; ) t[i].first = t[i*2].first + t[i*2+1].first; } void add(size_t l, size_t r, const T &val) { if(l>=r) return ; _add(l, r, val, 0, d, 1); } T operator()(size_t l, size_t r) const { if(l>=r) return {}; return _calc(l, r, 0, d, 1); } private: size_t d; //t[i] = pair of #(su...
Most familiar solution is segment tree with lazy propagation. And maybe you didn't knew, but such

Полный текст и комментарии »

  • Проголосовать: нравится
  • +53
  • Проголосовать: не нравится

36.
Автор GM_Dan4Life, 23 месяца назад, По-английски
[Tutorial] Solving Range (Chmin, Chmax, Add, Assign) + Point queries Hi Codeforces! This is my first attempt at a tutorial blog XD. Disclaimer: No headaches occured during the making of this blog Problem statement ----------------- Given an integer array $A$ of length $n$ and $q$ of the following 5 types of queries: 1. For all $i \in [l,r]$, change $A_i$ to $\max(A_i, v)$ 2. For all $i \in [l,r]$, change $A_i$ to $\min(A_i, v)$ 3. For all $i \in [l,r]$, change $A_i$ to $A_i + v$ 4. For all $i \in [l,r]$, change $A_i$ to $v$ 5. Output $A_i$ - $ 1 \leq n,q \leq 10^6 $ - $ 1 \leq l \leq r \leq n $ - $ -10^9 \leq A_i, v \leq 10^9 $ The above is solvable with techniques like [Segment Tree Beats](https://codeforces.me/blog/entry/57319) in $\mathcal{O}(n+q\log^2{n})$, but as a binary search enthusiast, you didn't learn segment tree beats? Don't worry, here's an easier, faster, and shorter solution that solves this particular problem in $\mathcal{O}(n+q\log{n})$ Prerequisites ------------- You should know the following t...
distributive properties of $\max$ / $\min$ 3. Basics of a lazy propagation segment tree (not required for

Полный текст и комментарии »

  • Проголосовать: нравится
  • +100
  • Проголосовать: не нравится

37.
Автор nikgaevoy, 4 года назад, По-английски
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...
whatever the regular recursive segment tree with lazy propagation can do, but in time and space of the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +254
  • Проголосовать: не нравится

38.
Автор cadmiumky, 23 месяца назад, По-английски
Height-wise Small-to-Large Trick Hello Codeforces, I will present today, and in any day in the future, a means to correctly calculate a corner case of the well known small-to-large trick, and how this can be employed to solve a set of certain problems. This blog is written with encouragement from the [Month of Blog Posts](https://codeforces.me/blog/entry/133806) initiative. <spoiler summary="Forenote; Height definition"> The *height* of a node, as will be used throughout this blog, refers to the maximum distance in a rooted tree from a node to any of the leaves within its subtree. As a corollary, hereby it is considered that a leaf has a height of 1. </spoiler> ### The standard example. Let's try to solve the following problem: [Cat In a Tree, BOI 2017](https://oj.uz/problem/view/BOI17_catinatree). Although this problem can be solved employing some greedy algorithm, assume we have no idea what greedy is or how it could be correct, and revert to the basics: #### The standard DP. How can we formul...
latter illustrating very well an application of lazy propagation on such structures and its power

Полный текст и комментарии »

  • Проголосовать: нравится
  • +208
  • Проголосовать: не нравится

39.
Автор dragonslayerintraining, 7 лет назад, По-английски
Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2) Editorial [1209A &mdash; Paint the Numbers](https://codeforces.me/contest/1209/problem/A) ================== Author: [user:MikeMirzayanov,2019-09-14] Consider the smallest element $x$ in the array. We need to paint it in some color, right? Observe, that we can paint all elements divisible by $x$ in that color as well. So we can perform the following while the array is not empty: * find the minimum element $x$, * assign new color and remove all elements divisible by $x$ Complexity: $\mathcal{O}(n^2)$. [1209B &mdash; Koala and Lights](https://codeforces.me/contest/1209/problem/B) ================== Author: [user:FieryPhoenix,2019-11-28] Because each individual light flashes periodically, all the lights together are periodic as well. Therefore, we can simulate the lights up to the period to get the answer. The actual period can be calculated as follows: <spoiler summary="Spoiler"> * If a light toggles every $t$ seconds, its period is $2t$. * The overall per...
values in each node and do lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +124
  • Проголосовать: не нравится

40.
Автор pedriwnl, 2 месяца назад, По-английски
AtCoder Educational DP Contest Editorial (The Best DP Contest for Beginners) Hello, Codeforces! ------------------ ### Introduction Searching for editorials for this [contest](https://atcoder.jp/contests/dp) can be surprisingly annoying, since there is no official editorial on the AtCoder website. Because of this, my friends ([user:murkat,2026-07-08] and [user:GuilhermeKK,2026-07-08]) and I felt it was necessary to put together a unified guide all in one place. We essentially wanted to create the editorial we wish we had when we were first solving these problems! ### Who is this for? This contest covers all the fundamental DP techniques and optimizations. If you are not familiar with DP (and you definitely should be, since it is one of the most common topics in cp), the first few problems will be perfect for you to understand the reasoning behind it. If you know the basics of DP but feel like you are always one step away from finding the right state or transition, there are a lot of great problems here for you to practice. If you are looking for...
How to optimize it using Segment Tree? You will need lazy propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • +80
  • Проголосовать: не нравится

41.
Автор one_autum_leaf, история, 23 месяца назад, По-английски
Lazy Propogation with Xor range updates and range sum queries ### Problem Statement: You are given an array `arr` of size $N$. Initially, all $arr[i]$ are set to 0. Now consider $Q$ queries, where each query is of one of the following two types: 1. **\[1, l, r\]:** In this case, calculate the sum of values of $arr[i]$ for $l \le i \le r$. 2. **\[2, l, r, x\]:** In this case, for each $arr[i]$, $l \le i \le r$, update the value to $arr[i] = arr[i] \oplus x$ (where $\oplus$ is the XOR operation). ### Constraints: 1. $ 1 \le N \le 10^5 $ 2. $ 1 \le Q \le 10^5 $ 3. $ 1 \le l \le r \le N $ 4. $ 1 \le x \le 2^{30} - 1 $ Problem Link &mdash; [problem:242E] --- ### Approach: This problem can be solved easily with a Segment Tree with Lazy Propagation, had there been no XOR updates. Lazy Propagation requires that for an update on range $[l, r]$, we should be able to calculate the value of $[l, r]$ after the update in $O(1)$ time (or at least sub-linear time like $O(\log n)$). For other updates, say multiply by $x$, this would b...
Lazy Propogation with Xor range updates and range sum queries, Lazy Propagation, had there been no XOR updates. Lazy Propagation requires that for an update on, This problem can be solved easily with a Segment Tree with Lazy Propagation, had there been no XOR, Thus, we can build a segment tree with lazy propagation for this array.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

42.
Автор AlexLuchianov, 4 года назад, По-английски
[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...
does sound a lot like segment tree with lazy propagation...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +278
  • Проголосовать: не нравится

43.
Автор kartik8800, история, 5 лет назад, По-английски
Range query data structures Hello Codeforces! It's been a while since I contributed something useful to the CF community. So here I am trying my best to make some high quality lectures on range query data structures! For trying out some range query problems: [head to cses range query section](https://cses.fi/problemset/)<br> For solutions: [my previously written cf blog](https://codeforces.me/blog/entry/77128)<br> Video Series for range query DS ================== Range Query Problems and Data Structures ------------------ Video link: [https://youtu.be/8wJzUFZOqK4](https://youtu.be/8wJzUFZOqK4)<br> Welcome to the series on Range Query data structures and problems!! In this video we will discuss:<br> 1. What are range query problems?<br> 2. Types of Range query problems.<br> 3. Online queries vs offline queries.<br> 4. point updates and range updates.<br> 5. Common Range Query Data Structures for efficiently solving these problems.<br> Prefix Arrays ------------------ Video lin...
1. Mo's algorithm over arrays and trees. 2. Segment trees with/without lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +110
  • Проголосовать: не нравится

44.
Автор bhikkhu, 12 месяцев назад, По-английски
BUMP: Super lean lazy Fenwick tree with auto tests I have polished my implementation after ten long days of refactoring and minimizing the number of variables required to keep track of each action. I added hardcore random numbers tests to tally results against brute force verifier. I have tested it against a dozen problems. It's a continuous process. Please just run the program it will automatically test against the brute force algorithm for range update and queries. The code should be extremely easy to understand from what it was ten days ago. The rest of logic is just propagation of lazy values from top to the bottom of the intervals. Solution for below CSES https://pastebin.com/Tnr0f5PF https://cses.fi/alon/task/1651 <spoiler summary="Fenwick tree with lazy propagation "> ~~~~~ #include <iostream> // For cin, cout #include<cassert> #include <vector> // For vector container #include <tuple> // For tuple #include <random> // For mt19937 and uniform_int_distribution #include <chr...

Полный текст и комментарии »

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

45.
Автор whatthemomooofun1729, история, 3 года назад, По-английски
multiplication and addition range updates using lazy propagation Hi, I'm trying to solve a problem I just gave myself using lazy propagation and segment tree. Essentially, we have some queries on an array, where each query consists of two integers $L$ and $R$, and we are supposed to update the array by multiplying each element in the range by $2$, and then adding $1$ to every element. Every element a[i] within the range becomes 2 * a[i] + 1. For each query, we just print the sum of all elements. Let N be the number of elements, A be the array. So, for this test case: N = 5. A = {1, 2, 3, 4, 5}. 1 Query: [L, R] = [1, 2] The answer should be 20, but my code prints 19. Here is my attempt: <spoiler summary="Code"> ~~~~~ int N; vi t, a, laz1, laz2; // laz1 stores the aggregate of the multiplications // laz2 stores the aggregate the additions void build(int u, int l, int r) { if (l == r) { t[u] = a[l]; } else { int mid = (l + r)/2; build(2 * u, l, mid); build(2 * u + 1, mid+...
multiplication and addition range updates using lazy propagation, Hi, I'm trying to solve a problem I just gave myself using lazy propagation and segment tree, void addd(int u) { // lazy propagation for additions laz2[2 * u] += laz2[u]; laz2[2 * u, void multiply(int u) { // lazy propagation for multiplication laz1[2 * u] *= laz1[u

Полный текст и комментарии »

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

46.
Автор Xellos, 12 лет назад, По-английски
Codeforces Trainings Season 2 Episode 8: Editorial [Complete problemset + tests + original presentation of solutions.](http://www.bapc.eu/problemset.zip) [Official scoreboard](http://bapc.eu/scoreboards/bapc/), [public contest scoreboard](http://www.bapc.eu/scoreboards/public/), [used for training elsewhere](http://www.cs.ubc.ca/~acm-web/practice/2014-10-25/scores.php). Short hints first, more detailed solutions afterwards. ### A. Avoiding the Apocalypse (difficulty: medium-hard, [code](http://ideone.com/JQOMyq)) Maxflow in a suitably selected graph. Ford-Fulkerson is sufficient. <hr> The vertices of our graph need to correspond to states that one person can be in when traversing the original road network; the number of people moving in a group is then represented by flow along edges. Therefore, the most natural choice is to use vertices corresponding to states (location, time). The rules from the problem statement say that at most $c$ people can move along an edge $e=(u->v)$ in the original at any time. That me...
maximum belonged to. Lazy propagation is a standard thing, so I won't describe the tree here, but

Полный текст и комментарии »

  • Проголосовать: нравится
  • +116
  • Проголосовать: не нравится

47.
Автор Wind_Eagle, история, 4 года назад, По-русски
Divide and conquer. Dynamic connectivity offline and DP optimization. Divide and conquer by queries. Hello, Codeforces! I have wanted to write an educational blog for a long time, but I couldn't find a topic for it. And recently I remembered that Codeforces doesn't have a good blog on one of my favorite topics: the "divide and conquer" technique. So I want to talk about it. The outline will be something like this: 1) Divide and conquer. What this technique is and what it is for. Example. 2) Dynamic connectivity offline with divide and conquer. Divide and conquer dp optimization. 3) Let me tell you about a method I invented myself: divide and conquer by queries. In this case, we divide not only the array, but also the queries into groups. So, here we go. First, about what this technique is. The point is about the following: let's say we have an array. Then, if we know how to calculate the answer for two parts of it, and if we know how to get the answer for the whole array from the answers of two parts, we can apply the divide and conquer technique. Let me show you the si...
without the lazy propagation. So what did we end up with? You can see that now the segment [l ... r

Полный текст и комментарии »

  • Проголосовать: нравится
  • +93
  • Проголосовать: не нравится

48.
Автор arthur_9548, 10 месяцев назад, По-английски
Editorial: XIII UnB Contest Mirror We hope everyone enjoyed the problems of [contest:106159]! This editorial contains the description of the solutions and their implementation. Feel free to discuss them in the comments! #### Problem A - Author: [user:PedroPacoca,2025-11-05] - Coauthor: [user:duduFreire,2025-11-05] <spoiler summary="Solution"> In this problem, we want to count the number of strings of length $n$ that have at least one occurrence of the given substring. To do this, we will use the Knuth-Morris-Pratt (KMP) algorithm and the automaton constructed from it, with a complexity of $O(m)$. If $n$ were small, we could solve this problem using dynamic programming, calculating, for each $1 \leq i \leq n$, how many ways we can reach state $0 \leq j \leq m$ of the automaton (representing a string with the last $j$ characters equal to the first $j$ of $s$). This solution has $n \cdot m$ states with transitions of the size of the alphabet, resulting in a time complexity of $O(26 \cdot n \cdot m)$, which is...
persistent segment tree (segtree), sparse, and with lazy propagation.

Полный текст и комментарии »

Разбор задач XIII UnB Contest Mirror
  • Проголосовать: нравится
  • +13
  • Проголосовать: не нравится

49.
Автор RetiredAmrMahmoud, 11 лет назад, По-английски
Codeforces Round #312 (Div. 2) Editorial [problem:558A] ------------------ Let's divide all the trees into two different groups, trees with a positive position and trees with a negative position. Now There are mainly two cases: 1. If the sizes of the two groups are equal. Then we can get all the apples no matter which direction we choose at first. 2. If the size of one group is larger than the other. Then the optimal solution is to go to the direction of the group with the larger size. If the size of the group with the smaller size is $m$ then we can get apples from all the $m$ apple trees in it, and from the first $m + 1$ trees in the other group. So we can sort each group of trees by the absolute value of the trees position and calculate the answer as mentioned above. **Time complexity:** $\operatorname{}O (n\ log\ n)$ [**Implementation**](http://ideone.com/3zzpsd) [cut] . [problem:558B] ------------------ First observation in this problem is that if the subarray chosen has $x$ as a value tha...
. We will have to use lazy propagation technique for updating ranges.

Полный текст и комментарии »

Разбор задач Codeforces Round 312 (Div. 2)
  • Проголосовать: нравится
  • +96
  • Проголосовать: не нравится

50.
Автор skywalkert, история, 7 лет назад, По-английски
2018 CMUT BeihangU Contest, Editorial This editorial corresponds to [contest:102114] (stage 5), which was held on Aug 6th, 2018. Moreover, this problem set was also used as Jingzhe Tang Contest 1 in Petrozavodsk Winter Camp on Jan 30th, 2019. **This post is now finished**, in which I try to elaborate on notes, solutions and maybe some data generating. Alternatively, you can refer to [an old published material](https://drive.google.com/file/d/1CFumWbNLTUEywkVDNF-LKT3SzYd1r15L/view), though I think the old English version did not explain something clearly. --- [problem:102114A] This problem requires to calculate $s$-$t$ min cut between any two vertices on a weighted cactus graph having $n$ vertices, denoted by $\mathrm{flow}(s, t)$. You need to report $\sum_{s < t}{(s \oplus t \oplus \mathrm{flow}(s, t))}$. $n \leq 10^5$, $\sum{n} \leq 10^6$, weights are $\leq 10^9$. Try to find some features of this graph. <spoiler summary="solution"> By contradiction, we can prove that for an undirected graph, each ed...
problem offline. We can build a sparse table to postpone changes like **lazy propagation** on segment

Полный текст и комментарии »

  • Проголосовать: нравится
  • +79
  • Проголосовать: не нравится

51.
Автор brunomont, история, 6 лет назад, По-английски
[Tutorial] A powerful representation of integer sets Hello, Codeforces! This blog is heavily inspired by [user:TLE,2020-10-22]'s blog [using merging segment tree to solve problems about sorted list](https://codeforces.me/blog/entry/49446). I don't know exactly how well known this data structure is, but I thought it would be nice to share it anyway, along with some more operations that are possible with it. What it can do ------------------ We want a data structure that we can think of a set/multiset of **non-negative integers**, or even as a sorted array. We want to support all of the following operations: 1. Create an empty structure; 2. Insert an element to the structure; 3. Remove an element from the structure; 4. Print the $k$'th smallest element (if we think of the structure as a sorted array $a$, we are asking for $a[k]$); 5. Print how many numbers less than $x$ there are in the set (similar to lower_bound in a std::vector); 6. Split the structure into two: one containing the $k$ smallest elements, and the other ...
$ maps to $u \cdot v$); 3. Using lazy propagation and possibly modifying the merge function, it is

Полный текст и комментарии »

  • Проголосовать: нравится
  • +338
  • Проголосовать: не нравится

52.
Автор Errichto, 6 недель назад, По-английски
Harbour.Space IOI Camp 2026 - [2022 recordings](https://www.youtube.com/playlist?list=PLg_Krngrs0eC_1vn0dTjyPZMkwBOcVsgH) &mdash; CEOI 2016, CEOI 2017, CEOI 2022, optimization problems, segment tree nodes - [2023 recordings](https://www.youtube.com/playlist?list=PLg_Krngrs0eAN_QrR5MKnaZROHVSCaQiL) &mdash; POI 2019, POI 2022, CEOI 2018, graphs - [2024 recordings](https://www.youtube.com/playlist?list=PLg_Krngrs0eCfvefczNWB-c-Af3BUSH0x) &mdash; POI 2016, POI 2019 mix, POI 2023, IOI 2014, lazy propagation, sweep line, partial dp/bfs (Bombs) - [2025 recordings](https://www.youtube.com/playlist?list=PLLnK7ZZWZ74k) &mdash; POI 2018, IOI 2015, CEOI 2019, Convex Hull Trick Hi! I'm running an online IOI camp for the fifth time. This edition is sponsored by Harbour.Space Institute of Technology. It's free for IOI participants and coaches. We also accept participants of regional olympiads like APIO, EGOI, BOI and CEOI 2026. Every day will be a 5-hour virtual contest, the problem analysis, and sometimes a lecture. ...
-c-Af3BUSH0x) — POI 2016, POI 2019 mix, POI 2023, IOI 2014, lazy propagation, sweep line

Полный текст и комментарии »

  • Проголосовать: нравится
  • +138
  • Проголосовать: не нравится

53.
Автор THE_FOOL_ON_THE_GREY_FOG, история, 7 месяцев назад, По-английски
Bahnasy Tree [cut] ** بسم الله والحمدلله والصلاة والسلام على رسول الله ** Bahnasy Tree ================== **GitHub Repository:** [Bahnasy-Tree](https://github.com/Mostafa-Bahnasy/Bahnasy-Tree) Bahnasy Tree is a dynamic tree that represents a **sequence of length $N$** (positions $1..N$). It is controlled by two parameters: - $T$ ( **threshold** ): the maximum fanout a node is allowed to have before we consider it "too wide". - $S$ ( **split factor** ): used when splitting; computed from the node size using the smallest prime factor (SPF). If $S > T$, we fallback to $S = 2$. The tree supports the usual sequence operations (find by index, insert, delete) and can be extended to support range query / range update by storing aggregates (sum, min, etc.) and optionally using lazy propagation. --- ## 1) Node meaning and the main invariant Each node represents a contiguous block of the sequence. If a node represents a block of length `sz`, then its children partition this block into...
lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +92
  • Проголосовать: не нравится

54.
Автор UnexpectedValue, 18 месяцев назад, По-английски
[Tutorial] A New Perspective on Numbers and Operators: Introducing Group Theory We often start our mathematical journey with counting, primes, and basic arithmetic. Then we encounter modular arithmetic, with its intriguing properties and theorems like Euclid's algorithm and the Chinese Remainder Theorem. But what if there's a deeper, more abstract framework that ties all these concepts together? You might have encountered hints that group theory is behind some clever algorithms and data structures ([like this comment suggests](https://codeforces.me/blog/entry/103174?#comment-915676)). But if you've tried to learn about it, you might have found resources that felt either too abstract and disconnected from your existing knowledge ([for instance](https://zhtluo.com/cp/from-burnside-to-polya-a-short-introduction-to-group-theory.html)), or too intimidating and complex ([like this one](https://codeforces.me/blog/entry/91731)). This blog aims to bridge that gap. We'll start with familiar ground in discrete math and modular arithmetic, and then progressively in...
/course/2/lesson/4), require operations to be associative. Lazy propagation is used to handle non

Полный текст и комментарии »

  • Проголосовать: нравится
  • +93
  • Проголосовать: не нравится

55.
Автор karock, 10 месяцев назад, По-английски
Coding Track NITSHACKS 8.0 Editorial Thank you everyone for participating!<br> Here's the <a href="https://codeforces.me/blog/entry/148539">Blog Link</a> and <a href="https://codeforces.me/contestInvitation/bf7862176fe66f9655deac0d350e142a848b624a">Contest Link</a> <br> <h3><a href="https://codeforces.me/gym/652259/problem/A">A. AntiDitto Arrays! </a></h3> <p>Idea and Prepared by: [user:itsiftikar02,2025-11-23]</p> <spoiler summary="Hint 1"> The final array will be the form of either $1010101...$ or $0101010...$ </spoiler> <spoiler summary="Hint 2"> $x^1 + x^2 + x^3 + ... + x^{n - 1} < x^n$ $\forall$ $x \ge 2$ </spoiler> <spoiler summary="Solution"> **Case $x = 1$:** we will calculate the cost for both $101010...$ and $010101...$. Then minimum of this cost will be the answer. **Case $x \ge 2$:** For other value of $x$, it will always optimal not to change the value of $a_n$. if $a_n = 1$ then the final array will be $.....0101$ and if $a_n = 0$ then the final array will be $.....1010$ </...
*Data Structure:* Use a *Segment Tree* with Lazy Propagation to handle:

Полный текст и комментарии »

  • Проголосовать: нравится
  • +22
  • Проголосовать: не нравится

56.
Автор bobr_babizon, 2 года назад, По-русски
Translation of the article by ko_osaga on Kinetic Segment Tree. I hear a lot about this topic but could not find any resources in Russian or English, so I decided to translate an article by [user:ko_osaga,2024-06-13]. This translation may contain many inaccuracies, and it lacks the links available in the original article. This article presents a new segment tree, called the Kinetic Segment Tree. An element is considered Kinetic if it moves over time, i.e., if the element represents a linear or polynomial function. Segment trees are often found in competitions, as are Kinetic elements (e.g., the convex hull trick), so studying their combination can also be useful. It is also worth noting that Kinetic properties can be identified even in problems not directly related to Kinetic elements (e.g., using CHT in DP optimization), and consider how the Kinetic Segment Tree can be applied. This data structure has already been mentioned in articles on Codeforces, but I recently found time for a more thorough study. At the time of writing, the Kinetic ...
segment queries that cannot be solved by regular lazy propagation. It is a type oflazy propagation, обрабатывается с помощью Lazy propagation. Если наивное решение из-за операции heaten не, $, this segment is processed using Lazy propagation. If the naive solution due to the heaten

Полный текст и комментарии »

  • Проголосовать: нравится
  • +54
  • Проголосовать: не нравится

57.
Автор EbTech, история, 7 лет назад, По-английски
Generalizing Segment Trees with Rust This blog post outlines the design of a very general data structure for associative range queries, in the Rust programming language. In the "real world", self-balancing binary search trees can be augmented to handle a variety of range queries. However, for contest problems, statically allocated variants are much easier to code and usually suffice. The contest community has come to know these data structures as _segment trees_. Here, I will generalize most of the segment trees that you can find in the wild into one polymorphic data structure, that can easily be copy-pasted during online competitions. I will call it an _ARQ tree_. ARQ is pronounced "arc", which has a similar meaning to "segment", but also stands for "Associative Range Query". It supports highly customizable range queries, the main requirement being that the aggregation operation must be _associative_. ### Associativity and Semigroups We begin with an array $a_0, a_1, a_2, \ldots, a_{n-1}$. Each $a_i$ belongs to...
lazy propagation, which I like to call an ARQBIT. It's more heavy-weight than a standard BIT, but

Полный текст и комментарии »

  • Проголосовать: нравится
  • +112
  • Проголосовать: не нравится

58.
Автор oml1111, история, 4 года назад, По-английски
Introducing Algoteka Hello people of Codeforces! I'd like to introduce a website I've been working on and that I'm hoping to grow into something bigger: [algoteka.com](https://algoteka.com/) In essence, it's a site for submitting code samples that solve various problems and for finding code snippets in the language and technology stack you want for your problem (and possibly compare different approaches). We are planning to grow and monetize this site, and to compensate our content submitters appropriately for the value they bring. To start out, I decided to populate it with a lot of the algorithms I've used myself in competitive programming, for instance: **Data structures:** * [Heap](https://algoteka.com/samples/31/heap-c-plus-plus-raw%252C-commented-implementation) (and the [STL implementation](https://algoteka.com/samples/8/heap-c-plus-plus-using-the-stl-priority_queue)) * [Fenwick Tree](https://algoteka.com/samples/10/fenwick-tree-c-plus-plus-readable-implementation) * [Segment Tree](...
-templated-implementation) * [Lazy Propagation Segment Tree](https://algoteka.com/samples/12/lazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +48
  • Проголосовать: не нравится

59.
Автор Errichto, 14 месяцев назад, По-английски
Huawei IOI/EGOI/CEOI/etc. Camp 2025 [registration started] - [2022 recordings](https://www.youtube.com/playlist?list=PLg_Krngrs0eC_1vn0dTjyPZMkwBOcVsgH) &mdash; CEOI 2016, CEOI 2017, CEOI 2022, optimization problems, segment tree nodes - [2023 recordings](https://www.youtube.com/playlist?list=PLg_Krngrs0eAN_QrR5MKnaZROHVSCaQiL) &mdash; POI 2019, POI 2022, CEOI 2018, graphs - [2024 recordings](https://www.youtube.com/playlist?list=PLg_Krngrs0eCfvefczNWB-c-Af3BUSH0x) &mdash; POI 2016, POI 2019 mix, POI 2023, IOI 2014, lazy propagation, sweep line, partial dp/bfs (Bombs) Hi! For a fourth time, I'm organizing an online IOI camp sponsored by Huawei. It's free for IOI participants and coaches. **UPDATE**: we will accept participants of regional olympiads too (from this year, so e.g. BOI/EGOI/CEOI/APIO 2025)! Every day will be a 5-hour virtual contest, the problem analysis, and sometimes a lecture. - Dates: 17-23.07 (6 training days; Sunday off) - Contests: IOI 2015, POI 2024 and something else from POI/BOI/CEOI - **[EDIT]** Registration: Y...
-c-Af3BUSH0x) — POI 2016, POI 2019 mix, POI 2023, IOI 2014, lazy propagation, sweep line

Полный текст и комментарии »

  • Проголосовать: нравится
  • +92
  • Проголосовать: не нравится

60.
Автор pcheloveks, история, 10 месяцев назад, По-русски
Dsu with lazy propagation Трюк для DSU (disjoint set union), с которым я недавно столкнулся: У нас есть элементы, над которыми нужно выполнять два типа запросов: 1. Union — объединить множества, содержащие элементы v1 и v2. 2. Add — для всех i в множестве, содержащем элемент v, прибавить некоторое значение x к a[i]. Чтобы поддерживать это эффективно, можно хранить неявные модификации в вершинах — аналогично ленивым обновлениям (lazy propagation) в дереве отрезков, но без явной передачи изменений вниз. При запросе Add мы находим корень дерева, содержащего вершину v, и добавляем модификацию в этот корень. Когда нужно получить реальное значение a[i], мы сначала выполняем сжатие пути к корню и применяем модификации от корня. Во время сжатия пути (в процессе рекурсивного переподключения вершин) мы также применяем модификацию родителя к текущей вершине. Для операции Union можно действовать двумя способами: 1. Создать новую виртуальную вершину, которая станет родителем обоих компонентов. 1. Прикр...
Dsu with lazy propagation, efficiently, we can store implicit modifications in the nodes, similar to lazy propagation in a segment, ленивым обновлениям (lazy propagation) в дереве отрезков, но без явной передачи изменений вниз., To support this efficiently, we can store implicit modifications in the nodes, similar tolazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +34
  • Проголосовать: не нравится

61.
Автор Thunder8971, 16 месяцев назад, По-английски
[TUTORIAL] Building Segment Trees Iteratively: A Step-by-Step Guide # Building Segment Trees Iteratively: A Step-by-Step Guide This blog aims to explain a simple iterative segment tree that is easy to memorize due to its step-by-step approach while remaining efficient. This segment tree is designed for competitive programming contests that do not allow templates but still require this technique to be implemented quickly. # Introduction The segment tree is a data structure that enables range queries with updates. In this blog, I will demonstrate how to construct an iterative segment tree with this approach to solve the following operations: 1. Query the minimum value in a range. 2. Add a given value to each element in a range. ## Step 1: Preparations To begin, we need to adjust the size of the given array. For instance, if the array is named $A$ and has a size $N$, we must find the smallest power of $2$ greater than or equal to $N$. This adjustment is possible because the additional values we append to $A$ will never be accessed. To a...
implementing lazy propagation for range updates. The iterative approach presented here is designed to be, problem, we will use the lazy propagation technique, which involves placing an update tag and updating, updates with lazy propagation., ## Step 4: Adding Lazy Propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

62.
Автор UshanGhosh, 2 года назад, По-английски
Editorial of ShellBeeHaken Presents Intra SUST Programming Contest 2024 — Replay Kindly click the invitation link to access the problems. Contest Invitation : **[ShellBeeHaken Presents Intra SUST Programming Contest 2024 &mdash; Replay](https://codeforces.me/gym/105198)** **[problem:105198A]** Ideas : [user:Youkn0wwho,2024-06-11], [user:Raiden,2024-06-11], [user:UshanGhosh,2024-06-11] <br>Prepared : [user:UshanGhosh,2024-06-11] <spoiler summary="Hint1"> Think about the contribution of each bit to the answer. </spoiler> <spoiler summary="Hint2"> Does all bit contributes equally? </spoiler> <spoiler summary="Solution"> Each bit of $x$ contributes equally to the answer. When does a bit contribute? A bit contributes to the answer if and only if the bit remains set till reaching $0$ depth, *i.e.* $f(0, x)$. If you reset a bit in any depth, it won't contribute to the answer anymore. So for each bit, you have a total $k + 1$ option, reset the bit in any depth from $k - 1$ and $0$, for which it has $0$ contributions, or keep it set till the end,...
To flip a segment, multiply with $-1$ in the array using a segment tree with lazy propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • +13
  • Проголосовать: не нравится

63.
Автор arthur_9548, 4 месяца назад, По-английски
Editorial: VII UnBalloon Contest We hope everyone enjoyed the problems of [contest:106523]! This editorial contains the description of the solutions and their implementation. Feel free to discuss them in the comments! #### Problem A - Idea: [user:lucassala,2026-05-17] - Preparation: [user:lucassala,2026-05-17] <spoiler summary="Solution"> This is a classic problem where we can solve the queries offline. First, we receive all the queries, calculate the response for each node, and then respond. To calculate the response for each node, we will perform a DFS starting at vertex $1$ and create a map where we maintain the frequency of each color along the path from the root to the current node in the DFS. When we enter a new vertex, we add $1$ to the frequency of the current vertex's color in the map, and when we leave that node, we subtract $1$ from that color's frequency. Furthermore, we must ensure that all colors in the map have a positive frequency, removing any colors that reach a frequency of $0$ from the map...
We can build a segment tree with lazy propagation, in which each position corresponds to a segment

Полный текст и комментарии »

Разбор задач VII UnBalloon Contest Mirror
  • Проголосовать: нравится
  • +23
  • Проголосовать: не нравится

64.
Автор IcpcHelwan, 3 года назад, По-английски
Contest Without tests :)) #### We would like to thank everyone who contributed to this contest, whether by providing ideas or participating in solving the problems. - [user:MUZAN,2025-02-08] - [user:TANJIR0U,2024-12-10] - [user:detective...dots,2024-01-31] - [user:ZAYAN,2024-01-31] - [user:Uchiha_Ouda,2024-01-31] - [user:jimy_26,2024-01-31] - [user:gom3a_,2025-02-08] #### And we also want to thank those who tested the problems. - [user:Ali_Azzam,2024-01-31] - [user:ahmedalaa22,2024-02-03] - [user:opop1omar,2024-01-31] - [user:Ahmed_JS,2024-01-31] [A &mdash; Free Palestine](http://codeforces.me/group/rjUbMTacuS/contest/500816/problem/A) ------------------ Idea: [user:gom3a_,2025-02-08] <spoiler summary="Hint"> How many numbers are there from $1$ to $3$? </spoiler> <spoiler summary="Tutorial"> You simply calculate $end - start + 1$. </spoiler> <spoiler summary="Solution (gom3a_)"> ~~~~~ /* " أَمْ حَسِبْتُمْ أَن تَدْخُلُوا الْجَنَّةَ وَلَمَّا يَأْتِكُم مَّثَلُ الّ...
The topic used is [Lazy Propagation in Segment Tree](https

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

65.
Автор roll_no_1, 7 лет назад, По-английски
Compilation Error: "Compiled file is too large" and A way to deal with it This post elaborates on what is written in the title. So, it may not be relevant to many people. But if you get this kind of error someday on codeforces, this post may be helpful for you. **TL;DR:** _If you get this kind of an error, check to see if you are initializing a global array with a non-default value. If that's the case, move the piece of code doing the initialization inside the main function, or just replace the array with a vector._ A few days back, I was solving a problem with $N \le 10^6$. I thought of using lazy propagation to solve it. For this, I used my own template of lazy propagation. But, after coding the solution to the problem, I realized that the compilation of the source file was taking too much time on my laptop. So, I tried to use the custom invocation feature of codeforces. But amazingly, to my surprise, I got a compilation error like this: _Invocation failed [COMPILATION_ERROR]_ _Can't compile file:_ _Compiled file is too large [34412820 by...
for lazy propagation., with $N \le 10^6$. I thought of using lazy propagation to solve it. For this, I used my own template, A few days back, I was solving a problem with $N \le 10^6$. I thought of using lazy propagation to, Then, I remembered that once I tried using my lazy propagation template on some problem and got an

Полный текст и комментарии »

  • Проголосовать: нравится
  • +43
  • Проголосовать: не нравится

66.
Автор ngk_manh, история, 5 лет назад, По-английски
A simpler way to understand Li-Chao tree _Hi codeforces!_ _I was trying to learn about Li-Chao tree by some blog which i can find on gg (codeforces included). But there still some issue i was encountered while I trying to understood Li-Chao tree._ _Fortunately! I found that there's a simpler way to understand LC tree by thinking about another approach._ _So, I decide to write this blog for two reason :_ - _Archive_ - _Sharing_ _If you feel interesting about this topic, welcome!_ Prerequisite : ============== Did you read one of two blog ? : - https://robert1003.github.io/2020/02/06/li-chao-segment-tree.html - https://cp-algorithms.com/geometry/convex_hull_trick.html ### I.Which issue that me (or maybe someone) stuck in Li-Chao tree? These question are main motivation : - Why node on $Li-Chao$ $tree$ only store one line that is $min/max$ at point $mid$ which $mid$ is the middle point in segment $[L, R]$ which current node manage? - Why in $Query$ function we get $max$ result on way from root t...
Because $(**)$ then we also need a segment tree to range update (lazy propagation is recommend

Полный текст и комментарии »

  • Проголосовать: нравится
  • +87
  • Проголосовать: не нравится

67.
Автор SummerSky, 9 лет назад, По-английски
Notes on Codeforces Beta Round #99, A, B, C, D, E (Segment tree with lazy propagation) [problem:139A] We can first calculate the total number of pages that can be finished within one week. Then, we divide the total number of pages by this number and obtain the residual. Finally, for this residual, we find the last day on which the whole book is finished. [problem:139B] The description seems a little difficult to understand... We should first rotate the wall papers with 90 degrees so that the stripes are vertical. Then, we cut it into as many pieces as possible according to the height of the room. Next, we compute the total length that these pieces can cover, and finally obtain the number of rolls that is necessary to decorate the whole room. [problem:139C] A straightforward implementation problem, but one needs take care of “corner” cases. [problem:139D] This is in fact an exhaustive search problem. At first, we enumerate the number of 0s at the end. Then, we enumerate all the combinations of the first sum that is equal to 10, counting from rig...
Notes on Codeforces Beta Round #99, A, B, C, D, E (Segment tree with lazy propagation), practice segment tree with lazy propagation. One can find a lot of materials on the Internet about this, I think this is a very nice problem to practice segment tree with lazy propagation. One can find a

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

68.
Автор mkrjn99, история, 11 лет назад, По-английски
Manthan, Codefest 16: Editorials **Problem A: Ebony Ivory** The problem is to find if there exists a solution to the equation: $ ax+by=c $ where x and y are both positive integers. The limits are small enough to try all values of x and correspondingly try if such a y exists. The question can also be solved more efficiently using the fact that an integral solution to this problem exists iff $ gcd(a,b) | c $. We just have to make one more check to ensure a positive integral solution. Complexity: $ O(log(min(a,b)) $ **Problem B: A Trivial Problem** We know how to calculate number of zeros in the factorial of a number. For finding the range of numbers having number of zeros equal to a constant, we can use binary search. Though, the limits are small enough to try and find the number of zeros in factorial of all numbers of the given range. Complexity: $ O(log(n)^2) $ **Problem C: Spy Syndrome 2** The given encrypted string can be reversed initially. Then $ dp[i] $ can be defined as the index at which...
popularly called as “Mo’s algorithm”. Apart from that, segment tree(with lazy propagation) has to, their value modulo $m$ is a prime. Since, $m \le 1000 $, we can build a segment tree(withlazy

Полный текст и комментарии »

Разбор задач Manthan, Codefest 16
  • Проголосовать: нравится
  • +21
  • Проголосовать: не нравится

69.
Автор Hexagons, 23 месяца назад, По-английски
OMORI CONTEST Editorial Thank you for joining the [contest](https://codeforces.me/contestInvitation/fc8da6d6845e77adc452e754d3d84c1086148c59) &#128522;. <spoiler summary="How did you find the contest?"> - Great - Good - Average - Bad - Trash </spoiler> <spoiler summary="Which problem is your favourite?"> - SUNNY - AUBREY - HERO - KEL - MARI - BASIL - OMORI </spoiler> #### [A. SUNNY](https://codeforces.me/gym/551481/problem/A) <spoiler summary="Editorial"> <spoiler summary="Problem Tags"> `bijections` `dynamic-programming` </spoiler> <spoiler summary="Hint 1"> Try to find a bijection, meaning try to find another problem such that its solution is equivalent to the original problem but is easier to solve. </spoiler> <spoiler summary="Hint 2"> Try to notice what happens to the difference array of $a$ when Sunny plays a note. </sp...
+ 1, \text{Current }l]$ with value $p^{x-v}$ using a technique called [lazy propagation](https://cp

Полный текст и комментарии »

Разбор задач OMORI CONTEST
  • Проголосовать: нравится
  • +133
  • Проголосовать: не нравится

70.
Автор peacebringer167, история, 2 года назад, По-английски
My first problem. Hello everyone, As the title suggests, this is my first problem on Codeforces, and it's a medium to medium-hard challenge. I'm preparing this because I'm about to become my school's coach. If you have some time, I'd greatly appreciate it if you could take a look and provide me with some feedback. Thank you! Love you all <3. https://codeforces.me/contestInvitation/ccca44d49a984409344ede5f912629800ea6e003 P/S : I hate to say this as you've probably heard this a lot C:, but I apologize for my poor use of English in the problem statement. C: Solution: <spoiler summary = "Tutorial 1"> You can process queries of type 3 offline. The trick is not to go forward and adding new element, but go backward and delete element. This can be done in $O(N log N^2)$, or in $O(N log N)$ using walk on segment tree. </n> Query of type 1,2,4 can be processed using segment tree with lazy propagation. </n> Query of type 2 can be broken down to this : $a_p += (p -...
For query of type 1, you need an "override" lazy propagation array., Query of type 1,2,4 can be processed using segment tree with lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +12
  • Проголосовать: не нравится

71.
Автор Maxi135798642, 10 месяцев назад, По-английски
Range add update and range xor query. ## Introduction In this blog, I’ll explain a data structure that allows adding value **k** to all elements in the given range and querying the xor of all elements in the given range. <spoiler summary="complexity"> Both update and query take $\mathcal{O}(\sqrt{n}\log{n}\log{\text{max}})$ time. </spoiler> --- ## Prerequisites Before reading this post, you should be familiar with: - Segment Trees with **lazy propagation** - **SQRT Decomposition** - **Sorting** and **binary search** - Basic properties of **xor** - (Probably some other easy things I forgot to include) --- ## High-level idea We will use classic segment tree with lazy propagation where in each node we store xor of all the values in the range of this node, and as lazy we will store what to add to the range of the given node. Unfortunately, only keeping this doesn't allow us to apply lazy to some node. We need to store additional information. In each segment tree node we will also need to...
- Segment Trees with **lazy propagation** - **SQRT Decomposition** - **Sorting** and **binary, We will use classic segment tree with lazy propagation where in each node we store xor of all the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

72.
Автор reirugan, история, 17 месяцев назад, По-английски
Things I don't know (CM edition) Last weekend I finally hit CM, and today I reached a rating of over 2000, so in celebration, here's a list of some things I've heard of but don't know. I'm relatively new to CP—I started in August 2024—so there are a lot of techniques that most people probably consider standard that I'm not familiar with; feel free to comment below with more suggestions. (This definitely is not a copycat of [a certain other famous blog](https://codeforces.me/blog/entry/92248), I swear this is a completely original idea.) - Lazy propagation in segment trees - Fenwick trees - Sparse table - Sqrt decomposition - Mo's algorithm, which cost me an [ICPC solve](http://acmgnyr.org/year2024/problems/L-Repetitiveroutes/L-Repetitiveroutes.pdf) - Small-to-large merging - Binary search trees, including treaps - Heavy-light decomposition - Binary lifting - I've never implemented most graph algorithms, including Kruskal's/Prim's, Bellman-Ford, Floyd-Warshall, etc - I don't think I've ever implemented BF...
original idea.) - Lazy propagation in segment trees - Fenwick trees - Sparse table - Sqrt, - Lazy propagation in segment trees - Fenwick trees - Sparse table - Sqrt decomposition - Mo's

Полный текст и комментарии »

  • Проголосовать: нравится
  • +138
  • Проголосовать: не нравится

73.
Автор Sarvesh0955, история, 11 месяцев назад, По-английски
CodePlus Long 2025 Editorial Welcome to the Editorial of CodelPlus Long 2025. CodePlus Long Contest is a 2-day coding competition featuring a mix of educational and challenging problems. It allows participants to learn, practice, and compete to enhance their problem-solving skills. You can attempt the contest [here](https://codeforces.me/contestInvitation/940e1bd9749a95d26fbca52cd74512d1b505f65e). (Many Original and Challenging problems, you can give it a try :) ) The problems were authored and prepared by [user:pranavsingh0111,2025-10-14],[user:Sarvesh0955,2025-10-16],[user:Ragnar21,2025-10-16],[user:rndascode,2025-10-16],[user:ankitgarg2105,2025-5-14],[user:utk_09,2025-8-14]. We would also like to thank, [user:Rishabh_king,2025-10-16] for testing. Author : [user:Sarvesh0955,2025-10-14] <spoiler summary="Problem A"> This problem can be solved in several ways; one approach is as follows: --- ### Graph Construction Construct a new graph ( **nodes n+1 to 2n** ) where all edge weights ar...
2. Segment Tree with Lazy Propagation, Lazy propagation allows us to handle range updates efficiently. Instead of immediately updating

Полный текст и комментарии »

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

74.
Автор jigyasu_kalyan, 11 месяцев назад, По-английски
Why Lazy Segment Tree needs a push() function? Hello Codeforces, We all learn `push()/push_down()` function when studying Lazy Segment Trees. It's the engine that propagates the changes stored on a node to its children. This ensures that before we recurse deeper, the children of the current node are updated with any pending changes, guaranteeing we always work with consistent data. I was just studying Lazy Segment Trees and a fundamental question came to my mind. Is it possible to continue in Lazy trees without this `push()` function? I tried some variations of problems where we use Lazy Propagation with push() function, and tried to solve and find approaches on paper pen and I was able to find way to solve problems without push() function. I discussed with my peers an faculty if they can prove me wrong in those solutions and can provide some variation where we strictly need push() function with lazy tree. I am listing some variations below and their standard approaches of lazy tree with push() function and my approach of lazy tre...
Why Lazy Segment Tree needs a push() function?, tried some variations of problems where we use Lazy Propagation with push() function, and tried to

Полный текст и комментарии »

  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

75.
Автор intrusiv, 3 года назад, По-английски
Codeforces Round 915 (Div. 2) Editorial [A — Constructive Problems](https://codeforces.me/contest/1905/problem/A) ===== Author: [user:valeriu,2023-12-16] <spoiler summary="Solution"> We can observe an invariant given by the problem is that every time we apply adjacent aid on any state of the matrix, the sets of rows that have at least one rebuilt city, respectively the sets of columns that appear that have at least one rebuilt city remain constant. Therefore, if we want to have a full matrix as consequence of applying adjacent aid multiple times, both of these sets must contain all rows/columns. As such, the answer is bounded by $max(n, m)$. We can tighten this bound by finding an example which always satisfies the statement. If we take, without loss of generality, $n \le m$, the following initial setting will satisfy the statement: $(1, 1), (2, 2), (3, 3), ..., (n, n), (n, n + 1), (n, n + 2), .. (n, m)$ <spoiler summary="Author's Note"> I have proposed this div2A at 3 contests and after 1 year of waiti...
performing range additions which can be easily maintained by lazy propagation.

Полный текст и комментарии »

Разбор задач Codeforces Round 915 (Div. 2)
  • Проголосовать: нравится
  • +90
  • Проголосовать: не нравится

76.
Автор sslotin, 5 лет назад, По-английски
Even more efficient but not so easy segment trees https://en.algorithmica.org/hpc/data-structures/segment-trees/ I wrote a SIMD-friendly segment tree ("wide segment tree") that is up to 10x faster than the Fenwick tree and the [bottom-up segment tree](https://codeforces.me/blog/entry/18051): ![ ](https://en.algorithmica.org/hpc/data-structures/img/segtree-popular.svg) The article also explains in detail how all the other popular segment tree implementations work and how to optimize them (fun fact: the Fenwick tree can be made 3x faster on large arrays if you insert "holes" in the array layout and make it ~0.1% larger). The article is long but hopefully accessible to beginners. I only focused on the prefix sum case (partially to make the comparison with the Fenwick tree fair). While <s>I have some ideas on generalizing it to more complex operations, and I will probably add</s> I've added a separate section on implementing other operations, I highly encourage the community to try to efficiently implement mass assignment, RM...
to try to efficiently implement mass assignment, RMQ, lazy propagation, persistency, and other, , RMQ, lazy propagation, persistency, and other common segment tree operations using wide segment trees.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +260
  • Проголосовать: не нравится

77.
Автор Kmcode, история, 11 лет назад, По-английски
Code Monk (Segment Tree,RMQ,Lazy Propagation) Hello, competitive programmers! Are you interested in segment tree? or Do you think lazy segment tree is difficult? I invite you to take part in [Code Monk(Segment Tree,RMQ,Lazy Propagation)](https://www.hackerearth.com/code-monk-segment-tree-and-lazy-propagation/). You can check the start time [here](http://www.timeanddate.com/worldclock/fixedtime.html?msg=Code%20Monk%20%28Segment%20Tree%2CRMQ%2CLazy%20Propagation%29&iso=2015-09-30T10:30:00&p1=64). This is one of CodeMonk series. This contest will be held for programmer who is a beginner for (lazy) segment-tree, so we also prepared the tutorial of segment tree (and lazy segment tree). You can read it [here](https://www.hackerearth.com/notes/segment-tree-and-lazy-propagation/). There are 4 problems in this contest, segment tree or lazy segment tree problems. Do you think segment tree is very easy? Then,this contest will be easy for you ,so <b>how about solving very fast, and become a winner</b>? If you are intere...
Code Monk (Segment Tree,RMQ,Lazy Propagation), read it [here](https://www.hackerearth.com/notes/segment-tree-and-lazy- propagation/)., segment tree is difficult? I invite you to take part in [Code Monk(Segment Tree,RMQ,Lazy Propagation, ://www.hackerearth.com/code-monk-segment-tree-and-lazy-propagation/)., Are you interested in segment tree? or Do you think lazy segment tree is difficult?, I invite you to take part in [Code Monk(Segment Tree,RMQ,Lazy Propagation )](https, There are 4 problems in this contest, segment tree or lazy segment tree problems.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +48
  • Проголосовать: не нравится

78.
Автор Jrke, 4 недели назад, По-английски
Indian ICPC Camp 2026 ## Greetings Codeforces! ![ ](/predownloaded/87/8c/878cceb76b9a8b056b91b757d30549c8521ae520.png) This year, that pride comes with something new: some of India's strongest competitive programming communities are stepping up to help the next generation make the same leap. IIT Roorkee, IIT BHU, IIT Delhi, IIIT Hyderabad, IIT Indore, IIT Kanpur, IIIT Delhi, IIT Hyderabad, IIT Madras, IIT Kharagpur and IIIT Bangalore will each be hosting one week of this year's camp — several of them home to teams heading to the World Finals themselves. Each host college will also conduct a class on a topic relevant to their week's contest, so you're not just solving problems set by these communities, you're learning directly from them. The people setting your problems and running your contests this year are drawn from the very communities pushing India towards the top of competitive programming. If that isn't motivation to give this camp everything you've got, we don't know what is. With that, we're...
| | **W3** | Segment Trees | Segment tree (point update, range query); Lazy propagation; Walking on a

Полный текст и комментарии »

  • Проголосовать: нравится
  • +155
  • Проголосовать: не нравится

79.
Автор Corvus, история, 8 лет назад, По-английски
[Training] [Arabic] ACM Advanced Training 2018 — PSUT Hello Codeforces, From December 2017 to January 2018 the ACM Advanced Training 2018 was held in PSUT, covers varied topics consists of 5 Lectures. The training is recorded and published on youtube on [user:SolverToBe,2018-09-14] channel *note: language of training is Arabic. ### **Lecture 1** Presented By Mohammad Abu Aboud [user:Hiasat,2018-09-14] <spoiler summary="Combinatronics I"> Part 1 | [Rule of Sum and Product and Inclusion Exclusion](https://www.youtube.com/watch?v=7qQCQlSHsjU&list=PLPSFnlxEu99HgAEayVzwxfLo0jwUU3rQD&index=1) Part 2 | [Permutation and Combination](https://www.youtube.com/watch?v=TDHiHSfRxCM&list=PLPSFnlxEu99HgAEayVzwxfLo0jwUU3rQD&index=2) Part 3 | [Stars And Bars Problem](https://www.youtube.com/watch?v=DES5yGZpvxw&list=PLPSFnlxEu99HgAEayVzwxfLo0jwUU3rQD&index=3) Part 4 | [Problem Arrays &mdash; CodeForces 57C](https://www.youtube.com/watch?v=eU9_C7DKiys&list=PLPSFnlxEu99HgAEayVzwxfLo0jwUU3rQD&index=4) Part 5 | [Problem Bad Subsequenc...
Part 5 | [Lazy Propagation and Problem SPOJ HORRIBLE](https://www.youtube.com/watch?v=-Xdv1tuVDc8

Полный текст и комментарии »

  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

80.
Автор marks39, 3 года назад, По-английски
All the algorithms/techniques I have used "I'm just in a mood to shitpost. Don't take it too seriously." -Um_nik #### Graphs - DFS - BFS - 0-1 BFS - Kruskal's - Dijkstra's - Bellman-Ford - 2-Coloring - Prim's - Floyd-Warshall - Johnsons - Ford-Fulkerson - Dinics - Edmonds-Karp - Level Graphs - SCC - 2VCC/2ECC - 2-Sat - Dominator-Trees - Hopcroft-Karp - Hungarian - MCMF - Top Sort - Blossom's - Eulerian Cycle - Hamiltonian Cycle - TSP - Functional Graphs - Augmenting Paths #### DP - Range DP - Divide and Conquer DP - Convex Hull Trick - Space Save - Alien Trick - Bitmask DP - State Switch - Digit Descent #### Strings - Hashing - KMP - Z-function - Trie - Aho Corasick - Suffix Automaton - Suffix Tree - Suffix Array - Eertree - Manachers #### Data Structures - Segment Tree - Prefix Sum - DSU - DSU Rollback - Treap - Binary Indexed Tree - Queue - Stack - Priority Queue - Linked List - Sets - Maps - Bitsets - Ordered Statisic Tree - Lazy Propagation - Li Chao...
Statisic Tree - Lazy Propagation - Li Chao Tree - Sparse Table - Persistent Segment Tree - Implicit

Полный текст и комментарии »

  • Проголосовать: нравится
  • -17
  • Проголосовать: не нравится

81.
Автор Trace_X1729, 13 месяцев назад, По-английски
A New Way (supposedly) to answer Range Queries with Point Updates. Hello everyone :) I am going to present a new way(I couldn't find it on the internet) to do range queries with point updates, back story and all other details later: It is very intuitive and easy to understand, also I have included a lot of examples so please read till the end, it will be especially useful for those who are reluctant to study segment trees (I think). You are given an array A of size N, and Q queries involving both point updates and range queries. First we will have to do some pre-computation.I will call the precomputed structure as SST (full form later) from now. Also, for the sake of simplicity, just assume that we are constructing the structure for sum right now, the language is going to be cpp throughout the blog. ### **Declare SST:** ~~~~~ int N = A.size() - 1;//this is assuming that the array passed is 1-indexed. vector<vector<int>>SST(N + 1); //It is basically a 2-D vector of size N + 1, where N is the size of the array. It is N + 1 to ha...
I am hopeful that someone will find a workaround to make this support Lazy- Propagation. Also

Полный текст и комментарии »

  • Проголосовать: нравится
  • +11
  • Проголосовать: не нравится

82.
Автор Enamul_Hasan85, история, 19 месяцев назад, По-английски
My Solutions for the CodeForces ITMO Academy Segment Tree Course (Part 2_4) Hello CodeForces community, I completed the CodeForces ITMO Academy Course on Segment Tree Part 2 and wanted to share my solutions and explanations (only step 4) for the problems covered in these parts. I hope this will help others who are working through the course or anyone looking to strengthen their understanding of segment trees. I have uploaded all my solutions to GitHub, which you can find [here](https://github.com/Enamulhasan85/ProblemSolving/tree/main/CF%20ITMO%20Academy%20Segment%20Tree%20EDU/Part-2_4). #### [Part 2: Step 4 Practice Problems](https://codeforces.me/edu/course/2/lesson/5/4/practice) ###### [Problem A: Assignment, Addition, and Sum](https://codeforces.me/edu/course/2/lesson/5/4/practice/contest/280801/problem/A) <spoiler summary="Solution:"> In this problem, we handle two types of update operations: assignment and addition. To solve it, we store both the update value and type in the segment tree and query the range sum. ##### **Propagation L...
-defined limits. 3. **Optimized Lazy Propagation**: Only relevant nodes are created and updated

Полный текст и комментарии »

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

83.
Автор Guslix, история, 5 лет назад, По-английски
Next Permutation on Subsegment To get the next permutation of array of its subsegment there is a simple and very old Narayana's algorithm. This algorithm invented by Indian mathematician Pandit Narayana more than 600 years ago. Given array $a$. How to go to its next permutation? 1. Find the longest non-increasing suffix of the array (LNIS). If whole array is non-increasing, permutations are exhausted. 2. Let LNIS be a suffix $k$, where $k$ is position where it begins. Swap previous element, $a_{k-1}$ and the next largest number (NLN) that exists in suffix $k$. 3. Reverse suffix $k$. Time complexity: $O(n)$ in the worst case. But on average length LNIS is about 3 elements, so iteration over all permutations is doing for $O(n!)$, thus $O(1)$ for one permutation. Although suddenly there is such a problem. Given an array of 100500 elements and 100500 queries to get next or previous permutation. If the array is sorted and first query is prev permutation on whole array, second query is next permutation o...
~~~~~ void lazy_pr(treap t){ if(!t || !t

Полный текст и комментарии »

  • Проголосовать: нравится
  • +57
  • Проголосовать: не нравится

84.
Автор Iwaskid, история, 10 лет назад, По-английски
Segment Tree Implementation (Lazy Propagation) Hi all, I am trying to code up a solution to the "[Seating](http://www.usaco.org/index.php?page=viewproblem2&cpid=231)" problem in USACO January 2013 Gold, which uses a segment tree with lazy propagation. My code passes the first 2 test cases, but fails the rest. I have checked multiple times about my code but I don't see the problem. ~~~~~ #include<iostream> #include<fstream> #include<algorithm> #include<assert.h> #include<string> #include<vector> using namespace std; int n, m; int t; vector<int> A; vector<int> l0, r0, lazy0, lazy1,ans; void build(int a,int l,int r) { if (r - l < 1) { l0[a] = 1; r0[a] = 1; ans[a] = 1; return; } l0[a] = r - l + 1; r0[a] = r - l + 1; ans[a] = r - l + 1; build(a * 2, l, (r + l) / 2); build(a * 2 + 1, (r + l) / 2 + 1, r); } void lazyupdate(int a,int l,int r) { assert(!(lazy0[a]==1&& lazy1[a])); if (lazy0[a]) { lazy0[a] = 0; l0[a] =ans[a]= r - l + 1; r0[a] = r - l + 1; if (l != r) { lazy0[2 *...
Segment Tree Implementation (Lazy Propagation), group of people. `lazy0` and` lazy1` stores respectively the lazy propagation for setting to 0 and, of people. `lazy0` and` lazy1` stores respectively the lazy propagation for setting to 0 and setting, =viewproblem2&cpid=231)" problem in USACO January 2013 Gold, which uses a segment tree withlazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

85.
Автор ammar007, история, 2 года назад, По-английски
TCPC 2022 Solutions ### A. Mood <spoiler summary="Python Solution"> ```python def read(): return int(input()) def read_list(): return [int(i) for i in input().split()] def solve(): x, y = read_list() print(max(0, y-x)) for i in range(read()): solve() ``` </spoiler> ### B. Hungry <spoiler summary="Python Solution"> ```python def read(): return int(input()) def read_list(): return [int(i) for i in input().split()] def solve(): n = read() a = read_list() prefix_sum = [0]*(n+1) for i in range(1, n+1): prefix_sum[i] = prefix_sum[i-1] + a[i-1] q = read() for i in range(q): x, y, m = read_list() result = min(max(x, prefix_sum[n]), prefix_sum[m]+y) print(result) solve() ``` </spoiler> ### C. Ice Coffee <spoiler summary="Python Solution"> ```python def read(): return int(input()) def read_list(): return [int(i) for i in input().split()] max_a = in...
struct SegmentTree { // segment tree with lazy propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

86.
Автор willy108, история, 3 года назад, По-английски
Teamscode Spring 2023 Editorial This is the editorial for a recent contest [Teamscode](https://www.teamscode.org/). The problems are open for upsolving on [this gym](https://codeforces.me/gym/104287). Problems were prepared by [user:oursaco,2023-04-06], [user:dutin,2023-04-06], [user:thehunterjames,2023-04-06], [user:Bossologist,2023-04-06], [user:Esomer,2023-04-06], and me. ### [A. What do you do when the contest starts? Are you busy? Will you solve Bingo?](https://codeforces.me/gym/104287/problem/A) <spoiler summary = "Editorial"> <spoiler summary = "Are you busy?"> 1. WorldEnd/SukaSuka 2. Bocchi the Rock </spoiler> <spoiler summary = "No Sweep"> 1. Thomas </spoiler> <spoiler summary = "Multiplication Table"> 1. Lycoris Recoil </spoiler> <spoiler summary = "Greatest Common Multiple"> 1. Bokuben </spoiler> <spoiler summary = "A Certain Scientific Tree Problem"> 1. A Certain Scientific Railgun </spoiler> <spoiler summary = "Two and Three"> 1. Quintessential Quintluplets...
them in the formula to retrieve the answer. Updates can be done using lazy propagation similar to

Полный текст и комментарии »

Разбор задач Teamscode Spring 2023 Contest
  • Проголосовать: нравится
  • +87
  • Проголосовать: не нравится

87.
Автор EP11LU, 3 недели назад, По-русски
Алгоритмы — "Цикл постов. Часть 4" Сегодняшний пост будет посвящён алгоритмам. Я составлю основной список алгоритмов, разделю их по примерному уровню сложности и расскажу, в каком порядке и как их лучше изучать. Также немного поговорю о недостатках чисто алгоритмического подхода к программированию и о том, почему одного знания алгоритмов недостаточно. Как и в предыдущем посте, я выделю следующие основные, на мой взгляд, темы: конструктивные и ad hoc задачи, строки, графы и деревья, структуры данных, динамическое программирование, комбинаторика и теория чисел, математика, жадные алгоритмы, метод отжига и открытые тесты. **Уровень I** — базовые алгоритмы, необходимые для школьных и районных (муниципальных) олимпиад, а также для написания brute-force решений. **Уровень II** — основные алгоритмы среднего уровня, необходимые для **успешного** прохождения и выступления на областных (региональных) олимпиадах. Этот уровень предполагает знание наиболее важных и базовых алгоритмов из каждой темы. **Уровень III** —...
— *II* * Дерево отрезков с массовыми операциями и отложенным обновлением (Lazy Propagation) — *II

Полный текст и комментарии »

  • Проголосовать: нравится
  • +9
  • Проголосовать: не нравится

88.
Автор Pa_sha, история, 2 года назад, По-английски
[Tutorial] Another way to look at the segment tree and many other data structures I haven't seen anyone to write about this technique, so I decided to make a blog about it. I know that it is mostly general intuition, but not everyone really understand it. Also, I would be happy if you add something in comments or correct some errors. Also, before reading this blog I recommend to have some knowledge about segment tree and divide and conquer. I would like to thank [user:riazhskkh,2024-08-17] and [user:FBI,2024-08-17] for reviewing this blog. ### **The main idea** When we have some divide and conquer algorithm, we can memorize each recursive call to be able to operate with it as data structure. For example, when we do merge sort, we can memorize how array looked after sorting on each call. Using this we can get merge sort tree. Also, if we memorize quick sort in such way, we will get wavelet tree. A lot of standart ways to use divide and conquer would lead to segment tree. But, it also can be used when we divide array on 3 parts or more, when we divide consideri...
, that we can do almost all operation which we can do on segment tree, such as lazy propagation or, and assume we memorize at each level (even and odd array each time), then we can dolazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +60
  • Проголосовать: не нравится

89.
Автор Maaxle, 2 года назад, По-английски
CSES Range Queries solutions Hey Codeforeces! How are y'all doing? I was solving the CSES Range Queries module and thought of sharing my solutions with you if it's of any use. This blog entry is motivated by [user:kartik8800,2024-04-05]'s own entry ([https://codeforces.me/blog/entry/77128](https://codeforces.me/blog/entry/77128)). I noticed it was missing some of the last problems of the list, so I thought of adding those here as well. This is my first blog entry, so don't mind to correct me if you notice anything odd in here. If you have any alternative solutions to these problems, it'd be great to share them as well! Static Range Sum Queries ------------------ Given an array, answer $q \leq 2\cdot10^5$ queries consisting on the sum of values in the subarray $[l, r]$. Let's obtain the answer of a single query from the precalculated sum of every prefix in the array. This technique is called **prefix sum**. This approach allows us to answer each query in $O(1)$. <spoiler summary="How to obtain the a...
Fenwick Tree) or a Segment Tree with a special feature called Lazy Propagation . I will explain my, find the idea, you will be able to use a Segment Tree with Lazy Propagation., is a Segment Tree. We will need to do range updates, though. Here's where Lazy Propagation comes to, This is simply a Segment Tree with Lazy Propagation. You just have to be careful on how to do the

Полный текст и комментарии »

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

90.
Автор chinesedfan, история, 22 месяца назад, По-английски
Understanding Segment Tree by Divide and Conquer > As is well-known, segment tree allows answering range queries over an array efficiently, while still being flexible enough to allow quick modification of the array. -- https://cp-algorithms.com/ **This blog is about how to solve segment tree problems generally**, including not only the classic range sum/minimum/maximum, but also some other complex cases. If are already confident enough of your skills, you can skip reading most of the content and go to practice the last problem directly. ## Basic Example Almost everyone learns segment tree from calculating range sums with single element updates. The formal definition is: > Given an array $A$, for each query range $[L,R]$, returns its sum $\sum_{i=L}^R A[i]$. And also handle assignments of the form $A[i] = x$. The main idea is to divide the whole range $[1,N]$ into 2 parts. Obviously, if we know sums of each part, the whole range sum can be calculated in $O(1)$ by a simple add operation. ``` sum[1,N] = sum[1, N/2] ...
$[1,N]$, all $O(NlogN)$ nodes need to be updated. Using lazy propagation can optimize to $O(logN

Полный текст и комментарии »

  • Проголосовать: нравится
  • +15
  • Проголосовать: не нравится

91.
Автор dcordb, история, 10 лет назад, По-английски
COJ Round Contest #8 + Editorial Hello everyone. I would like to invite you to participate in the 8th COJ (Caribbean Online Judge) Round, this will be a contest with 5 problems, and three hours of duration. The problems will have Div2-like complexity and will be in English and Spanish. The contest will have ACM-ICPC format. You can find out more about it clicking [here](http://coj.uci.cu/contest/contestview.xhtml?cid=1522). You can also check out the previous rounds [here](http://coj.uci.cu/contest/past.xhtml). **UPD1:** Time of the contest has changed because of overlapping with Euro Semifinals :). The contest will start at [this time](http://timeanddate.com/worldclock/fixedtime.html?day=7&month=7&year=2016&hour=9&min=30&sec=0&p1=99). **UPD2:** The contest is about to start, [get in now!!](http://coj.uci.cu/contest/contestview.xhtml?cid=1522). **UPD3:** The contest is over. Hope you liked the problems. Hints: ------ #### Problem A: The last player to play wins. Note that this last player can al...
two strings. Also you should add lazy propagation to this.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +27
  • Проголосовать: не нравится

92.
Автор z4120, история, 7 лет назад, По-английски
Efficient and easy segment trees — extension An extension of the blog [Efficient and easy segment trees](https://codeforces.me/blog/entry/18051). ## Single element modification + find nearest previous element smaller than value For recursive implementation, see this comment: https://codeforces.me/blog/entry/55083#comment-389949. Non-recursive implementation: First it's necessary to find any parent of the target node. There are two methods. * Method 1 (similar to the query range function): divide the range `[0..x+1[` into $\log n$ ranges, find the rightmost range with minimum value smaller than `val`. * Method 2: just traverse the tree to the left starting from node `x`. For simplicity, assume the last element of the array is $-\infty$. (only required in method 2) (`t[x]` is the minimum value in node `x`.) ```cpp #define METHOD_1 /* 1 or 0 */ int previous_less_than(int x, int val) { x += n; #if METHOD_1 int found_node = -1; for (int l = n, r = n + x + 1; l < r; l >>= 1, r >>= 1) { if (l & 1) { ...
## Lazy propagation + find nearest previous element smaller than value

Полный текст и комментарии »

  • Проголосовать: нравится
  • +22
  • Проголосовать: не нравится

93.
Автор bhikkhu, 11 месяцев назад, По-английски
Super efficient RMQ alternative with updates If we build an interval tree as shown in the following picture, we can get super effective RMQ data structure as good as iterative segment tree. I have benchmarked against Fenwick RMQ and it turns out this is much much better time complexity wise than log square range decomposition. All queries take 3 logn at most because the search interval is halved every third step in worst case once we determine the offshoot segment which exceeds our leftmost point l. ![ ](https://codeforces.me/predownloaded/51/8b/518bf3fce31a2ba3677e2fff7d625d6ac7e63f92.jpeg) https://cses.fi/problemset/task/1649/ <spoiler summary="skewed range decomposition"> ~~~~~ #include <iostream> using namespace std; const int N = 200000; int tree[N + 1]; int leaf[N+1]; int len[N+1]; int par[N+1]; int n, q; void build_links(const int i){ const int L=len[i-1]; len[i]=1; if(L==len[i-1-L]){ len[i]+=2*L; par[i-1]=i; par[i-1-L]=i; } } void combine(const i...
Hence we have a super easy RMQ. Lazy propagation should be easy as we already have the required

Полный текст и комментарии »

  • Проголосовать: нравится
  • -19
  • Проголосовать: не нравится

94.
Автор mouse_wireless, история, 8 лет назад, По-английски
Yet another range query data structure I want to discuss a type of data structure that I (personally) haven't really seen get any attention. It doesn't really do anything special, but I still find it interesting enough that it should be at least noticed. It is an alternative to Fenwick trees (aka binary indexed trees), in the sense that it solves the same class of problems, in a memory-efficient way (unlike segment trees or binary search trees). Although the implementation has a couple extra lines of code, (in my subjective opinion at least,) it is easier to visualize and understand conceptually when compared to Fenwick trees. In fact, my motivation for writing this is that personally I've had a hard time learning BITs and understanding them (beyond memorizing the code) and for a long time I've avoided them in favor of segment trees or (when time/memory restrictions were tight), a structure similar to the one I'll be describing. With that out of the way, the sample problem we are trying to solve is the following: give...
experience). You can also easily implement range updates with lazy propagation (the same way you would

Полный текст и комментарии »

  • Проголосовать: нравится
  • +58
  • Проголосовать: не нравится

95.
Автор STommydx, история, 9 лет назад, По-английски
Codeforces Round #457 (Div. 2) Editorial I would like to take this opportunity to express my deepest apology to all of you who take your own precious time to participate in this unrated round. Also, apologies to [user:gritukan,2018-01-19] who really helped a lot in preparing the round and [user:MikeMirzayanov,2018-01-19] who helped to host the round, I did not do a good job in managing the round. As the main author of this round, I'm undoubtedly responsible for the mistake that not writing a brute force solution to test the correctness of the intended solution. It is my responsibility to make sure everything is right before the round starts. I am really sorry that the round must be unrated to ensure fairness to all contestants. I hope all of you can learn something from the contest. Do not claim a greedy solution absolutely correct (like me :C) unless you have proved it. On the bright side, I'm really glad that some of you found problem D and E interesting as said in some comments in the announcement blog post. I admit tha...
with lazy propagation.

Полный текст и комментарии »

Разбор задач Codeforces Round 457 (Div. 2)
  • Проголосовать: нравится
  • +191
  • Проголосовать: не нравится

96.
Автор yummy, 11 лет назад, По-английски
Codeforces Round #334 Bonus Editorial: More Ideas on Div. 1 E I wrote problem [problem:603E] for the recent Codeforces round and was pleasantly surprised to see so many different solutions submitted in addition to my own ([submission:14611571]). Even though I proposed the problem, I learned a lot by reading the submissions after the contest! Since I think these other approaches illustrate some beautiful techniques, I would like to share them with you guys. Below, I describe three different solution ideas by [user:TooSimple,2015-12-03], [user:winger,2015-12-03], and [user:malcolm,2015-12-03], respectively. (If you haven't read the [editorial](/blog/entry/21885) yet, I suggest that you do so before continuing, since some of the observations and definitions carry over.) #### Solution 1: [user:TooSimple,2015-12-03] Like my original solution, this approach uses a link-cut tree to maintain an online MST. The main idea is the following observation: In a tree with an even number of vertices, an edge can be removed if and only if it separates the grap...
link-cut tree and support path updates with lazy propagation to maintain the parity of each edge.

Полный текст и комментарии »

Разбор задач Codeforces Round 334 (Div. 1)
  • Проголосовать: нравится
  • +85
  • Проголосовать: не нравится

97.
Автор Sinedka, история, 11 месяцев назад, По-русски
ДО ресурсы Segment Tree ============================================ A-D: Segment Tree (Point Update Range Query) -------------------------------------------- ###Resources - https://csacademy.com/lesson/segment_trees - https://cp-algorithms.com/data_structures/segment_tree.html ###Example <spoiler summary="Segment tree base template"> ```c++ struct stree { vector<ll> t; // Вектор, хранящий вершины сегментного дерева. // Индексация с 1: вершина v = 1 — это корень дерева. // Каждый узел хранит сумму чисел на своём отрезке. // Размер вектора ~4*n, чтобы гарантированно уместить дерево // любой формы. // build(a, v, tl, tr) // // a — исходный массив // v — индекс текущей вершины в дереве (начинается с 1) // tl — левая граница отрезка (включительно) // tr — правая граница отрезка (включительно) // // После вызова build(a, 1, 0, n-1) дерево полностью построено. void build(const vector<ll...
E-G: Segment Tree with Lazy Propagation --------------------------------------- ###Resources

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

98.
Автор 2ndSequence, история, 6 лет назад, По-английски
Help with Segment tree + Primes problem from SPOOJ, with a brief of code and idea explanation. Hello guys.. I was trying to solve this [task](https://www.spoj.com/problems/PRMQUER/) on SPOOJ but i am getting WA for some reason so hope if someone can help me.. The problem in-short asks you to find the count of prime number in specific interval which are also less than or equal to 1e7 after some modifications. 1. I just look for the primes until i reach 1e3, why? because i think if we are just looking for primes until 1e7 then we can check primes until square root of x only right? if it wasn't divisible by any prime then it's a prime number and i may be wrong... 2. After that i just build a segment tree with lazy propagation. 3. For propagation the count for specific interval with be either the length (rx &mdash; lx) or zero. depends if the new value will be a valid prime. 4. For a single point update i keep go down from the root until i reach to that point and it's count should be either 0 or 1. 5. Just calculate the count of sub-segment like any other seg...
2. After that i just build a segment tree with lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • -7
  • Проголосовать: не нравится

99.
Автор MesbahTanvir, история, 8 лет назад, По-английски
Editorial [GYM] 2018 BACS Contest replay [problem:101864A] Setter: [user:ISwearItIsMyLastContest,2018-08-10] Alternate Writer: [user:prophet_ov_darkness,2018-08-10], [user:s_h_shahin,2018-08-10] <spoiler summary="Editorial"> This problem actually reflect the [josephus problem](https://en.wikipedia.org/wiki/Josephus_problem). The main part of this problem is to find Number of possible Y such that **josephus(Y,2) = X** . After finding this rest part is obvious calculation. Let’s see first few values of josephus(i,2): 1 1 3 1 3 5 7 1 3 5 7 9 11 13 15 We can see that there is a nice pattern here. **josephus(n,2)** is an increasing odd sequence that restarts with **josephus(n,2) = 1** whenever the index **n** is a power of 2. First we will find minimum value of p such that **josephus(p,2) = X**. we can do this in **O(log n)** , because for every **q>0** **josephus(2^q-1,2) = 2q^-1** and **josephus(2^q,2) = 1**. So we can run loop through q >= 0 and find highest value of **q** such that **josephus(2...
sorted, their order won’t change. So this can be solved easily with Segment Treelazy propagation in O, Now, to solve this problem (both for negative and non-negative Y) we need a treap(withlazy

Полный текст и комментарии »

Разбор задач 2018 BACS Contest Replay
  • Проголосовать: нравится
  • +38
  • Проголосовать: не нравится

100.
Автор cjtoribio, история, 10 лет назад, По-английски
Unknown Data Structure — (Sqrt Fragmented Tree) Block Tree =============== Story ----- I was trying to solve [this](http://codeforces.me/gym/100589/problem/A) problem from the gym and I struggled to find the solution. Finally, I came up with a very interesting data structure capable of handling any subtree update and really don't know if someone else has seen it before, but I will post it here since I could not find its name (if it has) in google. My solution was able to solve the problem with $O(N)$ memory, $O(N)$ in creation, $O(\sqrt{N})$ per query. When I saw the editorial I saw that it had another interesting approach with an update buffer which solved the problem in $O(Q\sqrt{Q}log{N})$, for my surprise my solution was $O(Q\sqrt{N} + N)$ summing the creation and queries, and I saw conveniently the author used $Q <= 10^4$ so probably the author didn't know about my approach. After analyzing my approach and reading one of the comments in the same problem, I saw that the problem could be also solvable using Square Roo...
the fragment **u** belongs will be updated completely in $\sqrt{N}$ [as lazy propagation] then it

Полный текст и комментарии »

  • Проголосовать: нравится
  • +115
  • Проголосовать: не нравится

101.
Автор nuredinbederu10k, история, 13 месяцев назад, По-английски
A2SV Contest #25 Editorial [Here](https://codeforces.me/contestInvitation/89b9e7a75935f3ce18b8492441c60a79516d3719) is the link to the contest. All problems are from Codeforces' problem set [A. Melody Perfection](https://codeforces.me/gym/628023/problem/A) <spoiler summary="Solution"> To determine whether a melody is perfect, we check each pair of consecutive notes in the sequence. For each pair $a_i, a_{i+1}$, we calculate the interval as $|a_i - a_{i+1}|$. We then verify whether this interval is one of the allowed values, 5 or 7. If all consecutive intervals satisfy this condition, the melody is perfect and the answer is "YES". Otherwise, if any interval is not 5 or 7, the melody is not perfect and the answer is "NO". This method ensures that every adjacent pair is validated exactly once, giving a time complexity of $O(n)$ and a space complexity of $O(1)$. </spoiler> <spoiler summary="Code"> ```python n = int(input()) notes = list(map(int, input().split())) perfect = True for i in ra...
## Segment Tree with Lazy Propagation, . - **Range Update:** Advanced Segment Trees with **lazy propagation** can handle efficient range, . 4. **Lazy Segment Tree:** Supports **efficient range updates** using lazy propagation. 5. **2D, We build a **segment tree** over `A` with **lazy propagation**.

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

102.
Автор hyforces, история, 3 года назад, По-английски
Teamscode Summer 2023 Editorial This is the editorial for the recent Teamscode Summer 2023 contest, and the problems are open for upsolving on this [gym](https://codeforces.me/gym/104520). Problems were prepared by [user:oursaco,2023-08-22], [user:dutin,2023-08-22], [user:thehunterjames,2023-08-22], [user:Bossologist,2023-08-22], [user:Esomer,2023-08-22], [user:danx,2023-08-22], [user:codicon,2023-08-22], [user:willy108,2023-08-22], and [user:hyforces,2023-08-22]. The problems were tested by [user:omeganot,2023-08-22], [user:codicon,2023-08-22], [user:cry,2023-08-22], [user:skye_,2023-08-22], [user:Litusiano_,2023-08-22], and [user:apple_method,2023-08-22]. ### [A. Who is cooking?](https://codeforces.me/gym/104520/problem/A) <spoiler summary="Solution"> danx </spoiler> <spoiler summary="Code"> ~~~~~ print("Esomer") ~~~~~ </spoiler> ### [B. Restaurant Sorting](https://codeforces.me/gym/104520/problem/B) <spoiler summary="Solution"> The answer is $n - $ the longest prefix of the array where a...
they occur, as well as the historic sum for each of the relevant $k$ values. In eachlazy tag, we

Полный текст и комментарии »

Разбор задач Teamscode Summer 2023 Contest
  • Проголосовать: нравится
  • +84
  • Проголосовать: не нравится

103.
Автор SummerSky, 9 лет назад, По-английски
My advance and my thought, after completing about 100 virtual rounds It took me about one year to complete about 100 virtual rounds. I learned a lot of techniques that I had seldom read in books or even never heard of before, like segment tree with lazy propagation, bit-mask dp and so on. In the early stage, I could only solve about two div2 problems. As time goes on, I found that I could solve more and even all div2 problems, either on my own or by reading tutorials. I also got familiar with a lot of IDs as I kept participating in more virtual contests. At first, I competed with them together in div2 but they improved quite fast and went to div1, and as it turns out, they are legends now. But I guessed that before legends become legends, they had similar experiences like us, too, facing challenges, keeping practicing, handling various problems, and making progress day by day. This makes me believe more deeply, that hard working may not be sufficient to achieve one's target, but is at least surely necessary. Best wishes to everyone's dr...
segment tree with lazy propagation, bit-mask dp and so on.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +196
  • Проголосовать: не нравится

104.
Автор Dragonado, 4 года назад, По-английски
[Tutorial] CMS trick — an alternate solution for ABC217D and CF1567E Hello everyone, Recently [user:peltorator,2023-01-17] created a [challenge](https://codeforces.me/blog/entry/110840) to create interesting educational blogs. This gave me the motivation to write about a trick I discovered a while back. The trick is simple and I wouldn't be surprised if it already exists with some other name. But I couldn't find any blog on it so I'm making my own. I have made a data structure that deals with the partition of an array. I call it Cut-Merge-Stick (CMS) trick. A partition of an array is a grouping of its elements into non-empty subarrays, in such a way that every element belongs to exactly one subarray. I refer to every segment in this partition as a "stick". Some operations on this data structure are merging two consecutive sticks, cutting a single stick into two smaller sticks, getting the longest stick in a range, counting the number of sub-sticks in a range, etc. ## Problem statement You are given a stick of length $N$ units, placed on ...
I don't have a deep understanding of the abstractness of lazy propagation in segment trees. I only

Полный текст и комментарии »

  • Проголосовать: нравится
  • +80
  • Проголосовать: не нравится

105.
Автор Jester, история, 8 лет назад, По-английски
Arithmetic Progression Range Update/(Max,Min) Query This problem has been taking a lot of my time lately and i would like to share it with you. Let's first warm up with this problem: given array $v$ of length $n$ and $q$ queries $(1 \leq n,q \leq 10^5)$ each query of the form $l,r,a,x , (1 \leq l \leq r \leq n) , (1 \leq a,x \leq 10^5)$ add to the element at index $l$ value $a$ add to the element at index $l + 1$ value $a + x$ add to the element at index $l + 2$ value $a + 2*x$ add to the element at index $l + y$ value $a + y*x$ add to the element at index $r$ value $a + (r - l)*x$. basically update range with arithmetic progression,apply all queries then print the final array Now depending on the details of the problem this can be solved using prefix sums , segment tree ,or some other way A brief explanation of the segment tree with lazy propagation solution is that in each node we store the value we want to add to the left most element in the range and the value $x$. When we are propagating the values...
A brief explanation of the segment tree with lazy propagation solution is that in each node we

Полный текст и комментарии »

  • Проголосовать: нравится
  • +44
  • Проголосовать: не нравится

106.
Автор TooObvious, история, 9 лет назад, По-английски
Materials from Summer Programming Camp ### Day 1 and 2 #### Dynamic Programming - Two good blog entries for dp &mdash; [Basic](http://codeforces.me/blog/entry/43256) , [Good Tricks](http://codeforces.me/blog/entry/47764) - [Modified Knapsack &mdash; 1](http://codeforces.me/problemset/problem/742/D) - [Maximum Disjoint Subtrees Sum](http://codeforces.me/problemset/problem/743/D) - [Modified Knapsack &mdash; 2](http://codeforces.me/problemset/problem/755/F) - [State-Space Reduction](http://codeforces.me/contest/505/problem/C) - [Chess Board Dp](http://codeforces.me/contest/559/problem/C) #### Segment Trees - A nice blog entry for this [Everything About Segment Trees](http://codeforces.me/blog/entry/15890),contains many good problems to try as well - [Stack-SegTree problem](http://codeforces.me/problemset/problem/756/C) - [Matrix Expo on SegTree](http://codeforces.me/problemset/problem/718/C) - [Implementation-Hackerearth](https://www.hackerearth.com/practice/notes/segment-tree-and-lazy-propagation/)...
-tree-and-lazy-propagation/)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +32
  • Проголосовать: не нравится

107.
Автор quinoa, история, 6 лет назад, По-английски
Segment tree complexity when not merging lazy updates After watching SecondThread's [Segment tree tutorial](https://www.youtube.com/watch?v=QvgpIX4_vyA&t=1999s&ab_channel=SecondThread) I have the following questions: #### Question 1: Not merging lazy updates At [this point in the video](https://youtu.be/QvgpIX4_vyA?t=1863) SecondThread mentions that you need to merge lazy updates for every node into a single update in order for the segment tree to stay $O(K * log N)$ time for $K$ queries. I don't understand why that is the case. Imagine we have a segment tree implemented for range sums and we implement it such that every node has a list of lazy propagation operations (which SecondThread says is bad), instead of a single lazy propagation operation. So for instance if you add +3 to some range, and then add +5 to the same range you would have [+3, +5] as your operations for the corresponding node instead of +8. Since every rangeAdd will add at most $log(N)$ of these operations to our lists, it means that in total we will have ...
Segment tree complexity when not merging lazy updates, has a list of lazy propagation operations (which SecondThread says is bad), instead of a singlelazy, list of lazy propagation operations (which SecondThread says is bad), instead of a singlelazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • +21
  • Проголосовать: не нравится

108.
Автор Infinidrix, история, 4 года назад, По-английски
Editorial for A2SV Full Squad Contest This was a fun contest to prepare and thanks to [user:seraph14,2022-05-01], [user:zbeimnet2,2022-05-01], [user:Triple-Threads,2022-05-01], [user:nCydready,2022-05-07], [user:0xdoggie,2022-05-07], [user:emrevarol,2022-05-07] and [user:aben,2022-05-07] for testing and reviewing the contest. Contest Link: https://codeforces.me/contestInvitation/8fdb81183a6e2a3ad23597d6d586c36f32680e6c ### [Outlets and Dividers](https://codeforces.me/gym/380981/problem/A) <spoiler summary="Tutorial"> For this problem, if an divider has $k$ outlets, then it provides $k-1$ outlets since it has to plug into an already existing outlet. So in order to minimize the number of outlets we are using we can keep taking the divider with the largest number of outlets until the sum of their outlets ($-1$ for each divider) is above or equal to the number of students. An edge case to be aware of is if the number of students is less or equal to 2, whereby we don't need any additional dividers. Time Compl...
Space Complexity: O($n(lgs)(lgs)$) with lazy propagation.

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

109.
Автор wineColoredDays, история, 11 лет назад, По-английски
WA on HORRIBLE SPOJ Guys, i'm getting consistently WA on this problem [HORRIBLE](http://www.spoj.com/problems/HORRIBLE/) . I tried some inputs myself, but they are of no use . please help . Here is my code that uses segment tree + lazy propagation : ` #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 1e5 + 5; int n, c; ll s[4 * N]; ll lazy[4 * N]; void upd(int id,int val, int l, int r){ s[id] += (long long )(1LL * (r-l+1) * (1LL * val)); lazy[id] += val; } void shift(int id, int l, int r){ int mid = (l + r) / 2; upd(2 * id, lazy[id], l, mid); upd(2 * id + 1, lazy[id], mid + 1, r); lazy[id] = 0; } void increase(int x, int y, int val, int id = 1, int l = 1, int r = n){ if(r < x or y < l) return; if(x <= l and r <= y){ upd(id, val, l, r); return; } shift(id, l, r); int mid = (l + r) / 2; increase(...
segment tree + lazy propagation :

Полный текст и комментарии »

  • Проголосовать: нравится
  • -5
  • Проголосовать: не нравится

110.
Автор GreenGrape, 9 лет назад, По-русски
Codeforces Round #426 Editorial We, the round authors, are eternally grateful to all the brave who took part in this round. Sadly there were some issues to encounter, but we hope it only made the contest more interesting :) [tutorial:834A] **Code**: [submission:29027824] [tutorial:834B] **Code**: [submission:29027867] [tutorial:834C] **Code**: [submission:29027782] [tutorial:833B] **Code** (divide & conquer, [user:GreenGrape,2017-07-31]) [submission:29027705] **Code** (divide & conquer, [user:x3n,2017-07-31]) [submission:29027883] **Code** (lazy propagation) [submission:29027667] [tutorial:833C] **Code**: [submission:29027757] [tutorial:833D] **Code**: [submission:29027729] [tutorial:833E] **Code**: [submission:29027876]
**Code** (lazy propagation) [submission:29027667]

Полный текст и комментарии »

Разбор задач Codeforces Round 426 (Div. 1)
Разбор задач Codeforces Round 426 (Div. 2)
  • Проголосовать: нравится
  • +45
  • Проголосовать: не нравится

111.
Автор SilverSurge, история, 3 года назад, По-английски
CSES Range Queries: Polynomial Queries: Solved!! Finally Solved ------------------ Thanks to the testcase by [user:sieunhan283,2023-10-30], I have solved the problem. I plan to Write a complete Step By Step Breakdown of the Problem Really Soon. Here is the Correct Code. ### Correct Code (You Can Use it as a LazyProp Template as well) ~~~~~ #include <bits/stdc++.h> using namespace std; #define fastio ios::sync_with_stdio(false);cin.tie(NULL) #define int long long int INF = 1e18; int NINF = -1e18; int MOD = 1000000000+7; class LazyDS { public: bool flag = false; int a = 0; int d = 0; }; class SegDS { public: int sum = 0; }; class LazySegmentTree { private: vector<SegDS> stree; vector<LazyDS> ltree; public: int n; vector<int> base; LazySegmentTree(int _n) { n = _n; base.assign(n, 0ll); ltree.assign(4*n, LazyDS()); stree.assign(4*n, SegDS()); } void init() { init(0, n-1, 1); } ...
My Approach ================== I used a segment tree with lazy propagation. The Lazy Tree node

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

112.
Автор yogesh_1___, 7 месяцев назад, По-английски
Segment Tree Visualizer Greetings Codeforces community! =============================== **This is a small learning resource to help understand segment trees through visualisation.** Segment trees are usually taught using recursive code and diagrams. Even though this is enough to write the implementation, many learners still find it hard to understand how queries and updates actually move through the tree. I built a small project to make this easier by showing each segment tree operation step by step using visualisations. Link: [https://segment-tree-visualization.vercel.app/](https://segment-tree-visualization.vercel.app/) ![ ](/predownloaded/bf/3d/bf3d3c0a9b3e58ecd20ffac7ef3e3bef4604049b.png) Note: Image quality is reduced due to Codeforces image compression. ### The tool visualises a standard segment tree and supports: - Build operation - Range queries - Point updates - Range updates using lazy propagation - SUM / MIN / MAX segment tree variants ### Additional features: - S...
- Build operation - Range queries - Point updates - Range updates using lazy propagation - SUM, - Segment Tree fundamentals - Segment Tree with Lazy Propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • +21
  • Проголосовать: не нравится

113.
Автор RussianCodeCup, история, 9 лет назад, По-русски
Russian Code Cup 2017 — Third Qualification Round Editorial <h2>A. Spreadsheets</h2> <p>Let us subtract 1 from <i>k</i>, now the columns are numbered from 0.</p><p>Let us first find out how many characters are there in the name of the column. To do it let us subtract powers of 26 from <i>k</i>, one by one, until the current power is greater than the remaining number <i>k</i>'.</p><p>Now the name of the column is <i>k</i>' in 26-based notation where characters A&ndash;Z are used as digits, prepended with leading A-s to the required length. You can either convert it using standard library function (in this case you must replace digits 0&ndash;9, A&ndash;P that will be used by the required digits), or implement a textbook algorithm of conversion to another base.</p><p>Final note: a day before the round one of the testers pointed out that CF Beta 1 Round problem B was similar to this one. After a discussion, taking into account that CF1 round was long ago, the problem is actually easier than CF1B problem, and we had no well prepared and easy enoug...
>·k) which is too slow. Let us use lazy propagation then.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +36
  • Проголосовать: не нравится

114.
Автор Mr.Quantum_1915, 7 месяцев назад, По-английски
Editorial for CCxEnigma: Tesseract '26 (IIIT Vadodara) Tesseract '26 Editorial ================== Hello Everyone! Hope you enjoyed **[CCxEnigma: Tesseract '26](https://codeforces.me/blog/entry/150726)** conducted by [IIITV Coding Club](https://iiitvcc.vercel.app/home) and Mathematics Club at IIIT Vadodara. Thank you for participating in the contest. Hope you had fun solving the problems with the new Sandbox twist :) This was the first time a reverse coding event was hosted in this **style**! _Feel Free to give some feedback in comments whether you **liked** it, suggestions for **improvement**, or ideas for the **Next** Edition :)_ Here are the official tutorials for the problems. Access the Sandbox here &mdash; [_SANDBOX_](https://tesseract-2k26.vercel.app/sandbox) ### [Problem A: DDR4 Shortage](https://codeforces.me/gym/668703/problem/A) Author: [user:Mr.Quantum_1915,2026-02-01] <spoiler summary="Hint"> Try entering aa and aaa in the sandbox. aa (Length 2) $\to$ 2a (Length 2). No space is saved, so i...
To handle the constraints efficiently, prefix sums and lazy propagation techniques can be used

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

115.
Автор quynhnhu.111207, история, 7 месяцев назад, По-английски
Is this a new segment tree variant or a rediscovery ? ### Hello Codeforces As the title states, I think I may have discovered a very nice segment tree variant, but I am not sure whether it corresponds to something already known. ## Supported Features And Time Complexity - Range query (RMQ): O(log n), more precisely O(log r) - Point update: O(log n) - Push back (append new element at the end): amortized O(1) - Pop back (remove last element): O(1) - 2n+1 memory complexity These are theoretical algorithmic complexities , not including CPU-level behavior (cache effects, branch prediction, etc.) into account. ## Memory | Structure | Memory (units) | |---------------|----------------| | IterSegment | 2000000 | | ForestSegment | 2000001 | ## Benchmark (n = 1,000,000 ; q = 10,000,000) In its optimized version, it has performance comparable to the iterative segment tree, as shown in the benchmark below. You are welcome to copy the benchmark code and test it yourself. | Operation | IterSegment (m...
and a lazy propagation extension): https://github.com/Fuvkfis/Forest-of-segment-tree.git - This

Полный текст и комментарии »

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

116.
Автор sidchelseafan, история, 11 лет назад, По-английски
A conceptual doubt about Segment Trees and Lazy Propagation. Hello everyone, I have a conceptual doubt/problem about Segment Trees and Lazy Propagation in general. I was solving this problem, [problem:52C]. It is a simple Range Minimum Query problem with range updates (Negative numbers are also present). And I submitted two solutions , One which doesn't involve Lazy Propagation and the other one which does. The first one got WA and the second one Ac'ed. I am curious. Have a look at the implementations. Without Lazy Propagation &mdash; [submission:12476539] With Lazy Propagation &mdash; [submission:12477535] Isn't lazy propagation just a technique to do Range Updates Faster ? I had tried my first implementation on many Segment Tree based problems before and it had AC'ed. The TL for this problem is 3s and its very liberal and hence I decided to code a normal Seg Tree without lazy propagation. [Link from where I got my Seg Tree](http://se7so.blogspot.in/2012/12/segment-trees-and-lazy-propagation.html) Don't both of them ...
A conceptual doubt about Segment Trees and Lazy Propagation., without lazy propagation., ). And I submitted two solutions , One which doesn't involve Lazy Propagation and the other one which, Hello everyone, I have a conceptual doubt/problem about Segment Trees and Lazy Propagation in, I have a conceptual doubt/problem about Segment Trees and Lazy Propagation in general. I was, Isn't lazy propagation just a technique to do Range Updates Faster ? I had tried my first, With Lazy Propagation — [submission:12477535], Without Lazy Propagation — [submission:12476539]

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

117.
Автор raashidanwar, 6 лет назад, По-английски
Algorithm Library in C++ Hi all of you. here is some very common algorithms in the form of class. writing those in contests was waste of time so you just need copy and paste the class (modify as per your need) ans use it. [DSU (disjoint Set Union)](https://github.com/raashidanwar/Algorithms/blob/master/dsu.cpp) [Fenwick tree](https://github.com/raashidanwar/Algorithms/blob/master/fenwick_tree.cpp) [Binary trie](https://github.com/raashidanwar/Algorithms/blob/master/binary_trie.cpp) [Convex hull](https://github.com/raashidanwar/Algorithms/blob/master/convexhull.cpp) [Manachers's algorithms](https://github.com/raashidanwar/Algorithms/blob/master/manacher.cpp) [String hashing](https://github.com/raashidanwar/Algorithms/blob/master/hashing.cpp) [Matching](https://github.com/raashidanwar/Algorithms/blob/master/matching.cpp) [Dinic (Maximum flow)](https://github.com/raashidanwar/Algorithms/blob/master/max_flow.cpp) [Segment Tree and Lazy Propagation](https://github.com/raashidanwar/Algor...
[HLD (heavy light decomposition with Segment Tree and Lazy Propagation ](https://github.com, [Segment Tree and Lazy Propagation ](https://github.com/raashidanwar/Algorithms/blob/master

Полный текст и комментарии »

  • Проголосовать: нравится
  • +38
  • Проголосовать: не нравится

118.
Автор tgbaodeeptry, история, 5 лет назад, По-английски
Why my "segment tree lazy propagation range sum" is not working? Hello guys, after learning Segment Tree, I approach to learn segment tree with LAZY PROPAGATION I tried to implemented it by do this task `increase V to all elements in range a to b and get sum of elements in this range`. This is my code: ~~~~~ #include <bits/stdc++.h> using namespace std; struct Node { int val; int lazy; }; struct Segment { int n; Node nodes[400001]; Segment (int n) { this->n = n; for (int i = 0; i <= 4*n; i++) nodes[i] = {0, 0}; } void down(int id) { int t = nodes[id].lazy; nodes[id << 1].val += t; nodes[id << 1].lazy += t; nodes[id << 1 | 1].val += t; nodes[id << 1 | 1].lazy += t; nodes[id].lazy = 0; } void update(int id, int l, int r, int u, int v, int val) { if (l > v || r < u) return; if (u <= l && r <= v) { nodes[id].val += val; nodes[id].lazy += val...
Why my "segment tree lazy propagation range sum" is not working?, Hello guys, after learning Segment Tree, I approach to learn segment tree with LAZY PROPAGATION I, if (u <= l && r <= v) { nodes[id].val += val; nodes[id].lazy += val, nodes[id << 1].val += t; nodes[id << 1].lazy += t; nodes[id << 1 | 1].val += t, nodes[id].lazy = 0; }, struct Node { int val; int lazy; };, void down(int id) { int t = nodes[id].lazy;

Полный текст и комментарии »

  • Проголосовать: нравится
  • -18
  • Проголосовать: не нравится

119.
Автор nsqrtlog, история, 4 года назад, По-английски
Alternative Editorial to 2019 USACO Gold February, Problem 1 (Cow Land) The [official editorial](http://usaco.org/current/data/sol_cowland_gold_feb19.html) to this problem is not asymptotically optimal and involves an advanced concept that's infrequent in USACO Gold. I managed to derive a relatively "low-tech" and faster solution, which I will describe below. ---------------------------------------------------------------------------------------------------------------------- ### [Problem link](http://usaco.org/index.php?page=viewproblem2&cpid=921) ---------------------------------------------------------------------------------------------------------------------- Solution ------------------ for the sake of convenience, let $\sum\limits_u^v$ denote the XOR of all labels on the path from node $u$ to node $v$. **Subtask 1** We want a way to efficiently calculate the XOR of every label along an arbitrary path without modifications. Note that after rooting the tree at an arbitrary root $r$, if we split a path by the LCA of its endpoints,...
any data structure that supports range modification, such as a lazy propagation segment tree

Полный текст и комментарии »

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

120.
Автор kartik8800, история, 7 лет назад, По-английски
(Not So)General Purpose Segment Tree library I have been recently working on preparing libraries for commonly used data structures in competitive programming. here is a link to the code : https://github.com/kartik8800/segTree The above segment tree library should (according to me) work for a huge number of range query problems with point updates. The things you need to specify to declare a segment tree is a function combine that tells the tree how to combine the results of child nodes to form parent node, an array for which the tree is to be constructed and a value such that combine(x, value) = x. Here are a few examples: vector<int> dataVector = {5, -8, 6, 12, -9}; int small(int x,int y){return min(x,y);} <br> SegmentTree < int > rangeMinQueries(dataVector,INT_MAX,small); <br> int sum(int x,int y){return x+y;}<br> SegmentTree < int > rangeSumQueries(dataVector,0,sum);<br> long long product(long long x,long long y){return x*y;}<br> SegmentTree < long long > rangeProductQueries(dataVector,1,product);<br>...
I wonder if it is possible to provide a similar implementation of the segtree withlazy propagation

Полный текст и комментарии »

  • Проголосовать: нравится
  • +35
  • Проголосовать: не нравится

121.
Автор Corvus, история, 8 лет назад, По-английски
[Training] [Arabic] JUST Summer Training 2018 — Segment Tree Hello Codeforces, On July 2018 the JUST Summer Training 2018 was held in the Jordan Univeristy of Science and Technology Presented By Ibraheem Tuffaha [user:Vendetta.,2017-09-02], Covered one topic: Segment Tree. The training is published on youtube on [user:SolverToBe,2018-09-14] channel *note: language of training is Arabic. ### **Lecture 1** <spoiler summary="Segment Tree I"> Part 1 | [Segment Tree &mdash; Range Sum Query](https://www.youtube.com/watch?v=KR7icII-RWI&index=1&list=PLPSFnlxEu99GKcA1y0T9d-sxcUdOyWy3x) Part 2 | [Range Minimum Query &mdash; Problem CodeForces 622C](https://www.youtube.com/watch?v=8QKIAcPyagA&index=2&list=PLPSFnlxEu99GKcA1y0T9d-sxcUdOyWy3x) Part 3 | [Problem CodeForces 597C](https://www.youtube.com/watch?v=WRvpG8DTgzk&index=3&list=PLPSFnlxEu99GKcA1y0T9d-sxcUdOyWy3x) </spoiler> ### **Lecture 2** <spoiler summary="Segment Tree II and Lazy Propagation"> Part 1 | [Problem Sereja and Brackets &mdash; CF 380C](https://www.youtube.com/w...
Part 1 | [Problem Sereja and Brackets, Part 2 | [Lazy Propagation ](https://www.youtube.com/watch?v=yLDdGkT4GkM&index=5&list

Полный текст и комментарии »

  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

122.
Автор srvntofthejudge, история, 7 недель назад, По-английски
LarpQ's Standard Larprary: Square Root and Multi-Root Decomposition Hello everyone! This is the first part of a multi-part blog series dedicated to "mostly useless algorithms". These are algorithms that contain some form of useful use, but are otherwise strictly worse than their peers. This initial episode shall be dedicated to Square Root and Nth-Root Decomposition. These are algorithms that implement $O(m)$ point update, i.e constant point update but $O(n^{1/m} * m)$ range query. Square Root Decomposition is a degenerate case of this: achieving $O(1)$ point update, and $O(\sqrt{M})$ range query. Effectively they are alternatives to Segment and Fenwick tree. With more advanced techniques you could reach $O(\log \log n)$ queries and updates, or as an upper bound, $O(\sqrt{n})$ updates and $O(\log \log \log \log N)$ queries (yes, four logs!) Now, these algorithms are quite simple, so let us begin with square root decomposition. Firstly, many problems can be decomposed into smaller "subproblems" that can be merged. For example, if we have the...
. (Range updates now need a more complicated lazy propagation method, similar to that of a segment tree

Полный текст и комментарии »

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

123.
Автор coder333, история, 6 лет назад, По-английски
How to optimize segment tree when there could be 4 operations applied on it: XOR, AND, OR? I’m trying to solve HackersEarth/CodeMonks problem called Bit operations. Unfortunately, I can't share the link of the problem (it is unshareable, you only can unlock the next section link by solving previously given problems). Here is the problem: You are given an array of size n. Initially, all the elements of the array are zero. You are given q queries, where each query is of the following type: - 1 LRX: For each element in the range [L,R] like y, set y=y|X - 2 LRX: For each element in the range [L,R] like y, set y=y&X - 3 LRX: For each element in the range [L,R] like y, set y=y⊕X - 4 LR: Print the sum of the elements in the range [L,R] - 5 LR: Print the result after performing the XOR operation of the elements in the range [L,R] I have tried to solve this problem via BIt and segment tree and in case of both I'm getting TLE and I got stuck on this problem. Here is my approach using bit: ~~~~~ #include <iostream> #include <vector> using namespace std; ...
Currently, I'm trying to optimize the segment tree-based solution by applying lazy propagation, but

Полный текст и комментарии »

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

124.
Автор McDic, история, 8 лет назад, По-английски
I just constructed my github repository to store my implementations. Hello. Just started to participate contests to fill 25 participation in codeforces, now I even created my github repository to store my implementation :) The link is here: https://github.com/McDic/MyImplementations/ Just wanted to show public, you can freely see or criticize my code anytime. **<2019-08-23>** Now I have following my own implementations: - Trie and Aho Corasick - Segment Tree and Lazy Propagation - Shortest path algorithms such as Dijkstra and Floyd Warshall - Disjoint Set Union - Eratosthenes Sieve (both $O(n \text{ log } n)$ and $O(n)$) - Convex Hull (both Graham Scan and Monotone) - KMP and Polynomial String Hashing - Matrix (but no advanced operations yet) - LCA - and some other uncompleted stuffs My further future implementation goal is: - Minimum Spanning Tree (I don't know why I don't have this in my repository. This is easier, I will implement this asap) - Heavy Light Decomposition (What the heck this is too hard to implement my...
- Trie and Aho Corasick - Segment Tree and Lazy Propagation - Shortest path algorithms such as

Полный текст и комментарии »

  • Проголосовать: нравится
  • -16
  • Проголосовать: не нравится

125.
Автор rangerscowboys, история, 2 года назад, По-английски
What to do for query problems? Howdy Codeforces! Recently, while solving previous Codefoces problems, I have seen many query problems. What I mean by query problems are: you are given q queries, like updating and printing something. This is what I have gathered from query problems: - Arrays can be used for simple query problems. - Prefix sums can sometimes be used for query problems (No Updates Ranged Query) - Sets/Multisets are often used for query problems that need O(logn) operations. - Ordered set is used for some query problems (Point Update Range Query) - Segment tree (with lazy propagation on ranged updates) can be used often for Point Update Range Query, Range Update Point Query, Range Update Range Query. Of course, although segment tree is a solution for many query problems, it isn't easy to code, especially for specialists like me. Me personally, I have started to direct myself to thinking set/multiset first, because it seems to often work. Did I miss any ways to solve query problems? ...
use (with lazy propagation)? Do you all have a different approach to query problems than what I do

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

126.
Автор Duarte, история, 11 лет назад, По-английски
Help problem SegmentTree with lazy Hello everyone, I'm trying to solve the problem http://www.spoj.com/problems/HORRIBLE/, I solved using BIT, but I'm learning about Lazy Propagation and I want to solve using this. I did a code but it is getting WA, and I don't know why. Anyone can help me ? ~~~~~ #include <bits/stdc++.h> using namespace std; typedef long long int lli; typedef vector<lli> vl; class SegmentTree { private: vl st, lazy, A; int n; int left(int p) { return p << 1; } int right(int p) { return (p << 1) + 1; } lli rsq(int p, int L, int R, int i, int j) { if(lazy[p] != 0) { st[p] += (R - L + 1) * lazy[p]; //RMQ = st[p] += lazy[ if(L != R) { lazy[left(p)] += lazy[p]; lazy[right(p)] += lazy[p]; } lazy[p] = 0; } if(i > R || j < L || R < L) return 0LL; if(L >= i && R <= j) return st[p]; return rsq(left(p), L, (L + R) / 2, i, j) + rsq(right(p), (L + R) / 2 + 1, R, i, j); } void updateRange(int p, int L, int R, int i,...
Help problem SegmentTree with lazy, using BIT, but I'm learning about Lazy Propagation and I want to solve using this. I did a code but

Полный текст и комментарии »

  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится

127.
Автор hzyfr, 13 лет назад, По-английски
lazy tag operations on sustainable segment tree I'm learning sustainable data structures now. And I've got the main idea of it, that is to share some common data with the old versions. Now I want to implement lazy propagation on sustainable segment tree and I've got some problems. It is no difference when I put a lazy tag on a sustainable segment tree or a normal tree. But when I want to push down the lazy tag to its children, I can't directly modify the children because old versions use the same memory and it will get WA on queries to the old versions later. So what should I do in such cases? And I think of dynamic allocating new space for these shared part of the tree. Is it a good solution to the problem? And how to connect its subtrees so that will not use too much additional space(it should be at most O(lgn) memory allocated per action)? For example I put a lazy tag on segment [1,8] before and now I want to push down to [1,4] && [5,8] but what will be these new nodes' children? Apparantly keep allocating is not a corre...
lazy tag operations on sustainable segment tree, some common data with the old versions. Now I want to implement lazy propagation on sustainable

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

128.
Автор Neu2daysago, история, 7 месяцев назад, По-английски
Editorial PLC TOC 16 Stage II I made this draft 7 months ago and I haven't published it. I went into some form of depression (cuz of the my stupidity in the final) so I got embarrassed to publish anything about it. But I spent a lot of time in this and since I don't care that much anymore, I'll publish this anyway. Hope you enjoy! A couple of MHT students in Indonesia decided to hold a contest for local Competitive Programming students. It is called PLC TOC 16 and it is inspired by PLC TOC 12. We have prepared original problems for this contest. For people who want to see the problems, it can be seen through links in the editorial. Here is the editorial. [Problems](https://codeforces.me/contestInvitation/dc0ff68270b387e43fb62f61d05ae4a90556e213) [A. PLC Maximum GCD Subarray](https://codeforces.me/gym/670273/problem/A) <spoiler summary="Subtask 1"> <spoiler summary="Hint 1"> How many possible subarrays are there in an array sized $n$? <spoiler summary="Answer"> There is a maximum amount of $n^2...
forgetting to reset the lazy propagation between testcases. And (I'm guessing you read all of it), thank

Полный текст и комментарии »

  • Проголосовать: нравится
  • +9
  • Проголосовать: не нравится

129.
Автор bicsi, история, 11 лет назад, По-английски
Could you help me with some new algorithmic techniques / problems? Hello! I am a fairly advanced programmer (although I'm pretty new), and I know the basic algorithms and data structures used for most problems. However, I don't know how to get better from this state onwards. I should say that my strength is mainly DS problems. Greedy, D&C, DP I do pretty well (once I recognize a specific-type problem), constructive algorithms seem very hard to me (for example [link](http://codeforces.me/contest/573/problem/C)). For DS, I know pretty much all there is to know about segment trees, BIT, sqrt-decomposition (I call it a DS, don't blame me :D), BSTs, hash, etc (the basic ones), although problems that involve advanced tricks with these (e.g. persistent segment trees, lazy propagation) seem very appealing. I want to prepare mysef for this year's ACM-ICPC contest, as it is my first year in Uni. I have been learning algo intensively since December. I would be grateful if you know any good lists of problems that are really crucial and/or teach useful...
, lazy propagation) seem very appealing.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +14
  • Проголосовать: не нравится

130.
Автор SummerSky, 9 лет назад, По-английски
Notes on Codeforces Beta Round #104, Div2- A, B, C, D , E, and Div1- E (Segment Tree with lazy propagation) [problem:146A] We read in the integer as a string and the left work is straightforward implementation. [problem:146B] For $a<b$, the answer is obviously $b$. If $a\ge b$, note that $10^6+b$ is always a potential answer except that it might not be the minimum one. Therefore, we can enumerate integers from $a+1$ and immediately terminate the loop if we find the first integer that satisfies the requirement (the loop will surely be terminated since $10^6+b$ provides an upper bound). [problem:146C] Let us compare the two strings position by position, and denote the total number of indices which lead to difference as $m$. For the first string, its $m$ indices must “contain” $m_1$ 4s and $m_2$ 7s, while for the second string, it becomes $m_1$ 7s and $m_2$ 4s. To achieve the minimum number of operations, we should swap $min(m_1, m_2)$ 4s and 7s while changing the left $max(m_1, m_2)-min(m_1, m_2)$ from 4s to 7s (or from 7s to 4s). Thus, the final answer is in fact $max(m_1, m_2)...
Notes on Codeforces Beta Round #104, Div2- A, B, C, D , E, and Div1- E (Segment Tree withlazy

Полный текст и комментарии »

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится