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

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

Results

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

Full text and comments »

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

2.
By parveen1981, history, 6 years ago, In English
I compiled a list of almost all useful blogs ever published on Codeforces [update: till 09.06.2021] <h3 style="color:red">If there are any blogs that I have missed, please tell in the comment section. Thank you.</h3> # Mathematics Stuff - [Number Theory in Competitive Programming [Tutorial]](https://codeforces.me/blog/entry/46620) - [Number of points on Convex hull with lattice points](https://codeforces.me/blog/entry/62183) - [FFT, big modulos, precision errors.](https://codeforces.me/blog/entry/48465) - [Number of ways between two vertices](https://codeforces.me/blog/entry/19078) - [Mathematics For Competitive Programming](https://codeforces.me/blog/entry/76938) - [FFT and NTT](https://codeforces.me/blog/entry/19862) - [Burnside Lemma](https://codeforces.me/blog/entry/51272) - [Number of positive integral solutions of equation 1/x+1/y=1/n!](https://codeforces.me/blog/entry/76836) - [On burnside (again)](https://codeforces.me/blog/entry/64860) - [Simple but often unknown theorems/lemmas/formula? Do you know?](https://codeforces.me/blog/entry/55912) - [Probabili...
Algorithm on Trees](https://codeforces.me/blog/entry/68271) - [A simple sqrt decomposition, on Trees](https://codeforces.me/blog/entry/68271) - [A simple sqrt decomposition solution to online, ://codeforces.com/blog/entry/85420) - [Sqrt-tree (part 2): modifications in O(sqrtN), lazy

Full text and comments »

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

3.
By zscoder, history, 7 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 1) Hi everyone! Inspired by the recent [Codeforces Round 641](https://codeforces.me/contest/1349), I decided to write an introductory tutorial on generating functions here. I am by no means an expert in generating functions so I will write about what I currently know about them. [user:MiFaFaOvO,2020-05-15] has written a really interesting [blog](https://codeforces.me/blog/entry/76447) here on Codeforces about more advanced applications of generating functions, but I think there is no English tutorial on the basics of this topic yet (or at least on CP sites). Thus, I would like to share about this topic here. I plan to split this tutorial into two parts. The first part (this post) will be an introduction to generating functions for those who have never learned about them at all, and some standard examples and showcases of generating functions. The second part will be a collection of several applications of generating functions in CP-style problems. If you are already familiar with ge...
equation $1-x-x^{2}=0$ (where $\gamma_{1} = \frac{1+\sqrt{5}}{2}$, $\gamma_{2} = \frac{1 - \sqrt{5, formula, we can obtain $C(x) = \frac{1 \pm \sqrt{1 - 4x}}{2x}$. Which sign should we choose? If we, in $C(x)$! Using the quadratic formula, we can obtain $C(x) = \frac{1 \pm \sqrt {1 - 4x}}{2x}$. Which, polynomial operations in $O(n\log n)$ time or $O(n\log^{2} n)$ time like $\sqrt {P(x)}$, $\ln(P(x, (\frac{B(x)}{2}\right) = \exp\left(\frac{\ln(A(x))}{2}\right) = \sqrt{A(x)}$, which is a nice formula!, ) = \exp(D(x))$, so we get the formula $G(x) = \exp\left(\ln\left(\sqrt {\frac{1}{1-x}}\right) - \frac{x}{2, Comparing coefficients, we get $f_{n} = \frac{1}{\sqrt{5}}(\gamma_{1}^{n} - \gamma_{2}^{n, Hence, $C(x) = \frac{1-\sqrt{1-4x}}{2x} = \frac{1}{2x}\left[1 - 1 - \displaystyle\sum_{n \ge 1, In particular, our mysterious function $\sqrt{1-4x} = (1-4x)^{\frac{1}{2}} = \displaystyle\sum_{n, We have shown before that the OGF of the Catalan numbers is $C(x) = \frac{1 - \ sqrt{1-4x}}{2x, }$). You may have heard of Binet's Formula, which states that $f_{n} = \frac{1}{\sqrt{5}}\left[\left

Full text and comments »

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

4.
By Um_nik, history, 2 years ago, In English
On AI ruining "solving math problems with computer" You all went crazy. Instead of arguing with every opinion separately, I just want to ask one question: Why are you doing competitive programming? Is it to get to 1600 rating and put it on the resume? If so, please use AI, cheat, and do everything possible to get to 1600 as soon as possible and get the f**k out of this platform. And if you are (not) a normal person and do competitive programming because it is fun to solve problems, do you think it is fun to copy the problem statement into an AI model prompt and then copy the code it spews to submit? And why do you assume that everyone else will do that if there will be such an opportunity? The same goes for cheaters. Yes, some people do not do this as a sport, for fun. Why do you care? I do think that AI is ruining competitive programming. By proxy. And that proxy is all of you who are running around yelling "We will all die, somebody do something about AI". I have seen a couple of comments saying "authors/coordinators must make s...
fast, which makes us increase limitations in order to show that $O(n \sqrt{n} \log n)$ is actually

Full text and comments »

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

5.
By Arpa, history, 14 months ago, In English
I Filled an Empty Codeforces Page! <div style="float: right;margin: 0 1.0em 1.0em 1.0em;text-align: center;"> <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen="" frameborder="0" height="560" src="https://www.youtube.com/embed/T9UZ21eaZJE" title="YouTube video player" width="315"></iframe> </div> <center> <be> <a href="https://algoritmiacademy.com/wp-content/uploads/2025/09/comments.png"> <img width="50%" src="https://algoritmiacademy.com/wp-content/uploads/2025/09/comments.png"> </a> <br> </center> You might wonder: what kind of _popular_ or _controversial_ topic gets **175 comments**? The answer: <center> <be> <a href="https://algoritmiacademy.com/wp-content/uploads/2025/09/content.png"> <img width="50%" src="https://algoritmiacademy.com/wp-content/uploads/2025/09/content.png"> </a> <br> </center> You are right! [Codeforces edu section &mdash; Community Course](https://codeforces.me/edu/course/3)! Most of ...
Table - SQRT Decomposition - Disjoint Sparse Table It's just a starting point, but hopefully, it, - Sparse Table - SQRT Decomposition - Disjoint Sparse Table

Full text and comments »

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

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

Full text and comments »

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

7.
By lotusblume, 16 months ago, In English
Worst-Case Graphs for Maximum Flow Algorithms Maximum flow algorithms are known to perform significantly better in practice than their worst-case time complexities would suggest. So in this blog, I will present graphs on which the following maximum flow algorithms actually achieve their worst-case running time: | Algorithm | Time Complexity | | ----------------------- | ------------------------------ | | Ford-Fulkerson with DFS | $\mathcal{O}\big(m^2 \cdot U)$ | | Edmonds-Karp | $\mathcal{O}\big(n \cdot m^2\big)$ | | Dinic | $\mathcal{O}\big(n^2 \cdot m\big)$ | | DFS with Scaling | $\mathcal{O}\big(m^2 \cdot \log(U)\big)$ | | Dinic with Scaling | $\mathcal{O}\big(n \cdot m \cdot \log(U)\big)$ | | Most Improving Augmenting Paths | $\mathcal{O}\big(m \cdot \log(U) \cdot (m + n \cdot \log(n))\big)$ | | FIFO Preflow Push | $\mathcal{O}\big(n^3\big)$ | | Highest-Label Preflow Push | $\mathcal{O}\big(n^2 \cdot \sqrt{m}\big)$ | Here and in the rest of this blog: - $n =$ number of vertices, ...
below for the final Anti-HLPP graph. By choosing $l = \Theta(n)$, $k = \Theta(n / \sqrt{m})$ and $w, the maximum flow in this graph. So by setting $w = \Theta(\sqrt{m})$ and $p = \Theta(\log U)$ we, we choose $p \approx \log(\sqrt{U}) = \Theta(\log(U))$, then $w^2$ ($= \Theta(m)$) cannot exceed, $ times. In total the number of augmenting paths is $l\cdot k^2$. So by choosing $k = \Theta(\sqrt{m, (\sqrt{m})$ vertices and add complete bipartite graphs between the groups, instead of the original, -Label Preflow Push | $\mathcal{O}\big(n^2 \cdot \sqrt{m}\big)$ |, 1. $\log(U) = \mathcal{O}(\sqrt{m})$ 2. $m = \mathcal{O}(\sqrt{U})$, 1. $\log(U) = \mathcal{O}(m /\log{m})$ 2. $m = \mathcal{O}(\sqrt{U})$, And the graph sizes are not large enough, such that $\frac{1}{150} n^2 \cdot \ sqrt{m}$ beats $3, The $p = \Theta(\log(U))$ Anti-Shortest-Paths-Graphs each require $\Theta(\sqrt {w^2}) = \Theta, We will choose $w = \Theta(\sqrt{m})$ and $k = \Theta(n / \sqrt{m})$. Therefore, if we are able to, }\big(n^2 \cdot \sqrt{m}\big)$ | Here and in the rest of this blog: - $n =$ number of vertices

Full text and comments »

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

8.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] Collection of little techniques #### Introduction There are a number of "small" algorithms and facts that come up again and again in problems. I feel like there I have had to explain them many times, partly because there are no blogs about them. On the other hand, writing a blog about them is also weird because there is not that much to be said. To settle these things "once and for all", I decided to write my own list about about common "small tricks" that don't really warrant a full tutorial because they can be adequately explained in a paragraph or two and there often isn't really anything to add except for padding. This blog is partly inspired by [user:adamant,2022-03-15]'s [blog](48417) from a few years ago. At first, I wanted to mimic adamant's blog structure exactly, but I found myself wanting to write longer paragraphs and using just bolded sentences as section headers got messy. Still, each section is short enough that it would not make much sense to write separate blogs about each of these things. A...
+ a_n = m$. Then there are only $O(\sqrt m)$ distinct values among $a_1, a_2, \ldots, a_n$., \sqrt n)$., certain magical order, we get $O(n \sqrt n \log n)$ complexity. Unfortunately, this is too slow; also $O, it is easy to see that $k$ is $O(\sqrt{m})$. , sorted in a certain magical order, we get $O(n \sqrt n \log n)$ complexity. Unfortunately, this is too, there can be only $O(\sqrt m)$ rocks (see next point). Now you can use a classical DP algorithm but, (\sqrt n)$., , we divide the array into blocks of length $\sqrt n$. For each block, we maintain the number of, - There exists an increasing subsequence with length $\sqrt{n}$. - There exists a decreasing, 1. Insert an element. Currently $O(\log n)$. Called $O(n \sqrt n)$ times. 2. Remove an element, Suppose that the length of the longest decreasing subsequence $\ell$ and $\ell < \sqrt{n}$. Then we, This proves that if the longest decreasing subsequence is shorter than $\sqrt {n}$, then there, You can use a variant of this idea: we can either find a path with length at least $\sqrt{n

Full text and comments »

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

9.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Data structures Today I want to introduce you some very very useful data structures. In this lecture, we are trying to improve your data structures skills, stay with us and click on **read more**. [cut] Important data structures : Trees ----- Trees are one of the most useful data structures.A tree is a connected-acyclic graph.There are too many types of trees, like : rooted trees, weighted trees, directed trees, tries, etc. Partial sum ----------- There are two types of problems solvable by partial sum. 1.Problems which you are asked to answer some queries about the sum of a part of elements (without modify queries). Solution of all of this problems are the same. You just need to know how to solve one of them. Example : You are asked some queries on an array $a_1,a_2,...a,_n$. Each query give you numbers $l$ and $r$ and you should print $a_l + a_{l+1} + ... + a_r$ . Solution : You need to build another array $s_1, s_2, ..., s_n$ which $s_i = a_1 + a_2 + ... + a_i$ ...
Doing this, we can do a lot of things in $O(\sqrt n)$. Usually we use them in the problems with, Heavy light decomposition -------------------------, Heavy light decomposition is a way to partition a tree's vertices (or edges) in a good way., In this kind of decomposition, we have some chains, and each vertex belongs to only one chain., SQRT Decomposition ------------------, Suppose we have an array $a_1,a_2,...,a_n$ and $k = \sqrt n$. We partition this array into $k

Full text and comments »

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

10.
By Radewoosh, 8 years ago, In English
Blogewoosh #3 Hello, codeforces! This time I've decided to choose a task from my own contest which took place last April and was known as the Grand Prix of Poland. If you want to write this contest virtually in the future, then consider not reading this blog. If you've participated in this contest and maybe even solved this task, then anyway I recommend reading it, cause this task has many very different solutions, each of them being very interesting (in my opinion). It's also a reason why this blog is longer than previous ones. I'll write about task C "cutting tree" (not uploaded to the ejudge yet :/). The statement goes as follows: You are given a tree with $n$ vertices ($1 \leq n \leq 2 \cdot 10^5$). The task is to calculate $f(k)$ for each integer $k$ from the range $[1, n]$ where $f(k)$ is defined as the maximum number of connected components of size $k$ which we can "cut off" from the tree. A connected component of size $k$ is a set of $k$ vertices such that it's possible to traverse ...
$k$ up to $\sqrt{n \cdot \log(n)}$, then we have to do only $O(\sqrt {\frac{n}{\log(n)}})$ binary, are aiming at $O(n \cdot \sqrt{n})$, the idea to calculate first $\sqrt{n}$ values of $f$ with our, imagine heavy-light decomposition). Here comes my freshest observation: in each heavy path we can, implies that for $k \geq$ $\sqrt{n}$, $f(k)$ will not exceed $\sqrt{n}$ (so there are only $\sqrt{n, the value of $f$, $O(\log(n))$ because of binary search and $O(\sqrt{n})$ because this is how many, $ $\sqrt{n}$, $f(k)$ will not exceed $\sqrt{n}$ (so there are only $\sqrt{n}$ possible values of $f(k, So, why is it fast? For each $k$ we look at every of $\sqrt{n}$ components and also each vertex is, To solve this problem without $\sqrt{n}$ factor in complexity we need to use again the fact that $k

Full text and comments »

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

11.
By adamant, history, 19 months ago, In English
Complex FFT is not as bad as you think ... Probably. Hi everyone! As some of you _might_ already know, I don't like NTT. Primary reasons for this are: - I don't like modular arithmetic optimizations (Montgomery, etc). - I don't like NTT mods, and prefer good, old $10^9+7$. - I do like algebra of complex numbers. But, to my regret, the overwhelming mainstream in modern competitive programming is NTT. Primary reasons are: - It's allegedly faster. - It needs less memory. - It has no precision issues. - People don't like algebra of complex numbers. There is nothing I can do about the last, but today I'll address the first 3. Optimizing complex FFT was on my mind for quite some time, but I didn't really work on it _that much_ until the [blog](https://codeforces.me/blog/entry/142063) by [user:Qwerty1232,2025-04-24] on optimizing NTT has dropped, which motivated me to actually put some serious effort into this. In this blog, we will primarily focus on optimizations that are specific to complex arithmetic...
$\sqrt n$ improvement in precision, in a somewhat better grounded manner., (-\frac{M}{2}, \frac{M}{2})$ instead of $x \in [0, M)$. Now, if we keep $m \approx \sqrt M$, we will, = x_0 y_0 + (x_0 y_1 + x_1 y_0) m + x_1 y_1 m^2 $$ So, assume that $m \approx \ sqrt{M}$, then we, \leq \sqrt{8} \varepsilon$., a random walk, meaning that the expected absolute value of the numbers in the output is $\sqrt n C^2, complex number, and estimate $|\delta|=\sqrt{\delta_x^2+\delta_y^2}$, the complex absolute value of, element by $\sqrt[2^k]{i}$, after which we sum up all the intermediate products. I will have to be rather, input numbers being of the form $a+ib$, where $|a|, |b| \leq \frac{\sqrt {M}}{2}$, meaning that the, inputs, the error of FFT is _much_ better. As a matter of fact, *by a factor of $\sqrt n$*. Typical, on the $k$-th layer we have remainders of $A(x)$ and $B(x)$ modulo $x^{n/2^k} - \sqrt[2^k]{i, proportional to $\sqrt n$, rather than $n$, and growth in $L_\infty$ is almost non-existent (essentially, randomization is, generally, insufficient to trigger the $\sqrt n$ improvement, because e.g. when the input, rationale can only really account for improvement in the precision by the factor of $\sqrt{\log n, size of the output by a factor $\sqrt n$, we _should_ as well reduce the absolute error by the same, the same on each layer, and goes as $1$, then $-1$, then $i$, then $-i$, then $\sqrt i$, then $-\sqrt, we will have the sequence of remainders modulo $x^{n/2^k}-\sqrt[2^k]{i}$ , where $\sqrt[2^k]{i}$ is, $$ \sum\limits_{i} |C'_i - C_i| \leq |A_i| \cdot |B_i|\left[(1+\varepsilon)^{4k} (1+\sqrt 5, $$ |(s',t')-(s,t)| \leq |(s,t)| \left[(1+\varepsilon)(1+\sqrt 5 \varepsilon)\left(1+\frac, $$ |(s',t',u',v')-(s,t,u,v)| \leq |(s,t,u,v)| \left[(1+\varepsilon)^2 (1+\sqrt 5 \varepsilon)\left, $$ |A'-A| \leq |A| \left[(1+\varepsilon)^{2k} (1+\sqrt 5 \varepsilon)^k \left(1+\frac{\varepsilon, $$ |x|, |y| \leq \sqrt{\frac{nM}{2}}, $$, $$ |z'-z| \leq |x| \cdot |y| \cdot 3\varepsilon k\left(2 + \sqrt 5\left(1+\frac{1}{3k}\right, $$ |z'-z| \leq |x| \cdot |y| \left[(1+\varepsilon)^{6k} (1+\sqrt 5 \varepsilon)^{3k+1} \left(1, $), $i$ and $-i$ (square roots of $-1$) on the second layer; - $1, -1, i, -i, \ sqrt{i}, -\sqrt{i}, i, It [can be shown](https://inria.hal.science/inria-00120352v2/document) that $|\delta| \leq \sqrt{5, Now, when we're doing $b \omega$, effectively the error of the multiplication up to $(1+\sqrt 5, So, assume that $m \approx \sqrt{M}$, then we have $|x_0|, |x_1| \leq \sqrt {M}$, and thus the, The order in question is $\omega, -\omega, i\omega, -i\omega, \sqrt{i} \omega, -\sqrt{i}\omega, meaning that we can estimate $|C'-C| \leq \delta \sqrt n \log n$ instead of $\delta n \log n, so we have $|\delta| \leq \frac{\varepsilon}{\sqrt{2}}$ for them., {n}{2}-\sqrt c$ and $x^\frac{n}{2}+\sqrt c$., }-\sqrt[2^k]{i}$. In my implementation, it is done in the following manner:

Full text and comments »

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

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

Full text and comments »

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

13.
By ATSTNG, history, 7 years ago, In English
[Tutorial] Matroid intersection in simple words **[This article is also available in [Russian](https://codeforces.me/blog/entry/69287?locale=ru)]** Hello, CodeForces. I think that matroids are beautiful and powerful concept, however, not really well known in competitive programming. I’ve discovered matroids at 2019 Petrozavodsk Winter Training Camp. There was a problem that clearly cannot be solved using usual techniques I knew, editorial for this problem was just these three words “just matroid intersection”. Back then it took me more than 2 days of upsolving to find all the information and details I need and implement solution that gets Accepted on this. And it took way longer to actually understand why does it work and exactly how does it work. (I still hesitate in some details.) Of course, it is not hard to google up all the definitions and some related articles, but in my opinion they all are focused more on mathematical part of theory, strict proofs in some not really obvious but short ways, and observing only ke...
types according to their parity. This loop will always have even length, so decomposition into two, потребуется в $\mathcal{O}(\sqrt{r})$ раз меньше вызовов оракулов, если мы будем строить графы замен лениво., Turns out this optimization actually improves complexity. In total we need $\mathcal{O}(\sqrt{r

Full text and comments »

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

14.
By gepardo, history, 9 years ago, In English
Sqrt-tree: answering queries in O(1) with O(NloglogN) preprocessing. Hello, Codeforces! Some time ago I invented an interesting data structure and I'd like to share it with the community. Maybe, it was known before, and if you knew about it before my blog post, please share the link to the source. # What can the data structure do? Given an array $a$ that contains $n$ elements and the operation $op$ that satisfies associative property: $(x\ op\ y) op\ z = x\ op (y\ op\ z)$ is true for every $x$, $y$ and $z$. So, such operations as $gcd$, $\min$, $\max$, sum, multiplication, $and$, $or$, $xor$, etc. satisfy these conditions. Also we have some queries $l, r$. For each query, we need to find $a_l\ op\ a_{l+1}\ op\ \dots op\ a_r$. Let's call such queries $q(l, r)$. My data structure can process such queries in $O(1)$ time with $O(n \cdot \log \log n)$ preprocessing time and $O(n \cdot \log \log n)$ memory. # How it works? [cut] # ## 1. Sqrt Let's do a sqrt-decomposition. We divide our array in $\sqrt{n}$ blocks, each block ha...
Sqrt-tree: answering queries in O(1) with O(NloglogN) preprocessing., array segment with size $k$ has $\sqrt{k}$ children -- for each block. Also each node contains the, at the end of block $j$. Note that we have $\sqrt{n}$ blocks, so the size of this array will be $O, can be modified to perform modification queries in something about $O(\sqrt {n})$ for modifying a, is $O(\log n)$, not $O(\sqrt{n})$. We use a sparse table instead of $between$ array. We will have $O, tree represents an array with length $k$, then its children have length $\sqrt {k}$. $\log(\sqrt{k, ## 1. Sqrt, (\sqrt{k})$ in size and we keep linear complexity for building the arrays in a segment., Let's do a sqrt-decomposition. We divide our array in $\sqrt{n}$ blocks, each block has size $\sqrt

Full text and comments »

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

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

Full text and comments »

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

16.
By Errichto, 5 years ago, In English
[Tutorial] Square Root Techniques _This is my 100th CF blog!_ This is a list of techniques with $O(\sqrt n)$ time complexity. Watch the lecture https://youtu.be/BJhzd_VG61k, with timestamps! 1. Square root decomposition &mdash; split the sequence into blocks of fixed size. 2. Splitting objects (e.g. vertices) into light and heavy. 3. Square root decomposition by the time of queries & rebuilding the structure. 4. Mo's algorithm &mdash; processing queries in proper order and updating the answer by erasing/inserting new elements. https://cp-algorithms.com/data_structures/sqrt_decomposition.html 5. Strings &mdash; if the sum of lengths is $S$ then there are at most $\sqrt{S}$ distinct lengths. 6. Birthday paradox & baby-step giant-step. See P4 and P6 [here](https://codeforces.me/blog/entry/95571), and see https://cp-algorithms.com/algebra/discrete-log.html. P1. [problem:398D] P2. [problem:220B] P3. <s>[problem:86D]</s> (actually, skip this one because it's boring) P4. Count triangles in a graph, i....
with total length $S$, find a pair where one string is a substring of the other, in $O(S \cdot \sqrt, 1. Square root decomposition — split the sequence into blocks of fixed size. 2. Splitting, This is a list of techniques with $O(\sqrt n)$ time complexity. Watch the lecture https://youtu.be, _This is my 100th CF blog!_ This is a list of techniques with $O(\sqrt n)$ time complexity

Full text and comments »

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

17.
By BLOBVISGOD, history, 3 weeks ago, In English
SQRT decomposition, slightly faster We have all at some point tried to cheese a problem with square root decomposition, only to be met with a TLE verdict. What if I told you that it is possible to make your solution up to $1.5$ times faster, while barely changing anything? Although it is not a huge complexity improvement, a $1.5\times$ difference can often be the difference between AC and TLE if you make sketchy square root complexity solutions, so I think it is still worth sharing. Let us first look at where the cost of a query of regular square root decomposition comes from. A query can be split up into two parts: the $\sqrt{n}$-sized blocks that lie fully within the queried interval, and the single elements at the ends of the interval that are not part of any such block. We will for now assume that the cost of traversing a block and the cost of handling a single element at the ends is approximately the same, and then account for this difference later. ![ ](/predownloaded/f2/79/f279be65e9438d30059072b478b9265f0e3...
SQRT decomposition, slightly faster, Let us first look at where the cost of a query of regular square root decomposition comes from. A, Since $2 \cdot \left(1+2+3+\ldots+\sqrt{n}\right) \approx n$, this comes down to having blocks of, The amount of work done for queries is at most $2\sqrt{gn}$ instead of $3\sqrt {gn}$. Hence, There can be almost $\sqrt{n}$ large blocks to handle, and simultaneously there can be almost, We have all at some point tried to cheese a problem with square root decomposition, only to be met

Full text and comments »

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

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

Full text and comments »

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

19.
By Phantasmagorias, history, 5 years ago, In English
Codeforces Round #745 Editorial I'm very sorry about all the inconvenience, and I would like to bear the blame. Much thanks to those who help me prepare this round. It's not their fault. And much thanks to your participation. [problem:1581A] ------------------ idea: [user:interlude,2021-09-30] preparation: [user:CQXYM,2021-09-30] tutorial: [user:CQXYM,2021-09-30] Assume a permutation $p$, and $\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\forall 1 \leqslant i \leqslant 2n, q_i=2n-p_i$. We can know that $\forall 2 \leqslant i \leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ should be counted. All in all, the half of all the permutaions would be counted in the answer. Thus, the answer is $\frac{1}{2}(2n)!$. The time complexity is $O(\sum n)$. If you precalulate the factors, then the complexity will be $O(t+n)$. ----- <spoiler summary="solution"> ~~~~~ #include<stdio.h> int f[100001]; int m...
this solution. For the trains of $x+y>\sqrt m$, we can modify every period by brute force because, If $x_i + y_i > \sqrt{m}$, the total times of maintenance and running don't exceed $\frac{m}{\sqrt, If $x_i + y_i \le \sqrt{m}$, suppose the train of model $i$ is repaired at $s_i$ day. For a date $t, Thus the intended time complexity is $O(m\sqrt{m})$ and the intended memory complexity is $O(n + m)$.

Full text and comments »

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

20.
By zscoder, history, 7 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 2) Welcome to Part 2 of my tutorial on generating functions. The [first part](https://codeforces.me/blog/entry/77468) focused on introducing generating functions to those without any background in generating functions. In this post, I will demonstrate a few applications of generating functions in CP problems. Let us start with some relatively straightforward examples. Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually $998244353$). Also, $[n]$ denotes the set $\\{1,2,...,n\\}$. ### Blatant Applications in Counting Problems **Problem.** [AGC 005 Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices. For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T$ which contains all vertices in $S$. For all $1 \le k \le n$, find the sum of $f(S)$ over all subsets $S$ with $|S| = k$. Constraints: $n \le 2 \cdot 10^{5}$. <spoiler summary="Solution"> First, ...
$1-x-x^2=0$? We can solve the quadratic equation to get two roots $a+b\sqrt {5}$ and $a-b\sqrt{5}$ for, (actually even in $O(\sqrt{k})$ time)., did to obtain the OGF of Catalan numbers?) to obtain $F(x) = \frac{1 \pm \sqrt {1-4C(x)}}{2C(x)}$., finite limit since $F(0)=1$. Thus, $F(x) = \frac{1 - \sqrt{1-4C(x)}}{2C(x)}$., these $2$ simultaneous equations! An implementation detail is that since we are dealing with $\sqrt{5, $B(a \pm b\sqrt{5})(1 - (a \pm b\sqrt{5}))^{n-1} = a \pm b\sqrt{5}$., $F(x) = \frac{1 - \sqrt{1-4C(x)}}{2C(x)} = \frac{(1 - \sqrt{1-4C(x)})(1 + \sqrt {1-4C(x)})}{2C(x)(1

Full text and comments »

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

21.
By galen_colin, 6 years ago, In English
Hybrid Tutorial #-2: Centroid Decomposition **See the [original post](https://codeforces.me/blog/entry/81317) on Codeforces for a playlist of all similar tutorials and also more information about what this is.** # "Intro" *Timestamp: [00:00](https://youtu.be/-DmMLQCmz94)* This is a "hybrid tutorial" &mdash; it has both a blog and a video component. See my original post for more explanation of what this is and also a playlist of all past tutorials. You can view the full video [here](https://youtu.be/-DmMLQCmz94). This tutorial is on centroid decomposition, a cool concept that has many uses in different problems. It's also another "decomposition" technique, one of many. I feel like this subject in particular doesn't have many great tutorials online that really capture the essence of what we do with the technique, so hopefully, I can improve that with this one. # Notation We'll use $0$-indexing for the whole tutorial, and the example problem will also be $0$-indexed. In addition, "vertex" and "node" mean the same...
Hybrid Tutorial #-2: Centroid Decomposition, centroid decomposition. Root the tree arbitrarily, let's say, at vertex $0$. Then let's maintain, for each, queries. Since centroid decomposition is just a technique rather than an algorithm, this will be, But let's ignore the complexity, we can optimize it later with the actual centroiddecomposition, Centroid decomposition can be used in many ways. This application was a "bottom-up" approach, If you've read other centroid decomposition tutorials, you've probably seen a problem called [Xenia, Other problems can require centroid decomposition in a "top-down" manner — that is, divide, There are other ways to solve this such as sqrt decomposition, but we'll do it with centroid, This tutorial is on centroid decomposition, a cool concept that has many uses in different problems

Full text and comments »

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

22.
By Arpa, history, 10 years ago, In English
Codeforces Round #383 editorial Hello again, and hope you have been Joon-Joon of the round :P **I’m preparing harder version of some of the problems (Div.2 A, B, and Div.1 A, D) and I’ll put them on some gym, so if you are interested in harder version of problems please wait for about one week.** You can see and download the problem archives (pretests, **tests**, statements, validator, checker, **solutions**) [here](https://mega.nz/#F!GoB1gCjK!fE_6d5qSSiqt_HMxAmV9GQ). You can see solutions in solutions folder, note that there are several codes there, there is a descriptor for each code (.desc) that shows the verdict of that code. Preparation details: -------------------- On 25 May [user:Sa1378,2016-12-06] came up with problem Div.1 D and other problems authored inchmeal. 9/25/16: Proposal sent to Gleb. 11/12/16: Answer from Gleb: Your proposal has been redirected to Nikolay [user:KAN,2017-06-02]. 11/15/16: Nikolay has replied, and commented about problems, saying some problems are easy, s...
sqrt decomposition.

Full text and comments »

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

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

Full text and comments »

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

24.
By YouKn0wWho, 4 years ago, In English
[Tutorial] Common Mistakes in Competitive Programming and How to Avoid Them One thing is for sure. You do make mistakes. I also make miskates and that's what makes us human. But what we can surely do is &mdash; to try to minimize the errors that we make throughout our life. I have compiled some of the mistakes that I made in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in C++ as it is the most used language for CP. **So, if you are new to CP, stick with me as you might don't wanna repeat the mistakes that I made when I was a beginner.** #### Mistake 1 Check out the following code: <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int a = 1000'000'000,b = 1000'000'000; long long product = a * b; cout << product << '\n'; return 0; } ~~~~~ </spoiler> The outp...
#### Mistake 21 Using `sqrt()` for integers directly might cause some precision issues and give

Full text and comments »

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

25.
By errorgorn, 4 years ago, In English
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
[Tutorial] Theoretically Faster HLD and Centroid Decomposition, centroid decomposition problems. Thanks to [user:balbit,2022-07-18] for telling me about this technique., centroid decomposition?, let's make the chains long instead. Specifically, create a balanced binary tree of $\sqrt n$ vertices, saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I, ## 1/3 Centroid Decomposition, But the proof of that is exactly the proof that centroid decomposition gives us a centroid tree of, I am unsure why a value of $k$ closer to $\sqrt n$ made the first $3$ codes all faster. Maybe there, Instead of thinking of doing centroid decomposition on vertices, let us consider doing it on edges, It is well-know how to solve this in $O(n \log n + q \log^2 n)$ by using centroiddecomposition, It seems that our complexity would be something like $O(n+q \log(\sqrt n) \log(\ sqrt n))$, which

Full text and comments »

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

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

Full text and comments »

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

27.
By box, history, 6 years ago, In English
[Tutorial] Square root decomposition and applications A brief introduction into the applications of square root decomposition ================== Square root decomposition is the process of separating a structure of size $O(N)$ into $O(\sqrt{N})$ "blocks" of size $O(\sqrt{N})$ each, in a way that aids manipulation of the entire structure. Square root decomposition is extremely versatile. Some of its most well-known use cases are: - answering queries on a static array, with methods such as Mo's algorithm or block precomputation - "lazy" brute force modifications, where it is easy to query an entire block, but tag pushing isn't obvious - separating objects based on a threshold, when there exists both an $O(x)$ algorithm and an $O(n/x)$ algorithm In this tutorial we will walk through multiple types of square root decomposition. Answering queries on a static array, offline (Mo's algorithm) --- Consider a problem where we are asked to find the answer for certain intervals $[l,r]$. We can't quickly compute the answer for an ar...
[Tutorial] Square root decomposition and applications, $O(nB+(n/B)^2)$ memory, $O((n+q)B+(n/B)^2)$. Square root decomposition gives $O((n+q)\sqrt n)$., ================== Square root decomposition is the process of separating a structure of size $O(N)$ into $O(\sqrt{N, consider block decomposition, which would only require insertion., incorporate decomposition into blocks of size $B$:, $$O((n+q)\sqrt[3]{n})$$, $$O(N\sqrt{\frac{N}{\log N}}\log \sqrt{\frac{N}{\log N}}+\frac{N^2}{\frac{\sqrt {N}}{\sqrt{\log N, $$\sum n_i\sqrt m_i\le(\sum n_i)\sqrt{\max m}$$, $O(n\sqrt n)$, )$ such that $a[i]>a[j]$. $O(n\log n\sqrt n)$., /B)$ transitions. Selecting a block size of $B=O(n/\sqrt{q})$ gives us a total transition count of $O, A brief introduction into the applications of square root decomposition ==================, Consider the following scheme for 2D Manhattan TSP: We do square root decomposition on the $x, Do block decomposition on this array into blocks of size $B$. For blocks that are completely, For this problem we need to support point increment/decrement in $O(\sqrt n)$ and prefix sum query, If you have other interesting square root decomposition problems, please share them in the comments, In this tutorial we will walk through multiple types of square root decomposition., Note that the complexity for Mo's with length $n$ queries $m$ is $O(n\sqrt m)$. Because of, Obviously direct precomputation and utilizing $pre[i]$ and $nxt[i]$ arrays lead to an $O((n+q)\sqrt, Selecting $B=O(\sqrt[3]{n})$ gives us a total time complexity of, Square root decomposition is the process of separating a structure of size $O(N)$ into $O(\sqrt{N, There are at most $O(\sqrt n)$ values that occur more than $O(\sqrt n)$ times. Consider a pair $x,y, Total time complexity is $O(n^2/B+qB)$, selecting $B=O(\sqrt n)$ is best, getting a total time, When the data structure for Mo's is small enough, you can use first do block decomposition into, the total time complexity is upper-bounded by $O(n\log n\sqrt m)$. [user:ODT,2020-10-01] claims

Full text and comments »

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

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

Full text and comments »

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

29.
By ko_osaga, history, 4 years ago, In English
Random notes on Lyndon decomposition I recently solved some problems that involved the concept of Lyndon decomposition. Honestly, most of them were too hard to understand for me. I'm just trying to think out loud about things I've read, so I can learn ideas or better takes from smarter people? Note that I will omit almost all proofs as I can't do that. I believe all unproven claims below are facts, but it is always great to have doubts about anything. ## 1. Lyndon decomposition, definition, and algorithms Partly copy-pasted from [this link.](https://cp-algorithms.com/string/lyndon_factorization.html#lyndon-factorization_1) A string is called simple (or a Lyndon word), if it is strictly smaller than any of its own nontrivial suffixes. Examples of simple strings are $a, b, ab, aab, abb, abcd, abac$. It can be shown that a string is simple, if and only if it is strictly smaller than all its nontrivial cyclic shifts. As a corollary, it can be observed that simple words are never periodic (it is not a repetition o...
Random notes on Lyndon decomposition, other string are simple. And if we take the Lyndon decomposition of $\overline{w}$, the first element, removes a simple word, so the algorithm will return a decomposition consisting of simple words. We, rotating at the respective position. This suffix can be found with Lyndon decomposition. Therefore we, the suffix array can be solved in $O(N)$, this gives an $O(N)$ solution to the Lyndondecomposition, ## 1. Lyndon decomposition, definition, and algorithms Partly copy-pasted from [this link.](https, ## 2. Computing Lyndon decomposition for each substring For a string of size $N$, the Lyndon, ## 5. Minimal Rotation from Lyndon decomposition Given a string $S$, what is the lexicographically, ### 1.1 Algorithm There are two algorithms that compute the Lyndon decomposition in linear time, ### 2.1. Lyndon decomposition for all suffixes The removal of a prefix does not change the, ### 2.2. Lyndon decomposition for all prefixes Duval's algorithm is basically incremental since it, ### 2.3 Lyndon decomposition for all substrings? [This paper](https://drops.dagstuhl.de/opus, * lead to an algorithm for computing Lyndon decomposition in near-linear time on output size, by, Alternatively, the Lyndon decomposition of string $s$ can be represented as $s = w_1^{p_1} w_2^{p_2, I recently solved some problems that involved the concept of Lyndon decomposition. Honestly, most, Let $S^R$ be the reverse of $S$. The answer is to take the Lyndon decomposition for $S^R$, and, The Lyndon decomposition of string $s$ is a factorization $s = w_1 w_2 \ldots w_k$, where all, decomposition algorithm, we fix the string $s_1 = s[0 : i)$ and compute the decomposition for the suffix, decomposition given a suffix array. Let $Rank_i$ be the inverse of the suffix array. Then, we can

Full text and comments »

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

30.
By twosquares, 11 months ago, In English
Good Bye 2025 Editorial We'd like to thank you all for participating in the contest, and hope you enjoyed it. Any feedback would be appreciated! <!-- You lost the game. --> <spoiler summary="Rate the contest"> - Great contest: - Good contest: - Average contest: - Bad contest: </spoiler> --- <spoiler summary="Did Franklin (from problem D) succeed in massacring a village of innocent elves like Frieren and Dilhan (from problem E)?"> The official lore is that he got lost in a forest of oddly colored Christmas trees (from problem F) and decided instead to write this editorial. </spoiler> <!-- ########### --> <!-- #PROBLEM A# --> <!-- ########### --> <h2>[problem:2178A]</h2> <spoiler summary="Did you like the problem?"> - Great problem: - Good problem: - Average problem: - Bad problem: - Did not solve: ...
if they are at distanct $\sqrt{k}$. Can you find any special properties that this graph has

Full text and comments »

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

31.
By gepardo, history, 8 years ago, In English
An alternative sorting order for Mo's algorithm Hello, Codeforces! I think many of you know about Mo's algorithm. For those, who don't know, please read this [blog](https://codeforces.me/blog/entry/7383). Here, I consider an alternative (and faster) approach of sorting queries in Mo's algorithm. # Table of contents * [Canonical version of the algorithm](#s1) * [Achieving a better time complexity](#s2) * [Relation to TSP](#s2-1) * [Hilbert curve](#s2-2) * [Benchmarks](#s3) * [Applicability](#s4) <div style="font-size: 1pt"> &nbsp; [cut] &nbsp; </div> <a name="s1"></a> # Canonical version of the algorithm The canonical version of this algorithm has $O((n + q)\cdot\sqrt{n})$ time complexity if insertions and deletions work in $O(1)$. Usually, the two comparators for query sorting are used. The slowest one: ~~~~~ struct Query { int l, r, idx; inline pair<int, int> toPair() const { return make_pair(l / block, r); } }; inline bool operator<(const Query &a, const Query &b) { re...
$n\sqrt{q} < (n + q)\sqrt{n},$, Here is the proof why this works in $O(n\sqrt{q})$ time. Suppose we have $n = 2^k$ and $q = 4^l, The canonical version of this algorithm has $O((n + q)\cdot\sqrt{n})$ time complexity if insertions, We can achieve $O(n\sqrt{q})$ complexity for Mo's algorithm (still assuming that insertions and

Full text and comments »

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

32.
By errorgorn, 5 years ago, In English
[Tutorial] Knapsack, Subset Sum and the (max,+) Convolution **Edit**: I have realized that this blog has been sent quite a lot on discord servers, so I am adding a content page at the start to help organize this blog better. ## Prerequisites Let us first define the classical knapsack, unbounded knapsack and subset sum problems. #### Subset Sum There are $N$ items. The $i$-th item has weight $w_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i = C$. #### Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a set $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. #### Unbounded Knapsack There are $N$ items. The $i$-th item has weight $w_i$ and value $v_i$. Find a **multiset** $S$ such that $\sum\limits_{i \in S} w_i \leq C$ and $\sum\limits_{i \in S} v_i$ is maximized. You should know how to do both versions of knapsack in $O(NC)$ and subset sum in $O(\frac{NC}{32})$ before reading this blog. In this blog post, I will just show some res...
$\sqrt{2C}$ distinct weights. So we can already determine that $M \leq \sqrt {2C}$. Since $occ_i \leq C, $, so we can expect $O(D \sqrt N)$ deviation from the origin (my analysis is very crude). Using bitsets, However, this is actually bounded by $O(\frac{C \sqrt C}{32})$ $^{[1]}$. Consider the set of, It is not hard to see that $|W'| \leq 2 \sqrt {2C} = O(\sqrt C)$, since we only add at most $2, It turns out we can do this in $O(\frac{C \sqrt C}{32})$., Therefore, $\sum\limits_{k=2^z} |S_k| \leq \sum\limits_{z \geq 0} \sqrt \frac{2C}{2^z} = \sqrt {2C, | \leq \sqrt\frac{C}{k}$.

Full text and comments »

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

33.
By -is-this-fft-, 5 years ago, In English
[Tutorial] Proving the inverse Ackermann complexity of Union-Find #### Introduction Most of us are familiar with the union-find data structure and the two optimizations one can do on it: _union by rank_ and _path compression_. Most tutorials will introduce these methods and state that if both optimizations are used, the complexity will be $\mathcal{O}((n + m) \alpha(n))$. Here, $n$ and $m$ are the number of vertices and queries respectively. What is $\alpha$? Generally, we are told that $\alpha$ is some mysterious function that grows very slowly: $\alpha(N) < 5$ where $N$ is the number of subsets of particles in the observable universe and whatnot. What it is is usually not clarified very much. And there is typically no proof (or intuition and other such justifications) as to why the complexity is like that: usually we're told that the complexity analysis is quite long and complicated. At the time of writing, both [cp-algorithms](https://cp-algorithms.com/data_structures/disjoint_set_union.html) and [Wikipedia](https://bit.ly/3EvnzrI) are like th...
- $a_{0, j} = j$ for every $j$; - $a_{1, j} = j \lfloor \sqrt{h} \rfloor$ for every $j$., - There are $\mathcal{O}(m)$ terminal find-edges. - There are $\mathcal{O}(n \ sqrt{h})$ 1, For any vertex $v$, the number of 1-nonterminal find-edges starting at $v$ is at most $\sqrt{h, Similarly, the number of 2-nonterminal find-edges starting at $v$ is at most $\ sqrt{h}$: every 2, That is: there is a checkline of weight 0 between every rank, and once every approximately $\sqrt{h, The number of find-edges is therefore $\mathcal{O}(m + n \sqrt{h})$. If we use union-by-rank, we

Full text and comments »

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

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

Full text and comments »

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

35.
By adamant, history, 5 years ago, In English
Lagrange interpolation and partial fraction decomposition Hi everyone! Today I'd like to write yet another blog about polynomials. Specifically, I will cover the relationship between polynomial interpolation and Chinese remainder theorem, and I will also highlight how it is useful when one needs an explicit meaningful solution for partial fraction decomposition. [cut]<br> #### Lagrange interpolation It's quite well-known that the system $$\begin{cases}P(x_0) = y_0, \\ P(x_1) = y_1, \\ \dots \\ P(x_n) = y_n\end{cases}$$ has a unique solution $P(x)$ among polynomials of degree at most $n$. A direct way to prove that $P(x)$ exists is through Lagrange's interpolation. To have a better grasp of it, let's recall that $P(x) \equiv P(x_0) \pmod{x-x_0}$, thus system becomes $$\begin{cases}P(x) \equiv y_0 \pmod{x-x_0}, \\ P(x) \equiv y_1 \pmod{x-x_1}, \\ \dots \\ P(x) \equiv y_n \pmod{x-x_n}.\end{cases}$$ From the Chinese remainder theorem follows that $P(x)$ is unique modulo $Q(x) = (x-x_0)\dots(x-x_n)$ and is explicitly given ...
Lagrange interpolation and partial fraction decomposition, it is useful when one needs an explicit meaningful solution for partial fractiondecomposition., #### Partial fraction decomposition, Noteworthy, $O(n \log^2 n)$ algorithm to compute partial fraction decomposition was [proposed, Then, the whole partial fraction decomposition can be computed in $O(n \log^2 n)$ with divide and, where $Q_i(x) = \frac{Q(x)}{(x-x_i)^{d_i}}$. Let's get back to partial fraction decomposition. If

Full text and comments »

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

36.
By Al.Cash, history, 11 years ago, In English
Heavy-light decomposition implementation Recently I've been looking for a good heavy-light decomposition code I can just copy-paste and continue to live happily. To my greatest disappointment, I didn't find one and had to write my own. First, there's this blog explaining what HLD is http://blog.anudeep2011.com/heavy-light-decomposition/, but it doesn't contain full code. Also it uses LCA for queries, which is absolutely unnecessary and complicates things too much. Second, there's this implementation https://sites.google.com/site/indy256/algo/heavy_light. (It has been updated, so the comment is related to old version). OK, complete working code, and it doesn't use LCA. But it has too many arrays. Way too many! Also it's mixed with segment tree code, and I'd rather separate the logic. Third, there's this post http://apps.topcoder.com/forums/?module=Thread&threadID=796128&start=0&mc=8. So far the best looking code, but it has only LCA method and no path query handling, which is the point of HLD. [cut] So, I refined the ...
Heavy-light decomposition implementation, -decomposition/, but it doesn't contain full code. Also it uses LCA for queries, which is absolutely unnecessary, Recently I've been looking for a good heavy-light decomposition code I can just copy-paste and

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

39.
By makrav, history, 6 months ago, In English
Niche technique with centroids Hello Codeforces! I was solving [this](https://codeforces.me/gym/102331/problem/J) problem, and the model approach involves HLD solution, however I came up with some interesting approach with centroids. In short, I wrote $dp_{v, cnt, mask}$ where $v$ is vertex in tree in which centroid subtree I am choosing edges, $cnt$ is number of edges that was taken to the matching and $mask$ is mask of vertices which were already taken to some of matching edges, but we only consider those vertexes which have edges to vertices outside of $v$'s centroid subtree. So this solution works in $O(C \log n)$ where $C$ is number of different $dp$ states, which is equal to $\displaystyle\sum_{v=1}^{n} siz_v \cdot 2^{edges}$ where $siz_v$ is size of $v$'s centroid subtree, and $edges$ is number of different edges from tree going outside from $v$'s centroid subtree. Here is the proof that number of different states is $O(n \log^2 n)$. Let me know if you notice any mistakes. Thanks to [user:zwezdinv...
Furthermore, the obtained decomposition still has all the properties of usual centroid

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

44.
By adamant, history, 3 years ago, In English
Dirichlet convolution. Part 1: Fast prefix sum computations Hi everyone! Suppose that you need to compute some sum of a number-theoretic function that has something to do with divisors: $$\begin{gather} \sum\limits_{k=1}^n \varphi(k) = ? \\ \sum\limits_{k=1}^n \sum\limits_{d|k} d^2 = ?? \\ \sum\limits_{x=1}^n \sum\limits_{y=1}^x \gcd(x, y) = ?!? \end{gather}$$ As it turns out, such and many similar sums can be computed with Dirichlet convolution in $O(n^{2/3})$, and in this article we will learn how. Let $f(n)$ and $g(n)$ be two [arithmetic functions](https://en.wikipedia.org/wiki/Arithmetic_function). Let $F(n)$ and $G(n)$ be their prefix sums, that is $$\begin{matrix} F(n) = \sum\limits_{i=1}^n f(i), & G(n) = \sum\limits_{j=1}^n g(j). \end{matrix}$$ We need to compute a prefix sum of the [Dirichlet convolution](https://en.wikipedia.org/wiki/Dirichlet_convolution) $(f * g)(n)$. In this article, we will consider some general methods, and show how to do so in $O(n^{2/3})$ if we can compute prefix sums of $F(n)$ and $G(n)$ in ...
$$ F^{-1}(n) = \frac{1}{f(1)} \left[1 + F(\lfloor \sqrt n \rfloor) F^{-1}(\lfloor \sqrt n \rfloor, $$ O(t) + \sum\limits_{i=1}^{n/t} O(\frac{n^\alpha}{i^\alpha}) + O(\sqrt n) = O\left(t + \frac{n, $$ \sum\limits_{k=1}^{\sqrt[3]{n}} \sqrt{\frac{n}{k}} \sim \int\limits_0^{\sqrt [3]{n}} \sqrt{\frac, $$\begin{align} \sum\limits_{ij \leq n} f(i) g(j) &= \sum\limits_{i=1}^{\lfloor \sqrt n \rfloor} f, $$\boxed{ H(\lfloor n/k \rfloor) = \sum\limits_{i=1}^{\left\lfloor \sqrt {n/k}\right\rfloor} f(i, **Note 1**: There might only be at most $2 \sqrt n$ distinct values of $\lfloor n/k \rfloor, 1. The corner is "concave", that is $\lfloor \sqrt t \rfloor(\lfloor \sqrt t \rfloor+1) \leq t$. It

Full text and comments »

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

45.
By Gheal, 4 years ago, In English
Codeforces Round #875 (Div.1 + Div. 2) Editorial [1831A &mdash; Twin Permutations](https://codeforces.me/contest/1831/problem/A) ------------------ Author: [user:Gheal,2023-05-25] <spoiler summary="Hints"> <spoiler summary="Hint 1"> If $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. </spoiler> <spoiler summary="Hint 2"> Building on the idea from the first hint, can we build a permutation $b$ such that $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$? </spoiler> </spoiler> <spoiler summary="Solution"> Since $a_i+b_i \le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Therefore, any permutation $b$ which satisfies $a_1+b_1=a_2+b_2=\ldots=a_n+b_n$ is a valid answer. If $b_i=n+1-a_i$, then: 1. $b$ is a permutation; 2. $a_1+b_1=a_2+b_2=\ldots=a_n+b_n=n+1$ Consequently, $b=[n+1-a_1,n+1-a_2,\ldots,n+1-a_i,\ldots,n+1-a_n]$ is a valid answer. Time complexity per test case : $O(N)$ </spoiler> <spoiler summary="Code (Gheal, C++)"> ~~~~~ #include<bits/stdc++.h>...

Full text and comments »

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

46.
By jtnydv25, history, 9 years ago, In English
A simple sqrt decomposition solution to online FFT Say we need to solve a recurrence of the form : $$ a_n = f \left (n, \displaystyle \sum_{i=0}^{n-1} a_i b_{n-i} \right ) \mod m $$ Here, $f$ is an arbitrary function which can be computed in $O(1)$. An example of such a problem is [problem:553E]. The tutorial gives a solution in $ N \log ^ 2 (N) $. I recently saw a similar problem in codechef may long [SERSUM](https://www.codechef.com/MAY18A/problems/SERSUM), where I used another technique which I had thought of when I saw the prior problem. In this post I explain this very simple and intuitive sqrt decomposition solution, running in $O(N \sqrt{N \log{N}}) $ which works in almost the same time as $N \log^2(N)$ solution because of a very low constant. Here goes: Let us divide into blocks of size say $K$, giving us a total of $\lceil N / K \rceil $ blocks. Block $t$ consists of $[(t-1)K, tK - 1]$ Let $A_t = \displaystyle \sum_{i=0}^{K t -1} a_i x^i $. Let $C_t = A_{t} B$. When processing the block $t + 1$ we assume th...
A simple sqrt decomposition solution to online FFT, this post I explain this very simple and intuitive sqrt decomposition solution, running in $O(N, Overall complexity = $O(N \log N \frac{N}{K} + N K) $, which is minimized taking $K = \sqrt{N \log

Full text and comments »

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

47.
By PurpleCrayon, history, 5 years ago, In English
Codeforces Round #728 Editorial [problem:1541A] Author: [user:PurpleCrayon,2021-06-25] <spoiler summary="Hint"> The parity (whether $n$ is odd or even) matters. </spoiler> <spoiler summary="Hint"> Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations. </spoiler> <spoiler summary="Hint"> If $n$ is even, the optimal distance is $n$, and if $n$ is odd the optimal distance is $n+1$. </spoiler> <spoiler summary="Solution"> [tutorial:1541A] </spoiler> [problem:1541B] Author: [user:PurpleCrayon,2021-06-25] <spoiler summary="Hint"> $i+j \leq 2 \cdot n$ </spoiler> <spoiler summary="Hint"> The number of pairs $(a, b)$ such that $a \cdot b \leq x$ is $O(x log x)$. </spoiler> <spoiler summary="Solution"> [tutorial:1541B] </spoiler> [problem:1540A] Author: [user:PurpleCrayon,2021-06-25] <spoiler summary="Hint"> What's the minimum value that an edge from $a$ to $b$ can be? </spoiler> <spoiler summary="...
Use sqrt decomposition to optimize it.

Full text and comments »

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

48.
By cry, 3 years ago, In English
CodeTON Round 8 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-03-10] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:oursaco,2024-03-30] | 800 | 1200 | 1500 | 1800 | 2200 | 2400 | 2800 | 2700 | 3400 | | [user:priyanshu.p,2024-03-30] | 800 | 1200 | 1300 | 1600 | 2200 | | | | | | [user:thescrasse,2024-03-30] | 800 | 1200 | 1400 | 1700 | 2100 | 2300 | 2900 | 2900 | 3500 | | [user:cry,2024-03-30] | 800 | 1000 | 1300 | 1700 | 2100 | 2200 | 2800 | 2900 | 3500 | | [user:buffering,2024-03-30] | 800 | 1000 | 1500 | 1900 | 2100 | 2200 | 2700 | 2800 | 3500 | | [user:jaggubandar,2024...
Alternatively, we can do square root decomposition by having $b=\sqrt n$ which leads to an

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

51.
By RP-1, 20 months ago, In English
Sqrt Heuristic for Floor Sums _Thanks to [user:Kapt,2025-04-10] for proofreading this blog._ Recently, I came across a couple of AtCoder problems on modular arithmetic. In short, they both involved sequences $\\{ A, A+C, A+2C, \dots \\}$ modulo $M$. The usual way to deal with these sequences is floor sums: **Problem (Floor Sum).** Calculate $\displaystyle \sum_{k=0}^n \left\lfloor \frac{Ck+A}{M} \right\rfloor$. This is solvable in $O(\log M)$ with a recursive Euclid-like algorithm. If you want to learn more about floor sums, I recommend [this blog](https://asfjwd.github.io/2020-04-24-floor-sum-ap/) by [user:_timelord,2025-04-10]. However, what I want to show you is how you can solve problems like that with a completely different idea. The basis of our reasoning is the following statement: (For the rest of this blog, let $0 \le C, A < M$, $\gcd(C, M) = 1$, $n < M$, just to avoid hassle.) **Statement.** The sequence $\\{A, C + A, 2C + A, \dots, Cn + A\\} \bmod M$ can be split into $O(\sqrt{M})$ d...
Sqrt Heuristic for Floor Sums, progressions. Since $d \le \sqrt{M}$ and $H < \sqrt{M}$, this boils down to $O(\sqrt{M})$., Now let's consider the first $\sqrt{M} + 1$ members of our sequence. By the pigeonhole principle, This also allows us to solve Floor Sum in $O(\sqrt{M})$. Hooray!

Full text and comments »

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

52.
By pajenegod, history, 3 years ago, In English
Tutorial: A simple O(n log n) polynomial multiplication algorithm Hi Codeforces! I have something exciting to tell you guys about today! I have recently come up with a really neat and simple recursive algorithm for multiplying polynomials in $O(n \log n)$ time. It is so neat and simple that I think it might possibly revolutionize the way that fast polynomial multiplication is taught and coded. You don't need to know anything about FFT to understand and implement this algorithm. Big thanks to [user:nor,2023-07-10], [user:c1729,2023-07-10] and [user:spheniscine,2023-07-10] for discussing the contents of the blog with me and comming up with ideas for how to improve the blog =). I've split this blog up into two parts. The first part is intended for anyone to be able to read and understand. The second part is advanced and goes into a ton of interesting ideas and concepts related to this algorithm. Prerequisite: Polynomial quotient and remainder, see [Wiki article] (https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Euclidean_divi...
# Calulate P_minus := P mod (x^(n/2) - sqrt(c)) # Q_minus := Q mod (x^(n/2) - sqrt(c)), # Calulate P_plus := P mod (x^(n/2) + sqrt(c)) # Q_plus := Q mod (x^(n/2) + sqrt (c)), # Recursively calculate PQ_minus := P * Q % (x^n/2 - sqrt(c)) # PQ_plus, $$ \begin{aligned} A(x) \% (x^n - c) = &\frac{1}{2} \left(1 + \frac{x^{n/2}}{\ sqrt{c}}\right, $$ \begin{aligned} \left(1 + \frac{x^{n/2}}{\sqrt{c}}\right) A(x) &= \left(1 + \frac{x^{n/2, $$ \begin{aligned} \left(1 - \frac{x^{n/2}}{\sqrt{c}}\right) A(x) &= \left(1 - \frac{x^{n/2, $$ \begin{align} & P(x) \% (x^{n/2} - \sqrt{c}), \\ & Q(x) \% (x^{n/2} - \sqrt{c, Step 3. Make two recursive calls to calculate $P(x) \, Q(x) \% (x^{n/2} - \sqrt {c})$ and $P(x) \, Q, }}{\sqrt{c}}\right) \left(A(x) \% (x^{n/2} - \sqrt{c})\right) \, + \\ &\frac{1}{2} \left(1 - \frac

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

55.
By tunyash, 14 years ago, translation, In English
Editoral Codeforces Round #122 Please, report me about every grammar mistake, you see. Thank you. **Problem <<Exams>>** Let's notice that $2n \le k \le 5n$. If $k < 3n$ author has to get $2$ on some exams. There are $3n-k$ such exams and that's the answer). If $3n \le k$ author will pass all exams (answer is $0$). **Problem <<Square>>** Let the pencil move by the line and put crosses through every $(n+1)$ point. Lets associate every point on the line with point on square perimeter. Namely, point $x$ on the line will be associated with point on square perimeter that we will reach if we move pencil around square to $x$ clockwise. Then lower left corner will be associated with all points $4np$ for every non-negative integer $p$. Crosses will be associated with points $k(n+1)$ for some non-negative $k$. Nearest point of overlap of two families of points will be in point LCM($n+1$, $4n$). Then we will put $\frac{LCM(n+1,4n)}{n+1} + 1$ crosses. **Problem "Cutting Figure"** Translation by [user:moskupo...
We also can code sqrt-decomposition and obtain complexity $O(n \sqrt{n})$.

Full text and comments »

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

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

Full text and comments »

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

57.
By Errichto, 8 years ago, In English
ROI 2018 in GYM Hi. On Wednesday at [9:05 CET / 8:05 UCT](https://www.timeanddate.com/worldclock/fixedtime.html?day=27&month=3&year=2019&hour=11&min=5&sec=0&p1=166) you can participate in the GYM version of the finals of 2017-2018 Russian Olympiad in Informatics (ROI), Day 1. And on Thursday there will be day 2, same time. Links to GYM contets: [day1](https://codeforces.me/gym/102147) and [day2](https://codeforces.me/gym/102154). 5 hours, 4 problems, IOI-style scoring with subtasks. Statements will be available in three languages: English, Russian, Polish. We wanted to use those problems in a camp in Warsaw so we had to import the problems to some system anyway. Then why not Polygon+Codeforces and thus allowing everybody to participate? Huge thanks to [user:MikeMirzayanov,2019-03-25] for helping me with using GYM. And credits to problem authors: [user:Andreikkaa,2019-05-21] for Radium, [user:Endagorion,2019-05-21] for Viruses, [user:pashka,2019-05-21] for Innophone, Георгий Корнее...
The total complexity is $O(n \sqrt n \log n)$. You can improve it to $O(n \sqrt n)$ if you sort by, decomposition. Before anything happens, let's gather all $b_i$, sort them, and split into buckets of size

Full text and comments »

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

58.
By MikeMirzayanov, 8 years ago, translation, In English
Codeforces: MathJax в постах и комментариях Привет! Мы поддержали отображение LaTeX-формул с помощью [MathJax](https://www.mathjax.org/) в новых постах и комментариях. Теперь формулы будут такие же красивые, как и в условиях задач. Из минусов &mdash; они не сразу отображаются, а переотрисовываются после отображения страницы. Старые посты и комментарии отображаются по старому (уже много старого контента, обратная совместимость очень важна). Замечу, что если вы отредактируете старый пост, то всё равно он будет отображаться в старом стиле. Несколько примеров: $1 \le n \le 10^{12}$,&nbsp;&nbsp;$c = \sqrt{a^2+b^2}$,&nbsp;&nbsp;$i\hbar\frac{\partial}{\partial t}\left|\Psi(t)\right>=H\left|\Psi(t)\right>$.
Here are some example: $1 \le n \le 10^{12}$, $c = \sqrt{a^2+b^2}$, $i\hbar, Несколько примеров: $1 \le n \le 10^{12}$, $c = \sqrt{a^2+b^2}$, $i\hbar\frac

Full text and comments »

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

59.
By FieryPhoenix, 6 years ago, In English
Codeforces Global Round 14 Editorial [problem:1515A] Idea: [user:FieryPhoenix,2021-05-02] <spoiler summary="Tutorial"> [tutorial:1515A] </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; void solve(){ int n,x; int w[101]; cin>>n>>x; int sum=0; for (int i=0;i<n;i++){ cin>>w[i]; sum+=w[i]; } //if the sum is x, we cannot avoid the explosion if (sum==x){ cout<<"NO"<<endl; return; } cout<<"YES"<<endl; //otherwise, the answer always exists //we will keep adding elements from left to right //if we can't add element i, we add element i+1 first by swapping the two for (int i=0;i<n;i++){ if (x==w[i]){ //i+1 will always be less than n because otherwise, the total sum would be x swap(w[i],w[i+1]); } cout<<w[i]<<' '; x-=w[i]; } cout<<endl; return; } int main(){ int T; cin>>T; while (T--) solve(); return 0; } ~~~~~ </spoiler> [problem:1515B] Ide...
bool isSquare(int x){ int y=sqrt(x); return y*y==x; }

Full text and comments »

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

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

Full text and comments »

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

61.
By Maksim1744, 5 years ago, In English
Counting primes in $\tilde{{\cal O}}(n^{2/3}\,\,)$ _Some time ago I read [this](https://projecteuler.net/thread=10;page=5#111677) post about calculating prime-counting function in $O(n^{3/4})$ (you have to solve problem 10 to access the post). And in the end author mentioned that there is $O(n^{2/3})$ solution. To my surprise I was not able to find any more or less relevant information on the internet about that. Maybe there is a beautiful blog describing all of this on 10-th page of google, but I decided to collect information I found in this post._ ###Prerequisites - From [distribution of prime numbers](https://en.wikipedia.org/wiki/Prime_number_theorem) $n$-th prime is approximately $n \ln n$, I will use it while proving complexities. ###$\tilde O(n^{3/4})$ Let's start with $O(n^{3/4})$ approach from Project Euler. We will need some definitions: - $\pi(n)$ &mdash; prime counting function, i.e. number of primes which are not greater than $n$. - $S(n, a)$ &mdash; suppose we take all numbers from $1$ to $n$ and sieve them w...
// return i such that v[i] = x // since v[i] = i + 1 for i <= sqrt(n) and v[v.size() - i] = n, Another fact is that $S(n, \pi(\left\lfloor \sqrt n\right\rfloor)) = S(n, \infty) = \pi(n) + 1, Let's take some integer $\sqrt[3]{n} \leqslant y \leqslant \sqrt{n}$ (we will set it to $\sqrt[3]{n

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

64.
By errorgorn, 6 years ago, In English
Codeforces Global Round 13 Editorial [problem:1491A] ------------------ Setter: [user:syksykCCC,2021-02-28] Prepared by: [user:syksykCCC,2021-02-28] <spoiler summary="Hint 1"> How can we find the largest $k$ such that the $k$-th smallest element of the array is $0$? </spoiler> <spoiler summary="Hint 2"> How can we maintain $k$? </spoiler> <spoiler summary="Solution"> Let's define $cnt$ to represent the number of 1s in the array. For the modifications, if $a_i$ is already $1$ now, then we let $cnt \gets cnt - 1$. Otherwise, let $cnt \gets cnt + 1$. For the querys, just compare $cnt$ with $k$. If $cnt \ge k$, the answer will be $1$. Otherwise, the answer will be $0$. The complexity : $O(n + q)$. </spoiler> <spoiler summary="Code (C++)"> ```c++ #include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; int n, q, a[N], cnt; int main() { scanf("%d%d",&n,&q); for(int i = 1; i <= n; ++i) { scanf("%d",a+i); cnt += a[i]; } while(q--) { int opt, x; ...
Divide the nodes into $\sqrt{n}$ blocks. The $i$-th block will

Full text and comments »

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

65.
By TheScrasse, history, 6 years ago, In English
Editorial of Codeforces Round #701 (Div. 2) [problem:1485A] Author: [user:TheScrasse,2021-02-07]<br> Preparation: [user:MyK_00L,2021-02-07] <spoiler summary="Hint 1"> Suppose that you can use $x$ operations of type $1$ and $y$ operations of type $2$. Try to reorder the operations in such a way that $a$ becomes the minimum possible. </spoiler> <spoiler summary="Hint 2"> You should use operations of type $2$ first, then moves of type $1$. How many operations do you need in the worst case? ($a = 10^9$, $b = 1$) </spoiler> <spoiler summary="Hint 3"> You need at most $30$ operations. Iterate over the number of operations of type $2$. </spoiler> <spoiler summary="Solution"> Notice how it is never better to increase $b$ after dividing ($\lfloor \frac{a}{b+1} \rfloor \le \lfloor \frac{a}{b} \rfloor$). So we can try to increase $b$ to a certain value and then divide $a$ by $b$ until it is $0$. Being careful as not to do this with $b<2$, the number of times we divide is going to be $O(\log a)$. In particular, i...
Complexity: $O(\sqrt x)$.

Full text and comments »

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

66.
By Hexagons, 2 years ago, In English
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...
`game-theory` `sqrt-decomposition` `hashing`

Full text and comments »

Tutorial of OMORI CONTEST
  • Vote: I like it
  • +133
  • Vote: I do not like it

67.
By Arpa, history, 21 month(s) ago, In English
[Tutorial] Ultimate RMQ + Sparse Table Hi Codeforces! I’ve recorded four videos about Range Minimum Query (RMQ) and related topics. These might be helpful for competitive programmers, especially if you’re diving into data structures or optimization techniques. Problem statement: You are given an array $a$ of size $n$. You are also given $q$ queries of type $[l, r)$ as a range. Each query asks for the minimum element of $a$ in the given range. <table> <tr> <td> <a href="https://www.youtube.com/watch?v=Y5-KUvoIWyQ"> <img src="/predownloaded/b1/96/b1962cc85356b5ce1204a7681b984f345be9357b.png"> </a> </td> <td> <a href="https://www.youtube.com/watch?v=tkYmaJ6PO_U"> <img src="/predownloaded/3a/f8/3af844de4aa3193a3f19ab78beaa1f463e9c3bec.png"> </a> </td> </tr> <tr> <td> <a href="https://www.youtube.com/watch?v=GTJeDtXta2Q"> <img src="/predownloaded/51/40/5140a8f8933b2031050661bed9f43baf62c6eb5b.png"> </a> </td> <td> <a href="https://www.youtube.com/watch?v=q67JVVmEwkA"> <img src="/predownloaded/44/...
- Covers fundamentals and basics of RMQ and how sqrt decomposition works.

Full text and comments »

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

68.
By ramchandra, 6 years ago, In English
Ear decomposition tutorial ##### Introduction This tutorial is about ear decomposition, a simple but powerful technique for finding graph connectivity, including 2-vertex-connectivity, 2-edge-connectivity, and strong orientation. In this tutorial we assume we have a connected graph. If the graph is disconnected, the algorithm can be run on each connected component. An _ear_ consists of a path where the endpoints (the first and last vertices) could be the same or different. So a cycle can be an ear. (It is called an "ear" because it is shaped like the human ear.) An _ear decomposition_<sup>1</sup> is a decomposition of a graph into a sequence of ears $C_1, C_2, \dots, C_n$. $C_1$ must be a cycle and each later ear must be either a path between two vertices that are on previous ears, or a cycle with one vertex on a previous ear. Since every edge in an ear belongs to a cycle, an ear decomposition has no bridges. So, a connected graph is 2-edge-connected **iff** it has an ear decomposition containing ...
Ear decomposition tutorial, ##### Finding ear decomposition

Full text and comments »

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

69.
By -is-this-fft-, history, 5 years ago, In English
[Math note] On the relationship between gf and me Today, I want to talk a bit about the relationship between two well-known methods for calculating the $n$-th term of a linear recurrence: **g**enerating **f**unctions and **m**atrix **e**xponentiation. More specifically, I want to explore how these two things are related to one another or how they can be thought of as variants of one another. This blog shouldn't be treated as a tutorial. If you know these algorithms, I doubt that I can teach you to solve some new problem in this blog. Rather, I'm kind of thinking out loud. I think it is a good idea to try to reflect and find connections between different things we have learned. This kind of thinking tends to strengthen the understanding of both methods and makes it easier to improve upon them to solve problems. And I'm sure that what I'm about to present is already quite well-known to some people ;). But when I realized this it was cool to me, so I want to share it. **Problem.** You have two sequences $b_1, b_2, \l...
calculate $\phi$ and $\psi$ using the quadratic formula, they are $\phi = \frac{-1 + \sqrt{5}}{2

Full text and comments »

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