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.

Algorithm

Last visit:  16 years ago
Registered:  16 years ago
2.
By MikeMirzayanov, 3 years ago, In English
Please, read this Hello, Codeforces. Friends. I apologize, but today I will be a bit chaotic and mix personal with public. It just happened that way, I'm sorry. Today, my mother passed away. It's hard for me to write this. Even just seeing it in text makes it feel like something from a nightmare. She was extraordinary. It's difficult for me to articulate it right now, but take my word for it. It felt like all the best qualities one could imagine in a mother converged in her. I don't know any other people so kind, sincere, non-judgmental, capable of love, listening, befriending, supporting, and taking joy in the world around them, and bringing joy to their loved ones. Mom, it's already hard without you, it feels empty. She had glioblastoma. It's an aggressive brain cancer that affects only a few people out of 100,000. I believe, I hope, that science will soon be able to tackle this disease. But for now, this diagnosis is a death sentence. Maybe some of you are or will be associated with medic...

Full text and comments »

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

3.
By Rhodoks, history, 4 years ago, In English
Codeforces Round #810 Editorial Sorry for the late editorial. May this editorial help you. If you have questions, feel free to ask. [problem:1711A] <spoiler summary="hint1."> The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). </spoiler> <spoiler summary="solution"> Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$. </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; } ~~~~~ </spoiler> [problem:1711B] <spoiler summary="hint1."> See the party as a graph. </spoiler> <spoiler summary="hint2."> Divide the vertices into two categories according to their degrees' parity. </spoiler> <spoiler summary="solution"> Let's consider ...
draw a beautiful picture using such algorithm:, vertex. Note our algorithm will guarantee that at every moment every connected component's indices, }{m} \rfloor \geq 3$. In this case, you can draw a beautiful picture using such algorithm: * Sort

Full text and comments »

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

4.
By MikeMirzayanov, history, 2 years ago, In English
Rule Restricting the Use of AI [revision 2024-09-14] It seems that neural networks are working technological wonders. Not long ago, they struggled with even the simplest tasks in our competitions, but now they are reaching new heights that cannot be overlooked. There is reason to believe that progress will continue, and we can expect further advancements in neural networks within the realm of programming competitions. For this reason, we are explicitly limiting the use of AI-based systems (such as various models like GPT, Gemini, Gemma, Llama, Claude, and others) for solving programming problems. However, we recognize that AI can be a valuable tool for learning and coding assistance, so we aim to establish clear boundaries for its use. **Application of this Rule:**<br/>This rule applies strictly to in-contest participation. This includes both registered contestants and out-of-competition participants in any rated Codeforces round. If a round is unrated and this is explicitly stated in the round announcement or rules, the rul...

Full text and comments »

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

5.
By SecondThread, history, 6 years ago, In English
Algorithms Thread 8: Tree Basics (+ Gym Contest) Algorithms Thread Episode 8: Tree Basics ================== Episode 8 of Algorithms Thread [comes out in <90 minutes!](https://youtu.be/MOy4UDjN8DM) This one is a bit more beginner-friendly and covers the following ideas: - Graph/Tree Diameters - Binary Lifting - Tree Flattening with Euler tours Also, to make sure you have actually learned that stuff, I made a [custom Gym set on CodeForces](https://codeforces.me/gym/102694) that will last two weeks that hopefully is really good practice for making sure you have learned this stuff. Here is a link to the gym set; it will be available 45 minutes after the video comes out so that people have time to watch the video before starting the set, if they are interested in penalty points. All of the problems in the gym are original to this set (in their flavortext at least, some are simple enough that I'm sure they have appeared in other contests before). The new gym integration was heavily inspired by [user:Errichto,2020-08-16]'s ...

Full text and comments »

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

6.
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 - [...

Full text and comments »

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

7.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #1 Hello, codeforces! The community wants so the community gets it! :D Here it is, my very first blog about tasks and algorithms. At the beginning I've decided to post my entries on codeforces, maybe I'll switch to something different if it becomes uncomfortable. To pour the first blood I decided to choose a task from one of the old ONTAK camps. Task's name is "different words" ([you can submit here](https://szkopul.edu.pl/problemset/problem/wTy-sxQCIKry0Ml-6RvM0L78/site/?key=statement)). The statement goes as follows: You are given $n$ words ($2 \leq n \leq 50\,000$), every of length exactly $5$ characters. Each character can be a lowercase letter, an uppercase letter, a digit, a comma... basically, it can be any character with ASCII code between $48$ and $122$ (let's say that $k$ is the number of possible characters). A task is to find all pairs of indexes of words which are $\textbf{really different}$. Two words are $\textbf{really different}$ if they differ at all $5$ corres...
character into zero or one and then run our algorithm for $k$ equal to $2$ — match groups of opposite, randomly change every character into zero or one and then run our algorithm for $k$ equal to $2$ &mdash, . Let's calculate the probability of fail if we'd repeat algorithm $600$ times. The probability that we

Full text and comments »

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

8.
By TLE, history, 8 years ago, In English
Linear Recurrence and Berlekamp-Massey Algorithm **#IjustWantContribution** It seems there isn't any blog about Berlekamp-Massey Algorithm around here, so I decided to go on a try. :P Acknowledgement: Hats off to matthew99 for introducing this algorithm. #### What is 'linear recurrence'? Assuming there is a (probably infinity) sequence $a_0,a_1...a_{n-1}$, we call this sequence satisfies a linear recurrence relation $p_1,p_2...p_m$, iff $\forall i \geq m,~a_i=\sum_{j=1}^m a_{i-j}p_j$. (Obviously, if $m\geq n$ any $p$ can do :P) #### How to calculate k-th term of a linear recurrence? For a polynomial $f(x)=\sum_{i=0}^{t} c_ix^i$, we define $G(f)=\sum_{i=0}^{t} c_ia_i$. Obviously $G$ satisfies $G(f)\pm G(g) =G(f \pm g)$. Because $a_i=\sum_{j=1}^m a_{i-j}p_j$, if we let $f(x)=x^m-\sum_{j=1}^m x^{m-j}p_j$, then $G(f)=0$. Also $G(fx),G(fx^2)...=0$. So $G(fg)=0$ (g is any polynomial). What we want is $G(x^k)$. Because $G(f\lfloor x^k/f\rfloor)=0$, then $G(x^k)=G(x^k \bmod f)$. [cut] We can calculate $x^k \b...
Linear Recurrence and Berlekamp-Massey Algorithm, to acquire the exact transition matrix (or maybe just you're lazy enough), and thisalgorithm makes, **#IjustWantContribution** It seems there isn't any blog about Berlekamp-Massey Algorithm around, Acknowledgement: Hats off to matthew99 for introducing this algorithm., It seems there isn't any blog about Berlekamp-Massey Algorithm around here, so I decided to go on a, It's Berlekamp-Massey Algorithm to the rescue! For a given sequence $x_0,x_1...x_{n-1}$, it can

Full text and comments »

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

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

Full text and comments »

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

10.
By maroonrk, history, 3 weeks ago, In English
I will step down as AtCoder Admin [Original Post on AtCoder](https://atcoder.jp/posts/goodbye_maroonrk_en). I'm maroonrk. I have been serving as an admin for AtCoder's Algorithm division since 2021, but I would like to announce that I will be stepping down at the end of January 2027. There are several reasons behind this decision, but the biggest turning point was this year's AWTF. It wasn't because I was devastated by seeing humans lose to AI. Having watched AI's progress, I had expected that this day would eventually come. I won't deny that seeing AI solve every problem was a shock, but even so, I am glad that I had the opportunity to witness that historic moment, and that the problems presented on that stage were ones I had created. That contest left me with a certain sense of accomplishment. I felt that all the effort I had poured into organizing contests over the years had been rewarded by becoming a part of history. At the same time, I began to feel that I needed to take on a new challenge. For a w...
have been serving as an admin for AtCoder's Algorithm division since 2021, but I would like to announce, AtCoder Algorithm Admin maroonrk, I have been serving as an admin for AtCoder's Algorithm division since 2021, but I would like to

Full text and comments »

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

11.
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...
2018](https://codeforces.me/blog/entry/59252) - [O(n) algorithm for finding largest triangle in a, Blog Post Resources about Algorithm and Data Structures](https://codeforces.me/blog/entry/13529, DP (basics)](https://codeforces.me/blog/entry/54154) - [Hirschberg's Algorithm ](https, Trees](https://codeforces.me/blog/entry/52854) - [[Tutorial] Boruvka's Algorithm](https, and easy segment trees](https://codeforces.me/blog/entry/18051) - [Algorithm Gym :: Everything, in O(nlogn)](https://codeforces.me/blog/entry/11337) - [Suffix tree. Ukkonen's algorithm](https, # Mo's Algorithm & Range queries Stuff - [Mo's Algorithm ](https://codeforces.me/blog/entry/7383, ) - [ICPC Graph Mining Challenge solution](https://codeforces.me/blog/entry/79734) - [Algorithm Gym, ++ and Berlekamp–Massey algorithm](https://codeforces.me/blog/entry/65570) - [C++ STL: Policy, ://codeforces.com/blog/entry/85984) - [Simple Linear and Effectively Duval Algorithm for Lyndon Factorization

Full text and comments »

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

12.
By Um_nik, history, 4 years ago, In English
Pro Tips - get them while they are free More tips to use while studying under my tutoring [here](https://um-nik.notion.site/Pro-Tips-8b923b0dc7c94770824bdf4184afc43c). ## Stop caring about the rating Unless there are prizes involved, your position in the standings makes no difference. I can feel awful after winning a contest if I know that I could solve one more problem. Or I can feel OK losing a bunch of rating points knowing that I solved everything I could.  Because rating is just a number. It is highly volatile and it depends on other people, not only on your skill. But solving problems is totally up to you. And you should evaluate yourself not based on some random metric, but on your honest feeling whether you performed up to your expectations. Your sense of self should be under your control, don't get hung up on some imaginary value, you cannot reduce your progress to a single number. ## Don't use more than one account Rating is just a number. Do not be afraid to lose your colour. You’ll get it back in no t...
determine it with 100% certainty from the constraints, and that doesn’t dictate whichalgorithm to use., do is to believe that the problem must be solved with any particular algorithm and only try to come, . What you shouldn’t do is to believe that the problem must be solved with any particularalgorithm, And do not choose an algorithm first and solve the problem later. Algorithms are tools you use to

Full text and comments »

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

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

Full text and comments »

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

14.
By McDic, history, 7 years ago, In English
Codeforces Round #589 (Div. 2) **다시 만나서 반가워요, 코드포스!** (Nice to see you again, Codeforces!) I'm again happy to introduce you to [Codeforces Round #589 (Div. 2)](https://codeforces.me/contests/1228). Please look at following information for details: - This contest will take place on [contest_time:1228]. - The round will be **rated for all Division 2 participants**. - There are **6 problems** and you will have **2 hours** to solve them. Score distribution will be announced later. The listed handles below are contributors. Thank you for all who listed! - **Main author**: ~McDic,2019-09-26 &mdash; I made and prepared all problems. - **Coordinator**: ~arsijo,2019-09-26 &mdash; He is my coordinator again. - **Early phase testers**: ~dorijanlendvaj,2019-09-26 ~tfg,2019-09-26 ~Lawali,2019-09-26 &mdash; They are early phase testers. They mostly focused on test data. - **Late phase testers**: ~_Kuroni_,2019-09-26 ~imbr92,2019-09-26 ~Redux,2019-09-26 ~Dr_Park,2019-09-26 ~Mahotsukai,2019-09-26 ~TOPWINDFLOWER,20...

Full text and comments »

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

15.
By tourist, 3 years ago, translation, In English
Code Weekend #1 <div align="right" margin="20px"> <img align="right" src="/predownloaded/72/f1/72f1f31badb1452243838a0fc2553c04accff164.jpeg" alt="logo" width="300px" height="300px" margin="20px"/></div> Hello everyone! We, the [RGBTeam](https://clist.by/team/Romka,tourist,%E2%88%A83886090/) ([user:qwerty787788,2024-05-21], [user:Romka,2024-05-21] and [user:tourist,2024-05-21]), are huge fans of heuristic programming competitions and are quite saddened by the fact that they are becoming less and less frequent each year. One day, we decided to organize our own competition :) Despite the fact that such ideas often remain just ideas, this time we have a serious mindset, and now we want to invite you all to participate in the first — and hopefully not last — **[Code Weekend #1!](https://codeweekend.dev)** The competition will be held in a format quite similar to ICFPC/Google Hashcode — there will be one problem and several dozen tests for it. You will need to submit just an output according to t...

Full text and comments »

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

16.
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, ...
into $t$. To push this flow back to $s$ the algorithm must relabel a lot of vertices $\Omega(n, maximum flow algorithms actually achieve their worst-case running time: | Algorithm, shuffling the adjacency lists before the start of the algorithm helps? Not really. You can still enforce, $ and then through $q_1$ toward $t$. Of course, the HLPP algorithm will not immediately realize that, Implementing the Ford-Fulkerson algorithm using depth-first search to find augmenting paths is, In total, the DFS with Scaling algorithm requires $\Omega(w^2 \cdot p)$ augmenting paths, to find, The Most Improving Augmenting Paths algorithm always chooses augmenting paths with the largest, The most improving augmenting paths algorithm will find the following six augmenting paths:, This algorithm initializes a threshold $\Delta$ as a large power of two, for example $\Delta = 2, This is the same algorithm, as DFS with Scaling, only that the paths are found with Dinic (i.e, [4] Norman Zadeh. “Theoretical Efficiency of the Edmonds-Karp Algorithm for Computing Maximal Flows, [5] Maurice Queyranne. "Theoretical Efficiency of the Algorithm "Capacity" for the Maximum Flow, ^3)$. (It is important, that the algorithm prioritizes $a_1 \dots a_{k-1}$ over $a_k$ and $b_1 \dots, algorithm will one by one push each of these $w$ flow excesses back through $a_1$ and then into $p_1, | Algorithm | Time Complexity

Full text and comments »

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

17.
By Um_nik, history, 5 years ago, In English
How to practice Competitive Programming [Um_nik version] CP is about solving problems fast. And as absurd as it may sound, I believe that <span style="color:blue">SOLVE</span> and <span style="color:red">FAST</span> are very different and almost independent parts, and you need to practice them separately. Let’s look at some <span style="color:red">contest</span>, like a CodeForces round. For the sake of simplicity let’s assume that every problem has some *difficulty*, which is a numerical value denoting how hard it is, bigger values correspond to harder problems (it is not true, but it is an ok-ish approximation, at least if we consider subjective difficulty for a fixed person). Contests are made for a wide range of participants, and problemsetters strive to make contests interesting for a wide range of participants, which means having a *smooth difficulty gradient*. Well... as smooth as it is possible with 5-6 problems. <spoiler summary="Graph 1"> ![ ](https://s3.us-west-2.amazonaws.com/secure.notion-static.com/677e0ae2-a8df-4874-aff...
-aff5-6ee6263ed2c9/photo_2022-01-07_20.14.38.jpeg?X-Amz-Algorithm =AWS4-HMAC-SHA256&X-Amz-Content-Sha256, /161c72da-a4c7-4b2a-9e36-701926a1d18a/photo_2022-01-07_20.14.28.jpeg?X-Amz- Algorithm=AWS4-HMAC-SHA256&X, /677e0ae2-a8df-4874-aff5-6ee6263ed2c9/photo_2022-01-07_20.14.38.jpeg?X-Amz- Algorithm=AWS4-HMAC-SHA256&X, /bebdd246-50f6-44b1-ac25-757a2558cf94/photo_2022-01-07_20.14.34.jpeg?X-Amz- Algorithm=AWS4-HMAC-SHA256&X

Full text and comments »

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

18.
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 ...
academia. But I don't know whether it's practical. The most popular algorithm is $O(n^2 + n^{1.5

Full text and comments »

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

19.
By neal, 8 years ago, In English
Don't use rand(): a guide to random number generators in C++ Don't use `rand()`. Why? Let's jump right into some code. What value will the following code print, approximately? ~~~~~ #include <cstdlib> #include <iostream> using namespace std; const int ITERATIONS = 1e7; int main() { double sum = 0; for (int i = 0; i < ITERATIONS; i++) sum += rand() % 1000000; cout << "Average value: " << sum / ITERATIONS << '\n'; } ~~~~~ Should be about 500,000, right? Turns out it depends on the compiler, and on Codeforces it prints 16382, which isn't even close. [Try it out yourself](http://codeforces.me/contest/1025/customtest). ### What's happening here? If you look up [C++ documentation on `rand()`](https://en.cppreference.com/w/cpp/numeric/random/rand), you'll see that it returns "a pseudo-random integral value between `0` and `RAND_MAX`." [Click again on `RAND_MAX`](https://en.cppreference.com/w/cpp/numeric/random/RAND_MAX) and you'll see that "This value is implementation dependent. It's guaranteed that th...
/algorithm/shuffle) and pass in your `mt19937` as the third argument; the shufflealgorithm will use, ~~~~~ #include <algorithm> #include #include #include #include, ~~~~~ #include <algorithm> #include #include using namespace std;

Full text and comments »

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

20.
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...

Full text and comments »

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

21.
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...
Consider the algorithm for a fixed $u$. For each child $v$ of $u, blog however, we consider Mo's algorithm. Don't worry, this idea can be applied in many situations, the $k$-th phase of this algorithm, we let $\mathrm{dp}[v]$ be a 64-bit integer that stores whether $v, the whole algorithm!, there can be only $O(\sqrt m)$ rocks (see next point). Now you can use a classical DPalgorithm but, #### 2. Avoiding logs in Mo's algorithm Consider the following problem. Given an array $A$ of, $. We are left with an algorithm that looks roughly like this:, ,$$ so the complexity of this part of the algorithm is $O(n \log n)$., The algorithm has exactly the form as seen above, thus its complexity is $O(C \log C)$, where $C, algorithm](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm) works by pretending that a certain

Full text and comments »

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

22.
By SecondThread, history, 6 years ago, In English
Algorithms Thread 9: Treaps (+ Gym Contest!) Algorithms Thread Episode 9: Treaps ================== Good morning everyone! [Episode 9 of AlgorithmsThread](https://youtu.be/6x0UlIBLRsc) comes out shortly after the Div2 round ends. This episode is on Treaps! It covers: - Fundamentals of Treaps - Splitting and Merging - Range reversing ... and more! I also decided to keep up the super-high quality style and made a [custom gym set](https://codeforces.me/gym/102787) with 5(+2) original problems to make sure you really understand everything that was covered in the lecture. The gym set will be released shortly after the lecture ends, and I hope that the problems will be challenging and fun, even for people who aren't seeing treaps for the first time. If you have any questions or suggestions, feel free to leave them below. I hope you enjoy the problem statements, and, in the spirit of the upcoming holiday, I'll leave you all with this: ![ ](http://wumbogames.github.io/cfPictures/GrimTreaper.png) <hr /> Update:...

Full text and comments »

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

23.
By Ari, history, 6 years ago, In English
On Problems vs. Questions in Competitive Programming: My solution _TL;DR: The most reasonable solution to the problems vs. questions debate is to use none of the currently accepted terms._ As we have seen many times, particularly over the past few days, the task of assigning a label to the activities we perform as competitive programmers is a bigger problem than one might think at first. Time and time again we have seen people questioning what we should call our activities, often to the point of eliciting some rather harsh responses. To give some context to this discussion, I will focus on two of the terms that members of the community have adopted over the years, _problems_ and _questions_. (Sorry task lovers! You have some fine points for sure, we frequently talk about subtasks rather than subproblems or subquestions after all :P). All quotations here are posted anonymously, but if you want to claim ownership of one of them or have one removed, just tell me. If you are familiar with the arguments, feel free to skip to the final section of the...
exist even algorithmic questions like “what’s the complexity of Dijkstra algorithm?” but problems

Full text and comments »

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

24.
By cjj490168650, history, 4 years ago, In English
[Repost] "Justice may be delayed, but it cannot be absent": New Evidence on NXIST's Cheating Scandal _Original post: [「正义可以迟来但不能缺席」:关于 NXIST 的一些新证据](https://zhuanlan.zhihu.com/p/620297880)_ _Translated by GPT-4 with some adjustment. Please inform me if there are any mistakes._ _All links to the invalid repository have been redirected to the backup repository._ **This article provides a logically complete set of evidence, which does not involve any non-public internet resources, regarding the "suspected cheating" incident involving the ICPC Yinchuan Station and ICPC Shenyang Station in 2021. By discovering the suspected GitHub account ([NaokiLH](https://github.com/NaokiLH), renamed to https://github.com/brokenTarget) of a team member from Ningxia Institute of Science and Technology (NXIST) TS 1 team, Lan Hao, two years ago, and by mining and analyzing the commit records of his algorithm competition repo, we have obtained direct evidence that at least 4 questions from the 2021 Yinchuan regional contest set and at least 6 questions (including scrapped questions) from the 2021 Sh...
many people with the same name). After some investigation (such as [his algorithm competition, the commit records of his algorithm competition repo, we have obtained direct evidence that at, their algorithm levels are not very high (both of their algorithm repos had only learned some basic, After July 29, everything returned to normal. NaokiLH started learning Kruskal's algorithm and, What really gave birth to this article was NaokiLH's algorithm competition repo:

Full text and comments »

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

25.
By Radewoosh, history, 5 years ago, In English
My own algorithm — offline incremental strongly connected components in O(m*log(m)) Hello Codeforces! As all of you know, there are so many known algorithms named after people who invented them &mdash; from the easiest ones, like Dijkstra, to the harder ones, like Berlekamp–Massey algorithm. These algorithms were innovative when they were invented, so of course, it's good that they are named after their inventors. But, today, I've seen a blog about the solution to the problem "compute LCS of two strings in time $O((n + k) \cdot \log(k))$, where $n$ is the sum of lengths of the strings, and $k$ is the number of pairs of matching positions in them". To be honest, it a bit pissed me off that even this algorithm is named after its creators. Is it ok to name the solution to every possible problem after its author? I won't judge it. Anyway, I want my very own Radecki algorithm, so let me give it a try. If anyone has ever heard about it &mdash; it's cool. Let me know, and it'll be just another helpful blog on Codeforces. Let's imagine the following problem: there is...
My own algorithm — offline incremental strongly connected components in O(m*log(m)), pairs of matching positions in them". To be honest, it a bit pissed me off that even thisalgorithm, ; from the easiest ones, like Dijkstra, to the harder ones, like Berlekamp–Masseyalgorithm. These, So, do you know any existing papers about this algorithm? If no, I claim that it'll be called, }{2} \rfloor$. Let's use the standard offline algorithm to calculate strongly connected components in, –Massey algorithm. These algorithms were innovative when they were invented, so of course, it's good that

Full text and comments »

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

26.
By pllk, history, 10 years ago, In English
Competitive Programmer's Handbook — a new book on competitive programming Competitive Programmer's Handbook is a new book on competitive programming, written by me. The book is still in progress but almost ready, and I decided to release it now for a wider audience. You can download the book here: https://cses.fi/book.html The book consists of 30 chapters and is divided into three parts. The first part discusses basic topics such as programming style, data structures and algorithm design. The second part deals with graph algorithms, and the third part introduces some more advanced techniques. The book assumes that the reader knows the basics of programming, but no background on competitive programming is required. I think that the book is useful for future IOI participants, as the book covers most topics in the IOI syllabus. The final version of the book will be ready later this year. The PDF version of the book will be available for free also in the future, and in addition, there will be a printed version that will cost something. Before t...
structures and algorithm design. The second part deals with graph algorithms, and the third part, topics such as programming style, data structures and algorithm design. The second part deals with

Full text and comments »

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

27.
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...

Full text and comments »

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

28.
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...

Full text and comments »

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

29.
By HosseinYousefi, 12 years ago, In English
C++ Tricks I see lots of programmers write code like this one: ~~~~~ pair<int, int> p; vector<int> v; // ... p = make_pair(3, 4); v.push_back(4); v.push_back(5); ~~~~~ while you can just do this: ~~~~~ pair<int, int> p; vector<int> v; // ... p = {3, 4}; v = {4, 5}; ~~~~~ [cut] [This](http://codeforces.me/blog/entry/10124) is a great C++11 tutorial for those who want to know more about C++11. #### 1. Assign value by a pair of {} to a container I see lots of programmers write code like this one: ~~~~~ pair<int, int> p; // ... p = make_pair(3, 4); ~~~~~ while you can just do this: ~~~~~ pair<int, int> p; // ... p = {3, 4}; ~~~~~ even a more complex `pair` ~~~~~ pair<int, pair<char, long long> > p; // ... p = {3, {'a', 8ll}}; ~~~~~ What about `vector`, `deque`, `set` and other containers? ~~~~~ vector<int> v; v = {1, 2, 5, 2}; for (auto i: v) cout << i << ' '; cout << '\n'; // prints "1 2 5 2" deque<vector<pair<in...
This library includes many of libraries we do need in contest like `algorithm`, `iostream`, `vector, You don't need to code Euclidean Algorithm for a gcd function, from now on we can use. This

Full text and comments »

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

30.
By brunomont, 6 months ago, In English
Chinese Postman Problem: How I Ran a 180 km Ultramarathon Through Every Street in My City Hello, Codeforces! A couple of years ago, a friend of mine told me that two cyclists had passed through every single street in the center region of the city I live in (Belo Horizonte, southeastern Brazil), on the [third try](https://www.strava.com/activities/1030665876/overview). <spoiler summary="First try"> After ~160 km, they had not completed 1/3 of the goal. [Strava link](https://www.strava.com/activities/976021527). <img src="/predownloaded/8a/53/8a53829f7d78e88808a3ff751b64406ec2fc0efd.png" style="width: 600.0px;max-width: 100.0%;max-height: 100.0%;"> </spoiler> <spoiler summary="Second try"> They were better prepared, but one of the guys was run over by a car (no big injuries). [Strava link](https://www.strava.com/activities/999450285). <img src="/predownloaded/85/8f/858fdcdcfda93cd1d9c7c59db7dbfad9e63d6ea2.png" style="width: 600.0px;max-width: 100.0%;max-height: 100.0%;"> </spoiler> <center> <img src="/predownloaded/8d/5c/8d5cfb677a361654105e49f36f214c35...
Postman Problem and discuss an exact solution: the Edmonds-Johnson algorithm., a weighted variant of an already complicated algorithm (Weighted Blossom), but there are, Final algorithm ------------------, The algorithm (described first by Edmonds and Johnson [1]) is described by the steps below., This constructive proof gives us a polynomial time algorithm to compute such walk. With this, algorithm and got an optimum route out of it. And...

Full text and comments »

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

31.
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$ ...
Algorithm Gym :: Data structures, One) Non-deterministic algorithm : Use Robin-Carp and for check if a suffix is lexicographically, Two) Deterministic algorithm : We sort them $log(MaxLength)$ steps, in the $i-th$ step (counting, ~~~~~ /* Suffix array O(n lg^2 n) LCP table O(n) */ #include #include < algorithm

Full text and comments »

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

32.
By dario2994, 6 years ago, In English
About Problemsetting (for AtCoder and Codeforces) Since the amount of information available about the preparation of a competitive programming contest for AtCoder/Codeforces is very little, I decided to collect here what was my experience. I will try to both describe my experiences and give some general advice to wannabe problemsetters. I hope that this will be useful to future problemsetters who are "out of the loop". Moreover, participants might be curious to know what happens behind the scenes (and maybe the platforms may consider this as a form of constructive feedback). *Acronyms*: - AGC = Atcoder Grand Contest - GR = Codeforces Global Round ### Why I know something about problemsetting? I am in the competitive programming world since ~8 years: I have participated in IOI/ICPC/GCJ and a number of contests on AtCoder/Codeforces (and lately Codechef). I am not a top participant but, being in this world for so long, I know, more or less, all the standard tricks. Recently, I was the author of the *flagship conte...
detailed proof of the solution and a careful description of the algorithm. Even better if it

Full text and comments »

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

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

Full text and comments »

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

34.
By maomao90, 3 years ago, In English
Editorial for Hello 2024 ### [problem:1919a] Author: [user:maomao90,2024-01-02] <spoiler summary="Hint 1"> When does the game end? </spoiler> <spoiler summary="Solution"> Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choices will still be valid. The only way that the game ends is when both players have $0$ coins. Since each operation decreases the total amount of coins by exactly $1$, the only way for Alice to win the game is if $a + b$ is odd. </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; if ((a + b) % 2 == 0) { cout << "Bob\n"; } else { cout << "Alice\n"; } } ...
order. At each time $t$, we will use the following algorithm:, Now that we managed to construct a modified solution which follows the greedy algorithm from time, Suppose there exists an optimal solution that does not follow our algorithm. We will let $OT_{t, i

Full text and comments »

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

35.
By Radewoosh, history, 8 years ago, In English
Blogewoosh #2 Hello, codeforces! All signs in the sky and on the ground indicate that you've enjoyed my first blog, so here is the second one. I've decided to choose a Polish task again, as there are plenty of interesting ones. This time we'll take a look at the "plot purchase" ([you can submit here](https://szkopul.edu.pl/problemset/problem/hwbyoUkNFPXQLOPcw3x5huTR/site/?key=statement)), which is a bit easier, but a few years ago I was very proud of myself when I solved it. The statement goes as follows: You are given a square $n \times n$ grid ($1 \leq n \leq 2000$). In every cell, there is a number from the range $[1, 2 \cdot 10^9]$. You are also given an integer $k$ ($1 \leq k \leq 10^9$). A task is to find a subrectangle of this grid such that the sum of values in this subrectangle lies in the range $[k, 2\cdot k]$ (or report that there is no such subrectangle). Just print coordinates of its opposite corners. [cut] $ $ If the problem would be more difficult, and we'd be asked to fi...
correct answer is to print only this corner. In our algorithm, we could lose it quickly if we'd stay in, we'll run our algorithm on it. Here we'll again use the fact about only positive numbers: if some

Full text and comments »

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

36.
By Monogon, history, 5 years ago, In English
[Tutorial] Blossom Algorithm for General Matching in O(n^3) I have decided to write a tutorial on a topic not even [user:Um_nik,2021-06-29] knows! ([source](https://codeforces.me/blog/entry/92248)) In this tutorial, I will talk about the blossom algorithm, which solves the problem of **general matching**. In this problem, you are given an undirected graph and you need to select a subset of edges (called matched edges) so that no two edges share a vertex, and the number of matched edges is maximized. More common in competitive programming is bipartite matching, which is the same problem but when the graph is guaranteed to be bipartite. In competitive programming, general matching seems to get a lot of hate for being very challenging to implement. However, the blossom algorithm is quite beautiful, and important in the history of algorithm research. It will help if you are already familiar with bipartite matching. I will discuss the high level ideas of the algorithm, but my main focus will be on the tricky implementation details. So you may...
[Tutorial] Blossom Algorithm for General Matching in O(n^3), ideas of the algorithm, but my main focus will be on the tricky implementation details. So you may also, Algorithm Overview ------------------, In summary, the algorithm works like this. We repeat the following process until we fail to find an, In this tutorial, I will talk about the blossom algorithm, which solves the problem of **general, Now that we have the subroutines, let's implement the whole algorithm. First, thealgorithm will, Now that we know what they are, how does the blossom algorithm handle them? It **contracts** them

Full text and comments »

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

37.
By Monogon, history, 6 years ago, In English
[Tutorial] Voronoi Diagram and Delaunay Triangulation in O(n log n) with Fortune's Algorithm What's a Voronoi Diagram? ------------------ Given a set $S$ of $n$ points in the 2D plane, the Voronoi diagram is a partition of the plane into regions. The region associated with a point $p\in S$ contains precisely the points $q$ such that $q$ is closer to $p$ than any other point in $S$. In other words, a point $q$ belongs to the region of its nearest neighbor. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Euclidean_Voronoi_diagram.svg/1024px-Euclidean_Voronoi_diagram.svg.png" width="300px" height="auto"/> The Voronoi diagram can be represented by the planar graph of boundaries between regions. A vertex in this graph is where three or more segments meet (or a point at infinity), and an edge is a segment connecting two of these vertices. The way the regions were defined, we see that a segment contains the points equidistant to two points in $S$, so it is part of their perpendicular bisector. Similarly, a Voronoi vertex is equidistant to three or more v...
[Tutorial] Voronoi Diagram and Delaunay Triangulation in O(n log n) with Fortune'sAlgorithm, hull algorithm, and the disadvantage is that it could require $\Omega(n^2)$ flips in the worst, Fortune's Algorithm ------------------, Fortune's Algorithm Implementation ------------------, In this blog, I will focus on Fortune's Algorithm. It takes a sweep-line approach to the problem, Resources ------------------ - [Fortune's Algorithm Notes](https://www2.cs.sfu.ca/~binay/813.2011, The advantage is that this gives a deterministic $O(n\log n)$ algorithm with only integer, The divide and conquer algorithm first sorts the points by $x$-coordinate. Then it splits the, The main challenge in designing a sweep-line algorithm for Voronoi diagrams is that a point after

Full text and comments »

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

38.
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...
To solve this problem, use NTT and polynomial inversion algorithm is just ok. Each time we, ~~~~~ #include #include <algorithm>

Full text and comments »

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

39.
By andreyv, 12 years ago, translation, In English
Catching silly mistakes with GCC As you know, the C++ language assumes that the programmer is always correct. Therefore C++ compilers don't add additional checks to the program, such as checks for null pointer dereference or out-of-bounds array access. This is good, because C++ programs run as fast as possible, and this is bad, because sometimes we may spend a long time debugging some silly mistake. We would want that the compiler can find such mistakes automatically. And many compilers can! In this post I will show various GCC options that do this. Previously [user:zakharvoit,2015-01-02] already wrote about this [here](/blog/entry/13875). All options that will follow should be added to the GCC command line. In various IDEs you can do it in IDE or compiler settings. Many of the options can also be used with Clang (for example, in Xcode). For MSVC++, I think, there is nothing better than Debug mode and `/W4`. [cut]   GCC warnings ------------------ Of course, the first step to debugging is to enable compi...

Full text and comments »

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

40.
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...
An alternative sorting order for Mo's algorithm, <> # Canonical version of the algorithm, # Table of contents * [Canonical version of the algorithm](#s1) * [Achieving a better time, As you can see, such sorting order doesn't make Mo's algorithm work slower, and when $q$ is, Here, I consider an alternative (and faster) approach of sorting queries in Mo's algorithm., I think many of you know about Mo's algorithm. For those, who don't know, please read this [blog, Let's compare the canonical version of Mo's algorithm and the version with Hilbert order. To do, Now we can see the relationship between Mo's algorithm and [TSP](https://en.wikipedia.org/wiki, 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

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

Full text and comments »

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

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

Full text and comments »

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

43.
By jiry_2, history, 9 years ago, In English
A simple introduction to "Segment tree beats" Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this comment](http://codeforces.me/blog/entry/54750?#comment-387957). Sorry for the long delay, as a sophomore in Peking University, I've just finished a tired semester and a painful final exam. And now I finally have enough time to do a simple introduction to this interesting algorithm. It may be a huge project for me since my English is not good. I think I will finish this blog in several steps and I will try to finish it as soon as possible :) In China, all of the 15 candidates for the Chinese National Team are asked to write a simple research report about algorithms in informatics Olympiad, and the score will be counted in the final selection. There are many interesting ideas and algorithms in these reports. And I find that some of them are quite new for competitors in CF although they are well known in China from the final standings of some recent contests. For example, In the last co...
finally have enough time to do a simple introduction to this interesting algorithm., In this part, we will proof the algorithm showed in Part 2 of this problem is $O(n \log n

Full text and comments »

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

44.
By Monogon, history, 5 years ago, In English
[Tutorial] Graph Potentials, Johnson's Algorithm, and Min Cost Max Flow In this tutorial I'll introduce potentials as it applies to directed graphs and discuss a few of its applications. I haven't seen many resources about this topic, so I decided to write one. Prerequisites: - Shortest path algorithms ([Dijkstra](https://cp-algorithms.com/graph/dijkstra.html) and [Bellman-Ford](https://cp-algorithms.com/graph/bellman_ford.html)) - For the Min Cost Max Flow section, you should be familiar with [Ford-Fulkerson](https://cp-algorithms.com/graph/edmonds_karp.html). But you can benefit from this blog with just the Johnson's Algorithm section if you're not familiar with flows. Introduction ------------------ For notation, let's say there is a weighted, directed graph $G=(V,E)$. Let $n=|V|$ and $m=|E|$. For simplicity, let's assume there are no loops or multiple edges between the same pair of nodes in the same direction. For an edge $u\to v$, we will use $w(u\to v)$ to denote its weight. Let's motivate the idea of a potential, so the definition d...
[Tutorial] Graph Potentials, Johnson's Algorithm, and Min Cost Max Flow, can benefit from this blog with just the Johnson's Algorithm section if you're not familiar with, upvote back!" But remember, we're trying to compute all-pairs shortest paths. Running analgorithm, , it's optimal to do the simple $O(n^2)$ Dijkstra algorithm which doesn't use any heap., - Johnson's Algorithm - https://codeforces.me/gym/101498/problem/L - MCMF - https, - [Johnson's Algorithm](https://en.wikipedia.org/wiki/Johnson%27s_algorithm) (Wikipedia, Johnson's Algorithm ------------------, Johnson's Algorithm solves this problem more efficiently for sparse graphs, and it uses the, Overall, step 3 is the bottleneck and Johnson's algorithm has complexity $O(nm\log n)$ (or $O(n^2, algorithm can give incorrect results, and we typically use Bellman-Ford instead, which has a worse, algorithm to get correct distances. We simply run Dijkstra's algorithm once for every vertex $u$, to get

Full text and comments »

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

45.
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...
Example $1$ : [Perfect Permutations, Subtask 4](https://www.hackerearth.com/problem/algorithm

Full text and comments »

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

46.
By heuristica, history, 6 years ago, In English
Heuristic algorithm for Hamiltonian path in directed graphs (It's a translated version of my blog at https://peehs-moorhsum.blog.uoj.ac/blog/6384. ) Finding a Hamiltonian path in a directed graph is a well-known NP problem. However, about a year ago, I came up with the following heuristic algorithm which has GREAT performance on random graphs(by first generating a hamiltonian path, adding random edges, then randomly permuting indices) and many CP problems. Here is the idea of the algorithm: We maintain a subset $S$ of edges, ensuring there's no cycle and each vertex has in-degree and out-degree at most 1. Whenever $|S|$ reaches $n-1$, we find a hamiltonian path. We start with $S$ empty. Each time we pick a random edge $e \notin S$. If we can add $e$ to $S$ without violating any rule, we simply add it to $S$. Otherwise, if $e$ won't create a cycle and violate with exactly one edge e', we replace e' with $e$ with 50% probability. Repeat until $|S|$ reaches $n-1$. We can use LCT to check cycles. Here's my code, which takes le...
Heuristic algorithm for Hamiltonian path in directed graphs, Here is the idea of the algorithm:, However, about a year ago, I came up with the following heuristic algorithm which has GREAT

Full text and comments »

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

47.
By Lewin, 11 years ago, In English
Wunder Fund Round 2016 Hello Codeforces! I invite all of you to participate in a **special** Codeforces round. It will take place on [29 Jan, 17:05 UTC](http://www.timeanddate.com/worldclock/fixedtime.html?day=29&month=1&year=2016&hour=20&min=5&sec=0&p1=166). It will not be a usual round. Thanks to Wunder Fund, the best participants will win prizes and souvenirs. Here are some words from <a href="http://wunderfund.io/">Wunder Fund</a>: <img src="http://assets.codeforces.com/images/optimization.jpg" style="float:right; margin: 0 1em;"/> > Our company is situated in the center of Moscow. We are engaged in high-frequency trading &mdash; developing high-performance systems and algorithms for automated trading in financial markets. In this area algorithms and data structures (that you love to invent and implement) are vital. Our systems should process transactions in milliseconds! High-frequency trading is a continuous competition of the best programmers and mathematicians around the world. By joining us...

Full text and comments »

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

48.
By -is-this-fft-, history, 7 years ago, In English
[Tutorial] The DFS tree and its applications: how I found out I really didn't understand bridges #### Introduction This is a tutorial/exploration of problems that can be solved using the "DFS tree" of a graph. For a way too long time, I didn't really understand how and why the classical algorithm for finding bridges works. It felt like many tutorials didn't really explain how it works, kind of just mentioned it in passing and quickly just moved on to implementation. The day someone explained what the DFS tree is, I finally understood it properly. Before, it took me ages to implement bridge-finding properly, and I always had to look up some detail. Now I can implement it at typing speed. But more importantly, I began to see how the same techniques can be used to solve graph problems that have more or less nothing to do with bridges. The thing is, when you have a black box, you can only ever use it as a black box. But if you have a box that you understand well, you can take it into pieces, repurpose the pieces for completely different things, all without getting lost...
This gives rise to the classical bridge-finding algorithm. Given a graph $G$:

Full text and comments »

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

49.
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) ...
Algorithm Gym :: Graph Algorithms, #### Dinic's algorithm, ). You can prove this algorithm using induction., **Six) Tarjan's algorithm $O(n a(n))$ ($a(n)$ is the inverse ackermann function)**, BFS is another search algorithm (Breadth First Search). It is usually used to calculate the, Bellman-Ford is an algorithm for single source shortest path where edges can be negative (but if, Each algorithm has complexities $$, it means that this algorithm's preprocess is, Floyd-Warshal algorithm is an all-pairs shortest path algorithm using dynamic programming., For this propose we can use RMQ problem, and the best algorithm for that, is to use Sparse table., Here is Dinic's algorithm as you wanted., In this algorithm, first of all we run DFS on the graph and sort the vertices in decreasing of, In this algorithm, first we sort the edges in ascending order of their weight in an array of edges., SPFA (Shortest Path Faster Algorithm) is a fast and simple algorithm (single source) that its, Tarjan's algorithm is offline; that is, unlike other lowest common ancestor algorithms, it requires, The most useful and fast-coding algorithm for finding SCCs is Kosaraju., The origin of this algorithm is unknown. It's said that at first Chinese coders used it in, This algorithm is a single source shortest path (from one source to any other vertices). Pay, This is the most useful and simple (among fast algorithms) algorithm., While running DFS, we assign colors to the vertices (initially white). Algorithm itself is really

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

52.
By antontrygubO_o, history, 7 years ago, In English
On problemsetting 2 [Previous part](https://codeforces.me/blog/entry/70178) Hi there again! Previous part with opinions of some amazing problemsetters turned out to be interesting for you, so I decided to gather some more opinions :D. I really hope that this post will help someone in their problemsetting future! #### When and how did you start problemsetting? [user:300iq,2020-01-11]: April, 2017 [user:maroonrk,2020-01-11]: In 2015 Summer, I hold the first contest with friends at high school club. It was a local Japanese contest. [user:Radewoosh,2020-01-11]: In high school, so probably for 5 years. I was creating problems for other people from my school as my teacher told me that it's a completely different point of view. [user:voidmax,2020-01-11]: It was 3 years ago. I was on plane and I didn't have a clue what to do in my free time. Then I realized that I can try myself in problemsetting. Later I created first and one of my favorite problem ([problem:963B]). I was full of inspiration a...
by tasks like "Do you know this particular algorithm?", or "Can you implement this in 1 hour, Firstly I have some algorithm or beautiful structure of something in mind, then create a problem

Full text and comments »

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

53.
By animeshf, history, 11 years ago, In English
Mo's Algorithm on Trees [Tutorial] Introduction ------------ Mo's Algorithm has become pretty popular in the past few years and is now considered as a pretty standard technique in the world of Competitive Programming. This blog will describe a method to generalize Mo's algorithm to maintain information about paths between nodes in a tree. Prerequisites ------------- Mo's Algorithm &mdash; If you do not know this yet, read this amazing [article](http://blog.anudeep2011.com/mos-algorithm/) before continuing with this blog. Preorder Traversal or DFS Order of the Tree. Problem 1 &mdash; Handling Subtree Queries ------------------------------------------ Consider the following problem. You will be given a rooted Tree $T$ of $N$ nodes where each node is associated with a value $A[node]$. You need to handle $Q$ queries, each comprising one integer $u$. In each query you must report the number of distinct values in the subtree rooted at $u$. In other words, if you store all the values in the subtree rooted...
Mo's Algorithm on Trees [Tutorial], doing a Preorder traversal and then implement Mo's Algorithm. Maintain a lookup table which, If you aren't sure about some elements of this algorithm, take a look at this neat [code](http, Mo's Algorithm has become pretty popular in the past few years and is now considered as a pretty, Mo's Algorithm — If you do not know this yet, read this amazing [article](http, The Algorithm -------------, [Original Post](http://www.animeshf.com/posts/mo-s-algorithm-on-trees) [Related Blog](http

Full text and comments »

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

54.
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...
can make an algorithm out of. - Solve the new and simpler problem directly, with DP, greedy or, , possibly a greedy algorithm or DP., 1. Concrete algorithms (Kruskal's algorithm, Li-Chao tree, fast Fourier transform) 2. General

Full text and comments »

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

55.
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...
for someone in the community, as I think that it is a beautiful algorithm and concept that is, overhead in the linear part of the algorithm, which is why I only use it on _large_ arrays, on which the, we'd really want to use something so tight, as any deviation from the specific algorithm that we

Full text and comments »

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

56.
By adamant, history, 2 years ago, In English
CP-Algorithms: Hacktoberfest 2024 + call for contributors and maintainers Hi everyone! <img src="/predownloaded/82/15/821540e8f87d8a2b2d468377aacbba80b0aa1623.png" style="float:right;" width=100px> I'm posting this on behalf of **[CP-Algorithms](https://cp-algorithms.com/)**, a community project that [started off](https://codeforces.me/blog/entry/13198) in 2014 by [user:RodionGork,2024-10-13] as a translation of [e-maxx](http://e-maxx.ru/), a Russian go-to resource at the time by [user:e-maxx,2024-10-13] for learning core competitive programming algorithms. Since then, CP-Algorithms grew quite a lot (which also prompted a rename from original project name `e-maxx-eng`) and includes a lot of new, original articles, and a lot of translated articles were enhanced and/or extended or even completely rewritten, amounting to a total of 157 articles at the moment. At the moment, the project is largely maintained by [user:Jakube,2024-10-13] and [user:adamant,2024-10-13] (that's me), but as it happens, we don't have as much time to dedicate to it as we used...

Full text and comments »

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

57.
By -is-this-fft-, history, 6 years ago, In English
How to ask for help in PM There was a blog today with a similar title, and although it was (I think, not really sure as I didn't get a good look) some kind of satire/joke blog, I wanted to post some serious advice about things I (don't) like to see when people are PMing me. However I decided that this wouldn't be in the spirit of the blog and decided to make a separate blog. And now that blog is deleted anyway. While it's not a bad thing to write messages to more experienced users, most people who write me do things that make them very difficult to deal with. These are my opinions, but somewhy I feel that many reds will agree. Some things here feel silly to write because they are so obvious. But I'm only writing them because people regularly mess them up. [cut] $~$ ####Use punctuation and spelling. There are some [very simple rules](https://codeforces.me/blog/entry/82186#comment-689836) that make your messages infinitely more readable. I find it especially strange when many of these messagers call...
capacity to understand this advanced algorithm or DS., likely to be able to answer technical questions (specifics of some problem, solution,algorithm...) than

Full text and comments »

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

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

Full text and comments »

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

59.
By Radewoosh, history, 6 years ago, In English
Special place for algorithm explanations/tutorials — feature proposal There are many blogs on Codeforces, and most of them aren't very important a long time after publishing, like round announcements, saying "hello", asking for a better explanation of problem B than the one in the editorial, and so on. Among them, there are a few very interesting blogs that are a great resource of knowledge, like [ODE by MiFaFaOvO](https://codeforces.me/blog/entry/76447), [HLD by Vladyslav](https://codeforces.me/blog/entry/12239), [suffix automaton by quasisphere](https://codeforces.me/blog/entry/20861) or even Blogewooshes. In my opinion, it would be great if there would be a special place for such blogs, accessible for example, by navigation bar, where they would be somehow sorted. It would be much easier to think "Let's learn something new!" and to do it. Also, probably Codeforces would have the greatest such base for competitive programmers. What do you think guys and [user:MikeMirzayanov,2020-06-04]? **EDIT** One more argument after thinking a bit more: of ...
Special place for algorithm explanations/tutorials — feature proposal

Full text and comments »

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

60.
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...
also returns as `int`. Check [this](https://en.cppreference.com/w/cpp/algorithm /accumulate) out for

Full text and comments »

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

61.
By -is-this-fft-, 4 years ago, In English
[Tutorial] My way of understanding Dinitz's ("Dinic's") algorithm **Part 1: [Tutorial] My way of understanding Dinitz's ("Dinic's") algorithm** [Part 2: [Tutorial] Minimum cost (maximum) flow](https://codeforces.me/blog/entry/105330) [Part 3: [Tutorial] More about minimum cost flows: potentials and Dinitz](https://codeforces.me/blog/entry/105658) #### Introduction My philosophy on writing blogs is that I only write blogs when I feel that I have something new and interesting to contribute. This is usually not the algorithm itself, of course, but it can be that I recently found or heard of a new perspective or I figured out a way to explain something in a new way. This is in contrast to my dear colleagues at GeeksForGeeks who write the most low-effort (and often wrong) tutorial on everything and then sit at the top of Google results using their somehow world-class SEO. This is one such case. I have an idea how to explain Dinitz's algorithm in a way I haven't heard of before (but it is not very hard to come up with, so this is...
[Tutorial] My way of understanding Dinitz's ("Dinic's") algorithm, greedy algorithm is wrong., #### Dinitz's algorithm, #### The Universal Max-Flow Algorithm template, **Algorithm 8.** Given a flow network $(G, c, s, t)$., **Algorithm 9.** Given a flow network $(G, c, s, t)$., **Finding a flow in $D$.** This algorithm is best described in pseudocode., , all that is left is to prove that the algorithm terminates and we have a valid max-flowalgorithm., From the point of view of the correctness of the algorithm, this "layered" structure is not, This algorithm is often called the _blocking flow_ algorithm or called "finding the blocking flow"., We start with a slow algorithm and then work our way towards a better one.

Full text and comments »

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

62.
By GlebsHP, history, 4 years ago, In English
Nebius Welcome Round (Div. 1 + Div. 2, rated, t-shirts!) Hello, Codeforces! [user:Zlobober,2023-03-09] and I are glad to invite you to compete in Nebius Welcome Round (Div. 1 + Div. 2) that will start on [contest_time:1804]. The round will be rated for everyone and will feature 8 problems that you will have 2 hours to solve. I feel really thrilled and excited about this round as this is the first time I put so much effort in a Codeforces contest since I quit being a round coordinator in December 2016 (wow, that was so long ago)! We conduct this round to have some fun and we also hope to find some great candidates to join Nebius team. Solving 5+ problems in our round will be a good result and will count as one of the coding interviews. Apart from that top 25 contestants and 25 random contestants placed 26-200 will receive a branded Nebius t-shirt! <img style="float: right; margin: 0 1em 0.5em 1em; width: 400px;" src="/predownloaded/40/37/403770e78d9c8962d0bc0c20a9e1c45d0e3c5df9.png"> Some information about Nebius. I have join...

Full text and comments »

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

63.
By peltorator, 4 years ago, In English
Codeforces Month of Blog Posts (win $300) **TL;DR:** Write an interesting CodeForces blog post until February 15th and win $300. **UPD: Second place will receive $50.** **UPD2: Competition is over, The results are available [here](https://codeforces.me/blog/entry/113041).** I am a huge fan of CodeForces and specifically CodeForces blog posts! There are tens and hundreds of gems posted on this platform throughout the years. Thankfully, recently there was added the [catalog](https://codeforces.me/catalog) page where a lot of cool articles can be found. Personally, if I want to remember some classical algorithm, I would go to websites like [cp-algorithms](https://cp-algorithms.com/), but CodeForces is the place where new or rare stuff is born, where new points of view emerge. I think it is one of the most valuable functions of this website, and I would like to facilitate its growth. I know that many people have cool ideas in their minds that they came up with or maybe something that is known only in their community on ...
/rare algorithm/idea, a new interesting point of view on an already known algorithm, simplification of

Full text and comments »

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

64.
By PrinceOfPersia, 12 years ago, In English
Algorithm Gym :: Everything About Segment Trees In the last lecture of **Algorithm Gym** ([Data Structures](/blog/entry/15729)), I introduced you Segment trees. In this lecture, I want to tell you more about its usages and we will solve some serious problems together. [cut] Segment tree types : Classic Segment Tree -------------------- Classic, is the way I call it. This type of segment tree, is the most simple and common type. In this kind of segment trees, for each node, we should keep some simple elements, like integers or boolians or etc. This kind of problems don't have update queries on intervals. Example 1 (Online): Problem [problem:380C] : For each node (for example $x$), we keep three integers : 1.`t[x]` = Answer for it's interval. 2. `o[x]` = The number of $($s after deleting the brackets who belong to the correct bracket sequence in this interval whit length `t[x]`. 3. `c[x]` = The number of $)$s after deleting the brackets who belong to the correct bracket sequence in this interval whi...
Algorithm Gym :: Everything About Segment Trees, In the last lecture of **Algorithm Gym** ([Data Structures](/blog/entry/15729)), I introduced you

Full text and comments »

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

65.
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 ...
following algorithm is trivially correct: let's do a binary search from the bottom of this caterpillar to, But unfortunately, the tree doesn't have to be a caterpillar. So, where can this algorithm fail? It

Full text and comments »

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

66.
By Errichto, 8 years ago, In English
Lecture #3 — Exchange arguments (sorting with dp) Hi. I'm back from USA! I will do a new lecture tomorrow (Thursday) at 2pm CEST on my Youtube channel: [https://www.youtube.com/watch?v=7hFWrKa6yRM](https://www.youtube.com/watch?v=7hFWrKa6yRM). Watch me live (and ask questions), or just watch the video later. This will be part 1, and I will do part 2 in a few days (maybe Tuesday). **UPDATE** &mdash; part 2 is coming on Thursday, same time. Link: [https://www.youtube.com/watch?v=gXxu-Cr4b4c](https://www.youtube.com/watch?v=gXxu-Cr4b4c). There are no prerequisites this time. I recommend reading the materials below in advance, and trying to solve problems 1 and 5. If you are strong, just read problems and see if you can't solve something (maybe problem 8?). ### Technique "Exchange Arguments" If we're given $n$ items and we should choose some of them and choose their order, we should sort them with some strange/tricky comparator, and then do $O(N^2)$ dynamic programming. The dp should be $dp[pref][used]$ &mdash; best po...

Full text and comments »

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

67.
By ko_osaga, history, 4 years ago, In English
SMAWK algorithm as an alternative for D&C optimization Yesterday I participated in a local contest involving a problem about Monge arrays. I could've wrote some d&c optimization, but I got bored of typing it so I copypasted [user:maroonrk,2023-01-01]'s SMAWK implementation to solve it. Today, I somehow got curious about the actual algorithm, so here it goes. ## 1. Definition I assume that the reader is aware of the concept of D&C Optimization and Monge arrays. The goal of SMAWK is to compute the row optima (ex. row minima or maxima...) in a $n \times m$ **totally monotone** matrix. By *totally monotone*, it means the following: **Def: Monotone.** The matrix is monotone if the position of row optima is non-decreasing. **Def: Totally Monotone (TM).** The matrix is totally monotone if every $2 \times 2$ submatrix is monotone. Totally monotone matrices are monotone (proof easy but nontrivial), but not vice versa. The latter is a stronger condition. Note that Divide and Conquer Optimization works on a monotone matrix, therefore ...
SMAWK algorithm as an alternative for D&C optimization, ## 2. Algorithm Basically, SMAWK is a combination of two independent algorithms: *Reduce* and

Full text and comments »

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

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

Full text and comments »

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

69.
By Errichto, 8 years ago, In English
Sums and Expected Value — part 1 part 2: https://codeforces.me/blog/entry/62792 Watch my lecture-stream tomorrow (Thursday) at [14:00 CEST](https://www.timeanddate.com/worldclock/fixedtime.html?msg=EV+lecture+1&iso=20181025T14&p1=262) &mdash; <s>[https://www.youtube.com/watch?v=qdlPY37MBPo](https://www.youtube.com/watch?v=qdlPY37MBPo)</s> [https://www.youtube.com/watch?v=U_h3IjreRek](https://www.youtube.com/watch?v=U_h3IjreRek). I will go through theory and problems from this blog. The only prerequisite is knowing what is probability. The next (harder) part on Monday. The video will be available later, with timestamps for each problem &mdash; so you don't have to watch everything. ### Definition of EV Let's say we bought a lottery ticket for 2$. We will win 10$ with probability 10%, and 20$ with p-bility 2%. On average, it gives us $0.1 \cdot 10 + 0.02 \cdot 20 = 1.4$, so we are worse off after buying the ticket. The computed average is called the expected value. The expected value (EV, expecta...

Full text and comments »

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

70.
By Tony2_CF, history, 11 months ago, In English
The Time Complexity Lower Bound for Segment Tree Beats is log^2 Original Post: https://jiry-2.blog.uoj.ac/blog/1404 The following content is translated by Gemini 2.5 Pro. ## Part 1: Introduction to the Hacking Method ### How to Map the Hack Sequence to a Segment Tree First, we are given a Hack sequence of length $len$. After $O(1)$ range addition operations and $\Theta(\log len)$ global $\text{chkmax}$ operations, this sequence becomes a cyclic shift (rotation) of the original sequence. Since a cyclic shift does not affect our range addition and global $\text{chkmax}$ operations (we can simply shift the indices for the range addition accordingly), we can consider the sequence as unchanged. If we have such a sequence, let $len=n^{\frac{1}{3}}$, and place such a sequence at intervals of $n^{\frac{2}{3}}$. Each sequence corresponds exactly to a segment tree interval. A subtree of size $n^{\frac{2}{3}}$ contains exactly one such segment tree interval. For the Hack sequence, the range addition operations are performed one by one on eac...
The Segment tree beats algorithm was proposed by jry in 2016. I can't seem to find the ppt I saw

Full text and comments »

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

71.
By ko_osaga, history, 7 years ago, In English
Story about edge coloring of graph You are given a graph $G$, and for each vertex $v$ you have to assign a positive integer **color** such that every adjacent pair of vertices (vertices directly connected by edge) have different color assigned. You have to minimize the maximum color assigned: In other words, you have to minimize the number of distinct assigned colors. But that's [graph coloring](https://en.wikipedia.org/wiki/Graph_coloring) (vertex coloring). It's hard. Ok, one more time: You are given a graph $G$, and for each **edge** $e$ you have to assign a positive integer **color** such that every adjacent pair of edges (edges sharing same endpoints) have different color assigned. You have to minimize the maximum color assigned: In other words, you have to minimize the number of distinct assigned colors. This is the edge coloring of graph, and I will talk about this now. *Note that this can be interpreted as "graph coloring (vertex coloring) of line graphs". In that sense, you can consider in a similar...
The $O(mn)$ algorithm is very simple to implement and it usually don't find long Kempe chains. I

Full text and comments »

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

72.
By -is-this-fft-, history, 4 years ago, In English
[Tutorial] FFT If I was a YouTuber, this would be the place where I fill the entire screen with screenshots of people asking me to make this. Anyway, not so long ago I gave a lecture on FFT and now [user:peltorator,2023-01-11] is giving away [free money](https://codeforces.me/blog/entry/110840), so let's bring this meme to completion. In this blog, I am going to cover the basic theory and (competitive programming related) applications of FFT. There is a long list of generalizations and weird applications and implementation details that make it faster. Maybe at some point I'll write about them. For now, let's stick to the basics. **The problem.** Given two arrays $a$ and $b$, both of length $n$. You want to quickly and efficiently calculate another array $c$ (of length $2n - 1$), defined by the following formula. $$c_k = \displaystyle \sum_{i + j = k} a_i \cdot b_j.$$ Solve it in $O(n \log n)$. First of all, why should you care? Because this kind of expression comes up in combinatorics a...
#### The core of the algorithm

Full text and comments »

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

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

Full text and comments »

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

74.
By PurpleCrayon, 5 years ago, In English
[Tutorial] Simulated Annealing in Competitive Programming Hi Codeforces! I've recently noticed a lack of simulated annealing tutorials, so I decided to make one. It all started when I was trying to "cheese" [problem:1556H] after the contest. In general, simulated annealing is a pretty niche topic, but it can sometimes lend you unintended solutions for very hard problems. It's also very useful in contests like Google Hashcode, where you can add simulated annealing to an already good solution to make it a lot better. Simulated annealing's name and terms are derived from physical annealing, the process of letting metals or glass cool down and harden while removing internal stresses. An Overview ------------------ Simulated Annealing is an approximation algorithm. It's generally useful in problems with low constraints (i.e. $n \leq 50$ or $n \leq 100$) where you need to find the minimum/maximum of something over all possible states (and there are usually way too many of them to check). In general, it's good at finding the global maximum...
The issue with this algorithm is that it often gets stuck in a local minimum, instead of a global

Full text and comments »

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

75.
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...
Tutorial: A simple O(n log n) polynomial multiplication algorithm, ### (Advanced) Speeding up the algorithm This section will be about tricks that can be used to, ### (Advanced) [user:-is-this-fft-,2023-07-07]? This algorithm is actually FFT in disguise. But it, Algorithm:

Full text and comments »

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

76.
By djm03178, 2 years ago, In English
Common mistakes on Dijkstra algorithm and how to hack them As many people may have noticed, I've done quite a number of TL hacks on [problem:2000G]. The hacked submissions even include many masters' and grandmasters' solutions, and most of them don't even have suspicious running time on the original tests. I predict many more solutions will fail on system testing because I've checked only some of C++20 and C++17 submissions and haven't tried running all the hack cases. So, how did they get time limit exceeded? They're actually caused by a few different mistakes, and we need different strategies to hack each of them. For convenience I'll assume that $\mathcal{O}(n)$ = the number of nodes = the number of edges, because whether the factor becomes $n$ or $m$ can vary depending on the implementation, and the number of edges is likely to be at least the number of nodes. Also for convenience (and as this problem is like that) I'll assume that the graph is bidirectional, but it works the same for directed graphs (only a bit harder to slowdown du...
Common mistakes on Dijkstra algorithm and how to hack them, /hacks/1068253 . It required two versions because some people started Dijkstra algorithm from node $1

Full text and comments »

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

77.
By ko_osaga, history, 4 years ago, In English
[Tutorial] On Range LIS Queries, Part 1 Hello, Codeforces! At some point of life you want to make a new data structure problem with short statement and genius solution. LIS (Longest Increasing Subsequence) is a classic problem with beautiful solution, so you come up with the following problem: * Given a sequence $A$ of length $N$ and Q queries $1 \le i \le j \le N$, compute the length of Longest Increasing Subsequence of $A[i], A[i + 1], \ldots, A[j]$. But on the other hand this looks impossible to solve, and you just give up the idea. I always thought that the above problem is unsolved (and might be impossible), but very recently I learned that such queries are **solvable** in only $O(N \log^2 N + Q \log N)$ time, not involving any sqrts! The [original paper](https://arxiv.org/abs/0707.3619) describes this technique as *semi-local string comparison*. The paper is incredibly long and uses tons of scary math terminology, but I think I found a relatively easier way to describe this technique, which I will show in t...
## Chapter 1. The All-Pair LCS Algorithm

Full text and comments »

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