Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

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

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

Results

1.
By Rhodoks, history, 4 years ago, In English
Codeforces Round #810 Editorial Sorry for the late editorial. May this editorial help you. If you have questions, feel free to ask. [problem:1711A] <spoiler summary="hint1."> The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). </spoiler> <spoiler summary="solution"> Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\cdots,n-1]$. </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; void work() { int n; cin>>n; cout<<n<<' '; for (int i=1;i<n;i++) cout<<i<<' '; cout<<endl; } int main() { int casenum=1; cin>>casenum; for (int testcase=1;testcase<=casenum;testcase++) work(); return 0; } ~~~~~ </spoiler> [problem:1711B] <spoiler summary="hint1."> See the party as a graph. </spoiler> <spoiler summary="hint2."> Divide the vertices into two categories according to their degrees' parity. </spoiler> <spoiler summary="solution"> Let's consider ...
a pair of toroidal neighbors with different colors. For example, $col_{x,y}=a$ and $col_{x+1,y}=b(a

Full text and comments »

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

2.
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 ...
a(n), b(m); for (int i = 0; i < n; i++) { scanf("%lld", &(a[i

Full text and comments »

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

3.
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"; } } ...
precisely, ReLU segment tree can solve the following problem: > You are given two arrays $a$ and $b$ of, To handle updates, we can use a segment tree. Each node of the segment tree stores the minimum

Full text and comments »

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

4.
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...
folder called "yinchuan" and uploaded codes for problems B, G, and I: ![NaokiLH's commit records, /algorithm_trans/tree/cb2e076261540a960ae0068d7dbfa088171c49ac/blue_book/sh) at that time (including

Full text and comments »

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

5.
By rama_pang, history, 6 years ago, In English
[Tutorial] Li Chao Tree Extended Hello everyone! I discovered a new (?) trick on how to apply lazy propagation on the Li Chao Tree and decided to write a blog about it. I've personally never seen it before (outside of myself), nor have I seen a problem that needs the Extended Li Chao Tree specifically, but it *can* overkill some problems. Of course, I might not be looking hard enough... You can learn about the basics of Li Chao Tree from [cp-algorithms](https://cp-algorithms.com/geometry/convex_hull_trick.html) or [this simple blog](https://robert1003.github.io/2020/02/06/li-chao-segment-tree.html). The Extended Li Chao Tree can do the following problems (and other variations): ## Problem 1 There is an array $A$ of size $N$. There are $Q$ online operations: - Range Line Insertion. Given $l$, $r$, $a$, $b$, do $A_i = \max(A_i, a \cdot i + b)$, $\forall i \in [l, r]$ in $O(\log^2 N)$ - Range Line Addition. Given $l$, $r$, $a$, $b$, do $A_i += a \cdot i + b$, $\forall i \in [l, r]$ in $O(\log^2 N)$. - Po...
[Tutorial] Li Chao Tree Extended, $b$ with a classic segment tree which takes only $O(\log N)$ time per operation. ## Overkilling, = \min(A_i, a \cdot i + b)$, $\forall i \in [l, r]$. - Find $\min\limits_{\forall i \in [1, W]} A_i$., ~~~~~ template struct Line { data_t a, b;, $. That way, we can simply maximize $b$ with a classic segment tree which takes only $O(\log N)$ time per, **Solution.** Operation $1$ and $2$ are both supported by an Extended Li Chao Tree, so we can, - Range Line Insertion. Given $l$, $r$, $a$, $b$, do $A_i = \max(A_i, a \cdot i +b)$, $\forall i, - The Li Chao Tree can work with any functions, as long as that for all pairs of functions $f$ and, . We can do a range sum addition on the segment tree of $B$, then easily update $B_L$ and $B_{R + 1, Line() : a(0), b(-inf) {} Line(data_t a, data_t b) : a(a), b(b) {}, data_t get(data_t x) { return a * x + b; }, void add(Line x) { a += x.a; b += x.b; } };

Full text and comments »

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

6.
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...
6. Gaussian elimination 7. Kruskal’s minimum spanning tree algorithm 8. Kuhn’s bipartite matching, independence. If it connects two vertices in the same tree, then there is a loop, so we need to remove some, We can exchange yellow edge for one of blue edges to get one-edge-different spanningtree. Let’s

Full text and comments »

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

7.
By mnbvmar, 8 years ago, In English
Codeforces Round #556 Hi Codeforces! I'm so happy to invite you to [contest:1149] and [contest:1150]! The rounds will be held on [contest_time:1149]. The round will be rated for both divisions. (At least that's what I've been told!) The problems were written and prepared by me. Thanks to [user:300iq,2019-04-27] for the round coordination, and to [user:Radewoosh,2019-04-27] for his invaluable help with choosing the problemset and testing the problems! Also, I want to give a shout-out to [user:MikeMirzayanov,2019-04-27] for his amazing Codeforces and Polygon platforms! ![ ](http://students.mimuw.edu.pl/~ms360974/stuff/tab-bar2.png) _My browser's tab bar, right now._ You'll work on **5** problems, and you will have **2** hours to solve them. The scoring distribution will be revealed closer to the round. ~~~~~ def get_end_remark(): return random.choice([ "Wish everyone high ratings!", "Good luck!", "Have fun!", "Please, read all the problems!"]) ~~~...
Challenge](https://codeforces.me/contest/1150/problem/B) | 3:43 | [user:Nazarbek_Baltabaev,2019-04-29, -29] | | | | [Tiling Challenge](https://codeforces.me/contest/1150/problem/B) | 3:43

Full text and comments »

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

8.
By jiry_2, history, 9 years ago, In English
A simple introduction to "Segment tree beats" Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this comment](http://codeforces.me/blog/entry/54750?#comment-387957). Sorry for the long delay, as a sophomore in Peking University, I've just finished a tired semester and a painful final exam. And now I finally have enough time to do a simple introduction to this interesting algorithm. It may be a huge project for me since my English is not good. I think I will finish this blog in several steps and I will try to finish it as soon as possible :) In China, all of the 15 candidates for the Chinese National Team are asked to write a simple research report about algorithms in informatics Olympiad, and the score will be counted in the final selection. There are many interesting ideas and algorithms in these reports. And I find that some of them are quite new for competitors in CF although they are well known in China from the final standings of some recent contests. For example, In the last co...
A simple introduction to "Segment tree beats", each leaf and make $H_i=\max(H_i,f_{a,b}(C_i))$ ($C_i$ is the current value) after putting tag $f_{a,b, has the form $f_{a,b}(x)(h_{a,b}(x))$ and this tag can also be merged. After push down the tag $(f_, two auxiliary arrays $B,C$. Initially, $B$ is equal to $A$ and $C$ is all zero., And these tags can be merged: $f_{a,b}(f_{c,d}(x)) = \max(\max(x + c, d) + a, b ) = \max(x + a+c, Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this, In this problem, the lazy tag is a function $f_{a,b}(x) = \max(x + a,b)$. The first operation is

Full text and comments »

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

9.
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 ...
common parent in the tree, $A$ moves up at least two times and then $B$ moves once, then $A$ loses many, $ and $B$ have a common parent in the tree, $A$ moves up at least two times and then $B$ moves once

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

12.
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...
* id,l,mid), b = segment(x,y,2 * id + 1,mid,r); int T, temp, O, C; temp = min(a.y.x, when we want to st `b[p[po]] = 0` to update the segment tree: ~~~~~ void update(int p,int id, At first we'll set all array $b$ to $1$ and we will set all of them to $0$ one by one., So, build function would be like this ($s[x]$ is the sum of $b$ in the interval of node $x$) :, et An update function for when we want to st `b[p[po]] = 0` to update the segmenttree:, ~~~~~ po = 0 for j = 0 to q-1 while po < n and a[p[po]] <= k[w[j]] b[p[po]] = 0, po = po + 1 ~~~~~

Full text and comments »

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

13.
By Um_nik, 8 years ago, In English
How to read problem statements But [user:Um_nik,2018-10-26], we all know how to read, we have our whooping 2 month of experience! Oh, my sweet summer child, my experiments show that many people with kinda cool achievements like medals on ROI don't know how to read statements. But don't worry, I'll teach you. Well, probably you won't understand anything, because you didn't try to understand anything in your life, you expect all hard work to be done for you by someone else. Let's start! Basic rules ================== - The result of reading the statement is usually pure math model. If story helps to build correct understanding, you can keep it, but still try to discard as many unnecessary details as possible. - Imagine you want to tell the problem to someone else. What parts you want to tell? (According to my PM, this rule won't help you). - Shorter = better. - Simpler = better. - Limitations are part of problem statement. Especially small limitations, because for small data you can try all the possib...
after deleting some vertices of a tree? Well, they are all trees themself. What we know about trees, pair of vertices, it's called tree. 4 letters instead of 12 words, see? - Try even harder to spot, Given a tree, all vertices are initially white. Two players, Red and Blue, take turns coloring

Full text and comments »

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

14.
By TheScrasse, history, 5 years ago, In English
[Tutorial] Diameter of a tree and its applications Hello everyone,<br> finding the diameter is one of the most frequent ways to solve problems about trees. In this tutorial we will see how to find a diameter and some of its properties, and we will use them to solve some problems of increasing difficulty.<br> The first part of the tutorial is quite basic, so feel free to skip it and jump to the problems if you already know the concepts. Target: rating $[1400, 2300]$ on CF<br> Prerequisites: basic graph theory, greedy The diameter ------------------ Given an unweighted tree, let's define $\text{dist}(a, b) =$ the number of edges in the simple path $a \rightarrow b$. A diameter of the tree $a \rightarrow b$ is the longest path, i.e., the one that maximizes $\text{dist}(a, b)$ over all pairs of nodes. If there are multiple diameters, let's pick any of them. The same definition is valid for a weighted tree with nonnegative weights (with $\text{dist}(a, b) =$ the sum of the weights of the edges in the simple path $a \rightar...
[Tutorial] Diameter of a tree and its applications, ------------------ Given an unweighted tree, let's define $\text{dist}(a, b) =$ the number of edges in, The optimal path is either $a \rightarrow i$ or $i \rightarrow b$. You, \text{dist}(d, b)$), using that $b$ is the farthest node from $a$., another DFS from node $a$. Let $b$ be a node whose distance from node $a$ is maximized. $a \rightarrowb, component, the distance of each node from $a$, $b$, the prefix maximums $\text{pm}(i)$ of $\text{dist}(a, i, generality that $j_1$ is closer to $a$ than to $b$), $\text{dist}(i, j_1) = \text{dist}(i, r) + \text, is a path $u \rightarrow v$ ($i$ in the component of $u$; $a, u, v, b$ in this order). The paths $a, node $b = 7$ is the farthest from $a$., v$ ($a, u, v, b$ in this order). Then, the maximum distance between a node and the nearest shop is, #### Proof that $a \rightarrow b$ is a diameter Now we can finish the proof., #### Tree = edges of a diameter + forest Before proving the previous algorithm, let's analyze the, $, root of $i$, root of $j$, $b$ in this order). $a \rightarrow j$, $i \rightarrowb$, $a \rightarrow b, ). Notice that the required distance is also the maximum of $\text{dist}(a, u)$, $\text{dist}(v,b, , v)$ or $\text{dist}(u, b) \geq \text{dist}(u, v)$ (see "Farthest node for each node")., ., $\text{dist}(a, d) < \text{dist}(d, b)$) is at most the distance of the root of the component from the, A diameter of the tree $a \rightarrow b$ is the longest path, i.e., the one that maximizes $\text, Find a diameter $a \rightarrow b$ (from now, $a \rightarrow b$ will always be a diameter, unless, Let's assume without loss of generality that $\text{dist}(u, b) \geq \text{dist}(u, v)$. We get, The diameter ------------------ Given an unweighted tree, let's define $\text{dist}(a,b) =$ the, The same definition is valid for a weighted tree with nonnegative weights (with $\text{dist}(a,b, _Claim: $j = a$ or $j = b$ always works._, _Claim: the optimal path is one of the following: $a \rightarrow i$, $i \rightarrowb$._, tree (same with $b$, in another segment tree). You have to support range multiply by $-1$, range max, {cups}(1, i) = \text{cups}(1, a)$ (you can handle $\text{dist}(i, b)$ similarly). For each query, you

Full text and comments »

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

15.
By errorgorn, 19 months ago, In English
1/phi Halving in Interactive Tree Problems Thanks to [user:toxicpie9,2025-04-22] for proofreading and emotional support. Recently, I was thinking about JOISC 2025 Space Thief. And there is a part where you need to do divide and conquer on a tree, where you need to split the edges of the tree into two components where the edges are both connected. Basically, we consider an interactive problem on a tree where there is a hidden edge. We are allowed to ask queries of the form $(v,N_v)$ where $v$ is a vertex of the tree and $N_v$ is a set of neighbouring edges of $v$. Then the query returns to us whether the hidden edge is in the subtree of one of $N_v$ when we root the tree at $v$. We maintain a set of edges that the hidden edge can be in. In each query, we try to split the set of edges into two parts and ask a query to separate them. In the worst case, we replace the set of edges by the larger component. Let $R$ be the maximum ratio of the larger component. In [this blog](https://codeforces.me/blog/entry/120446)...
1/phi Halving in Interactive Tree Problems, \cup a \cup b \cup Y$, $X_2 \cup b \cup Y$ and $X_1 \cup a \cup b \cup X_2$., observations: 1. If there is a node $x$ of degree $2$ in the tree connected to vertices $a$ and $b, of $A \cup B_1$ has $3$ children of sizes $c,d,d$ where $c\le d$. Here $a=d$ and $b=c + d$., 1. If there is a node $x$ of degree $2$ in the tree connected to vertices $a$ and $b$, we can make, And because of our previous two observations, we know that $C(X_1 \cup a \cup b \cup Y),C(X_2 \cup, Now suppose the current node has $3$ children $A,B_1,B_2$ of sizes $a,b,b$ where $a\leb$., So if you reduce the search space into size $a + b$, you get $\tilde R = \frac{1+\varphi}{1+2, So we can set up the equations $\frac{a}{b} = \frac{c}{d}$, $a=d$ and $b=c+d$ to obtain $\frac{d}{c, So we should focus on the first two cases where the search size is $a+b$. To construct the worst, Suppose the current node has $3$ children of sizes $a\le b\le c$. Then after two moves, we can, The case work is if $v$ is chosen to be not $b$, we will take the subtree that contains $b$. If $v

Full text and comments »

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

16.
By zscoder, history, 7 years ago, In English
[Tutorial] Generating Functions in Competitive Programming (Part 2) Welcome to Part 2 of my tutorial on generating functions. The [first part](https://codeforces.me/blog/entry/77468) focused on introducing generating functions to those without any background in generating functions. In this post, I will demonstrate a few applications of generating functions in CP problems. Let us start with some relatively straightforward examples. Note: Unless stated otherwise, all computations are done modulo a convenient prime (usually $998244353$). Also, $[n]$ denotes the set $\\{1,2,...,n\\}$. ### Blatant Applications in Counting Problems **Problem.** [AGC 005 Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices. For a subset $S$ of vertices, let $f(S)$ denote the minimum number of vertices in a subtree of $T$ which contains all vertices in $S$. For all $1 \le k \le n$, find the sum of $f(S)$ over all subsets $S$ with $|S| = k$. Constraints: $n \le 2 \cdot 10^{5}$. <spoiler summary="Solution"> First, ...
Problem F](https://atcoder.jp/contests/agc005/tasks/agc005_f) You have a tree $T$ with $n$ vertices, The idea is to relate $b(n)$ with $c(n)$. Suppose we have a labelled connected graph on $n

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

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

Full text and comments »

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

21.
By Tlatoani, 5 years ago, In English
Editorial for Technocup 2022 — Elimination Round 1 and Codeforces Round #749 (Div. 1+Div. 2) We hope all of you enjoyed the round! This round has been a long time in the making -- the oldest problem in it is H, which was actually originally proposed for the rounds that eventually became [contest:1372] and [contest:1392]. The tutorial for E and implementations for all problems are now available. <spoiler summary="A - Windblume Ode"> Problem author: [user:hu_tao,2021-10-17] Preparation: [user:hu_tao,2021-10-17] [Implementation in Java](https://codeforces.me/contest/1586/submission/132266058) by [user:hu_tao,2021-10-17] [tutorial:1586A] </spoiler> <spoiler summary="B - Omkar and Heavenly Tree"> Problem author: [user:golions,2021-10-17] Preparation: [user:golions,2021-10-17] [Implementation in Java](https://codeforces.me/contest/1586/submission/132266285) by [user:golions,2021-10-17] [tutorial:1586B] </spoiler> <spoiler summary="C - Omkar and Determination"> Problem author: [user:Tlatoani,2021-10-17] Preparation: [user:Tlatoani,2021-10-17] and...
Problem author: [user:golions,2021-10-17]

Full text and comments »

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

22.
By Geothermal, history, 7 months ago, In English
My Solutions to Spectral::Cup 2026 Round 1 (CF Round 1094) Since the editorial for today's Div. 1 hasn't been published yet, I thought I'd share solution sketches. Some of these won't include all of the specific details, but hopefully they should communicate the main ideas. (I didn't compete officially, but I got AC on all of the problems using the below approaches, so I'm fairly confident in correctness.) Feel free to leave questions below and I'll respond if I have time. ## A &mdash; A Wonderful Contest If any problem has $100$ subtasks, the answer is yes: we can achieve an arbitrary score by solving some of the other problems fully and by solving the right number of subtasks of the $100$-subtask problem. Otherwise, there is no way to achieve a score of 1, so the answer is no. ## B &mdash; Artistic Balance Tree Note that each of the reversal operations swaps odd positions with odd positions and even positions with even positions, as $u-i$ and $u+i$ differ by $2i$ and thus have the same parity. Thus, when we are to mark an od...
## B — Artistic Balance Tree

Full text and comments »

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

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

Full text and comments »

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

24.
By neal, 6 years ago, In English
Unofficial Editorial for Educational Round 95 (Div. 2) Here are my approaches to the problems today: #### [problem:1418A] Since the second trade is the only way to get coal, we clearly need to perform the second trade $k$ times. So how many times do we need to do the first trade? We can see that in order to end up with enough sticks and coal by the end, we need to obtain $ky + k$ sticks ($ky$ to convert to coal and $k$ to save as sticks). Since the first trade really just gives us $x - 1$ new sticks each time, we'll need to make $\displaystyle \left \lceil \frac{ky + k - 1}{x - 1} \right \rceil$ first trades ([reference to floor and ceiling functions](https://en.wikipedia.org/wiki/Floor_and_ceiling_functions) for anyone unfamiliar). For implementation details, note that for positive integers $a$ and $b$, $\displaystyle \left \lceil \frac{a}{b} \right \rceil = \left \lfloor \frac{a + b - 1}{b} \right \rfloor$. Code: [submission:92851684] #### [problem:1418B] We can think about the problem as follows: we want to order the $a_i$ to...
sweep on $a$ and $b$ instead to just handle these queries with a 1D seg tree instead (query minimum in, Instead by using a segment tree, you can end up with a clean $O((n + m) \log^2 m)$ solution. The

Full text and comments »

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

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

Full text and comments »

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

26.
By errorgorn, 5 years ago, In English
On Div2ABs 2 years ago, [user:antontrygubO_o,2022-04-27] wrote [a blog](https://codeforces.me/blog/entry/75163) about div2ABs where he expressed his opinions that d2ABs should not be about "here is a statement, please implement what is written there". Thanks to him, the quality of d2ABs (and problem quality in general) have certainly improved. However, I still believe that there still quite large differences between how coordinators/problemsetters view d2ABs and how the intended participants view them. From the survey made by [user:kpw29,2022-04-27], we can see that most people agree that most people agree that we should **primarily** consider the target audience when proposing a task. I too think if a task is boring to div 1 contestants, we should not think of that as a reason to immediately disqualify a problem from being a d2A. ![ ](https://codeforces.me/predownloaded/70/b5/70b515da85a4dc3b362cf4eb0963dbd1fb642819.png) I think when people judge the interesting-ness of d2As, they try...
[user:Monogon,2022-04-27]: I think graph/tree problems shouldn't appear until C. Even though this, [user:sus,2022-04-27]: Pretty hard but it is a B problem, so I think its ok. Pretty interesting, I

Full text and comments »

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

27.
By errorgorn, 4 years ago, In English
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
$B$ is a fake vertex. If so, we separately process the actual lca in the originaltree., actually perform queries in our HLD structure. We know from HLD+segment tree our query loop is for, be vertex $b$ in our constructed tree (it can be vertex $a$ but we want to assume the worst case) so, by a path-parent edge in the new tree. If chains $a$ and $b$ were connected, with $a$ being the, here by imagining that there are fake edges from the root of each chain of the splaytree to its the, original tree would be connected by a path-parent edge in the new tree. If chains $a$ and $b$ were

Full text and comments »

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

28.
By bicsi, history, 7 years ago, In English
Link Cut Tree implementation Hello! Recently I have been trying to learn link cut trees (and splay trees, for that matter). I have tried to polish an implementation that is short (for our ICPC notebooks), and also easy to use and extend. I might be extending this blog post towards a tutorial on how link cut trees are used and, more so, how this template can be used. The implementation is here: <spoiler summary="Implementation"> ``` struct SplayTree { struct Node { int ch[2] = {0, 0}, p = 0; long long self = 0, path = 0; // Path aggregates long long sub = 0, vir = 0; // Subtree aggregates bool flip = 0; // Lazy tags }; vector<Node> T; SplayTree(int n) : T(n + 1) {} void push(int x) { if (!x || !T[x].flip) return; int l = T[x].ch[0], r = T[x].ch[1]; T[l].flip ^= 1, T[r].flip ^= 1; swap(T[x].ch[0], T[x].ch[1]); T[x].flip = 0; } void pull(int x) { int l = T[x].ch[0], r = T[x].ch[1]; push...
Link Cut Tree implementation, root of a splay tree node which contains the whole path from `a` to `b`. Also, the function `access, you call `lc.Path(a, b)`, the implementation will return the root of a splay tree node which contains

Full text and comments »

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

29.
By Endagorion, 12 years ago, In English
Codeforces Round #300 Editorial (+challenges) As usual, a challenge comes with every problem. I tried not to repeat the mistakes of my previous editorials and made sure that all challenges have a solution =) (except for the _italics_ parts that are open questions, at least for me). Go ahead and discuss them in the comments! General questions about problems and clarification requests are welcomed too. **UPD**: I added codes of my solutions for all the problems. I didn't try to make them readable, but I believe most part of them should be clear. Feel free to ask questions. [problem:538A] Let me first clarify the statement (I really wish I didn't have to do that but it seems many participants had trouble with the correct understanding). You had to erase exactly one substring from the given string so that the rest part would form the word `CODEFORCES`. The (somewhat vague) wording `some substring` in the English translation may be the case many people thought that many substrings can be erased; still, it is beyond my understa...
tree with $n$ leaves such that $dp_{max}(root) = a$ and $dp_{min}(root) = b$. For which numbers $n

Full text and comments »

Tutorial of Codeforces Round 300
  • Vote: I like it
  • +312
  • Vote: I do not like it

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

Full text and comments »

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

31.
By nikgaevoy, 4 years ago, In English
Push-Free Segment Tree ![ ](/predownloaded/95/ad/95ad3397de22cc8b20c52a1eccc87ac0c34e76cb.jpg) Figure 1: Tiffany A pdf version of this text could be found [here](https://acm.math.spbu.ru/trains/push_free_segment_tree.pdf). Prerequisites ------------- First of all, who this article is aimed at. This article assumes you already know what a segment tree is. Have you never heard about the segment tree, the Fenwick tree (aka binary indexed tree, BIT) or the RMQ problem, you should better read about it [somewhere else](https://codeforces.me/catalog) and then come back here right after to learn a bunch of cool stuff. The model target audience is the people able to solve [this problem](https://judge.yosupo.jp/problem/range_affine_range_sum) at least in theory. But even if you can't, this article could still be helpful. However, I think this article contains some ideas that were never published before, thus making it interesting even for people who are closely familiar with different variants o...
Push-Free Segment Tree, \cdot (b \cdot c) = (a \cdot b) \cdot c$. 3. Distributivity of multiplication over addition: $(x, allows you to answer the following types of queries on two "arrays" $A$ and $B $:, linear functions representing how values in the array $B$ change over time with the last segment, rule $a \cdot b = b$, except for $1$, where $1 \cdot a = a \cdot 1 = a$. Again, the same trick with, segment tree for this trick to work? Commutative property of multiplication only: $a \cdotb = b, , y, z, \ldots$) and multipliers ($a, b, c, \ldots$), but for the sake of simplicity, I will keep, 1. Add on a range of the array $A$. 2. Perform element-wise addition $B \mathrel{{+}{=}} A, But what do we actually need from the segment tree for this trick to work? Commutative property of

Full text and comments »

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

32.
By PurpleCrayon, 5 years ago, In English
[Tutorial] Euler Tour Trees (maintaining dynamic trees through their euler tour) Good morning Codeforces! Today's post regards a well-known, but surprisingly hard to learn topic, Euler Tour Trees. Prerequisites: ------------------ - Basic tree knowledge, e.g. general vocabulary - Balanced Binary Search Tree Knowledge (e.g Treaps/Splay trees). In my opinion, learning treaps is the easiest, and [user:SecondThread,2022-02-03] has a great video/problemset on treaps, so go check it out [here](https://codeforces.me/blog/entry/84017)! The BBST must store parent pointers, so make sure your implementation supports it. #### Disclaimer This idea will definitely not show up in easy problems, and is pretty uncommon. Nevertheless, it's a cool concept and it can be used to “cheese” somewhat difficult problems, and I haven't found any resources that describe it well. Brief Description of Operations ------------------ A Euler Tour Tree is a representation of a dynamic forest of trees. This means that, as long as the graph never contains any cycles, you can su...
“reverse” of $\text{reroot}(b)$, such that $(b, b)$ is the last edge in $b$'s Euler Tour. 3. Merge, , Euler Tour Trees. Prerequisites: ------------------ - Basic tree knowledge, e.g. general, 1. Cyclically shift the edge $(a, b)$ to the front of the tour. 2. Remove the edge $(a,b)$ (now, Important note: For all future queries, to locate an edge $(a, b)$ in the BBST's, you can store a, There are 3 steps when removing an edge between $(a, b)$:, There are three steps when adding an edge between $(a, b)$:, This query checks if two nodes $a$ and $b$ are in the same component. This can be done simply by

Full text and comments »

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

33.
By sevlll777, history, 5 years ago, translation, In English
Codeforces Round #770 (Div. 2) editorial Thank you for participating, we hope you enjoyed the problems! We kindly ask you to rate each of the round's problems in the corresponding spoiler in order to improve the quality of future contests. You can also check video editorials of problems B and C on [user:ak2006,2022-02-06] [Youtube channel](https://www.youtube.com/channel/UCnZ5rC2_JY0EuYMGMiAbISg). All problems were prepared by [user:Alexdat2000,2022-02-02] with the help of coauthors. [Why didn't AI participate](https://codeforces.me/blog/entry/99579?#comment-884764) [problem:1634A]<br> Idea: [user:sevlll777,2022-02-02] <div class="spoiler"> <b class="spoiler-title">Hint 1</b> <div class="spoiler-content" style="display: none;"> What property will the string have after the first operation (regardless of the type of operation)? </div></div> <div class="spoiler"> <b class="spoiler-title">Hint 2</b> <div class="spoiler-content" style="display: none;"> What happens if you apply an operation to a palindrome? ...
<b class="spoiler-title">Hint 2b> , like segment tree? <b class="spoiler-title">Hint 3b>

Full text and comments »

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

34.
By tibinyte2006, 4 years ago, In English
[Tutorial] Cartesian tree and some related problems The Cartesian Tree is a useful concept for solving some problems which revolve mainly about thinking of the range of maximality of elements. It also provides a sort of "persistance" to the algorithm of monotonic stack, if you will. In this blog, we will learn what a Cartesian Tree is, how to construct one and solve some related problems to strengthen our understanding. Let's begin! <hr> #### What is a Cartesian Tree? Let's consider an array $a$ where all values are distinct. The Cartesian Tree for the array $a$ is a binary labeled tree build recursively from the function $get(l,r)$ which constructs our desired tree from the subarray $l...r$. Now let's define $get(l,r)$ - First root the tree at index $i$ such that $a_i = min(a_l,a_{l+1},...,a_r)$. Note that because all values are distinct, $i$ will always be unique. - The aforementioned index will become the root of the Cartesian Tree. It's left and right subtrees will be recursively generated by $get(l,i-1)$ and $get(...
[Tutorial] Cartesian tree and some related problems, can easily note that this is equivalent to counting arrays $b$ for which their CartesianTree has the, And here goes the solution, let $dp_{i,j}$ hold the number of arrays $b$ that yield the same, This problem asks us, given an array $a$, to count the number of arrays $b$ such that for any

Full text and comments »

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

35.
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...
applied in many situations and a segment tree solution might not always be possible. A first

Full text and comments »

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

36.
By Syloviaely, history, 8 years ago, In English
A simple introduction to "Segment tree beats" **This blog is just a back up of [http://codeforces.me/blog/entry/57319](http://codeforces.me/blog/entry/57319) to prevent this tutorial from discarding after [user:jiry_2,2018-10-17] is banned.** Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this comment](http://codeforces.me/blog/entry/54750?#comment-387957). Sorry for the long delay, as a sophomore in Peking University, I've just finished a tired semester and a painful final exam. And now I finally have enough time to do a simple introduction to this interesting algorithm. It may be a huge project for me since my English is not good. I think I will finish this blog in several steps and I will try to finish it as soon as possible :) In China, all of the 15 candidates for the Chinese National Team are asked to write a simple research report about algorithms in informatics Olympiad, and the score will be counted in the final selection. There are many interesting ideas and algorit...
A simple introduction to "Segment tree beats", each leaf and make $H_i=\max(H_i,f_{a,b}(C_i))$ ($C_i$ is the current value) after putting tag $f_{a,b, has the form $f_{a,b}(x)(h_{a,b}(x))$ and this tag can also be merged. After push down the tag $(f_, two auxiliary arrays $B,C$. Initially, $B$ is equal to $A$ and $C$ is all zero., .** Hi, I’d like to introduce a simple trick about segment tree in this blog as I promised in [this, And these tags can be merged: $f_{a,b}(f_{c,d}(x)) = \max(\max(x + c, d) + a, b ) = \max(x + a+c, In this problem, the lazy tag is a function $f_{a,b}(x) = \max(x + a,b)$. The first operation is

Full text and comments »

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

37.
By darkshadows, history, 11 years ago, In English
DP on Trees Tutorial A certain question on Quora and some junior asking about DP on Trees is what inspired this post. Its been a long time since I wrote any tutorial, so, its a welcome break from monotonicity of events. Pre-requisites: - Will to read this post thoroughly. :) - Also, you should know basic dynamic programming, the optimal substructure property and memoisation. - Trees(basic DFS, subtree definition, children etc.) Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follow the optimal substructure. We all know of various problems using DP like subset sum, knapsack, coin change etc. We can also use DP on trees to solve some specific problems. We define functions for nodes of the trees, which we calculate recursively based on children of a nodes. One of the states in our DP usually is a node $i$, denoting that we are solving for the subtree of node $i$. As we do examples, things will get clear for you. ...
. ##Problem 1 ============== The first problem we solve is as follows: Given a tree $T$ of $N, Problems for practice: [1](http://codeforces.me/contest/461/problem/B) [2](https

Full text and comments »

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

38.
By Al.Cash, 12 years ago, In English
Efficient and easy segment trees This is my first attempt at writing something useful, so your suggestions are welcome. Most participants of programming contests are familiar with segment trees to some degree, especially having read this articles http://codeforces.me/blog/entry/15890, http://e-maxx.ru/algo/segment_tree (Russian only). If you're not &mdash; don't go there yet. I advise to read them after this article for the sake of examples, and to compare implementations and choose the one you like more (will be kinda obvious). Segment tree with single element modifications ================== Let's start with a brief explanation of segment trees. They are used when we have an array, perform some changes and queries on continuous segments. In the first example we'll consider 2 operations: 1. modify one element in the array; 2. find the sum of elements on some segment. [cut] . ### Perfect binary tree I like to visualize a segment tree in the following way: [image link](http://i.imgur.com/GGBmcEP....
obvious). Segment tree with single element modifications ================== Let's start with a, , which means the order of operands doesn't matter, we have $a + b = b + a$. The same applies to $min$ and

Full text and comments »

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

39.
By maomao90, history, 5 years ago, In English
Tutorial on SIMD vectorisation to speed up brute force I decided to write a blog on this as I was doing a problem on our local judge and I decided to try to speed up my brute force code. However, it was quite difficult to find resources on SIMD vectorisation, so I decided to try to compile some of the resources I found to hopefully allow more people to learn <s>to scam brute force solutions</s> Thanks to ~iloveioi,2022-01-02 and ~jamessngg,2022-01-02 for proofreading. Introduction ================== SIMD stands for single instruction, multiple data. SIMD allows us to give vector instructions which will allow the code to run faster. Vector instructions are instructions that handle short (length 2-16) vectors of integers / floats / characters in a parallel way by making use of the extra bits of space to do operations simultaneously. The most common form of vectorisation is making use of pragmas such as ~~~~~ #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") ~~~~~ This form of vecto...
Let us observe how we can get the prefix sums of 4 integers $[a, b, c, d]$ quickly. If we follow a

Full text and comments »

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

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

Full text and comments »

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

41.
By maomao90, history, 3 years ago, In English
Optimal 2/3 halving in interactive tree problems It is not uncommon to have interactive tree problems where you are allowed to query some connected component of the tree and use the return value to determine whether the answer is in the connected component or outside the connected component ([Link to example problem](https://oj.uz/problem/view/info1cup17_eastereggs)). The general approach for these kinds of problems is to always choose a connected component of size $\frac{n}{2}$. However, there are also problems where the allowed queries are more restricted, preventing $\frac{n}{2}$ halving from being possible. This blog covers one of those types of problems. Definitions ================== - Subtree: $S(r, u)$ contains the set of vertices in the subtree of vertex $u$ if the tree was rooted at vertex $r$. - Neighbour: $N(u)$ contains the set of vertices that are directly adjacent to vertex $u$. - Extended subtree: $ES(r, V) = \bigcup_{v\in V} S(r, v)\text{ if } v\in N(r)$. In other words, an extended subtree is a combination ...
Optimal 2/3 halving in interactive tree problems, If we query all the vertices, we will be able to determine the distance between $a$ and $b$. Let, You are given a tree consisting of $n$ nodes and there are two distinct nodes $a$ and $b$ that you, tree consisting of $n$ nodes and there are two distinct nodes $a$ and $b$ that you have to

Full text and comments »

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

42.
By FHVirus, history, 5 years ago, In English
[Tutorial] A Bit of Math, Historic Sum, and Range Add Range Sum Binary Indexed Tree (Fenwick Tree) Hello CodeForces! Since my contribution is negative currently (-4) due to a stupid comment I made, I would like to write a little tutorial to earn some contribution stonks. Anyways, here's the outline of this tutorial: 1. We're going to solve a simple problem and a not-so-simple problem, then 2. use the formula derived from the problems to solve "Historic Sum" problem and maintain it on data structures like segment trees. 3. Use the same technique to solve the "Range Add Range Sum" problem with BIT. Yes, it's possible! Disclaimer: I did not come up with the method myself. Tutorials on historic sum problem can be found [here](https://codeforces.me/blog/entry/57319) from [user:jiry_2,2022-02-13]'s blog, and range add range query BIT can also be found on the Internet. I forgot the link to the original post, but the same technique can be found in several different Chinese blogs. This blog serves as an implementation of Feynman's learning technique, and I hope that it makes s...
[Tutorial] A Bit of Math, Historic Sum, and Range Add Range Sum Binary Indexed Tree (Fenwick Tree), a segment tree to maintain $B_i$ and $B'_i$ for every cell in $E$, and the modifications will be, segment tree to maintain $B_i$ and $B'_i$ for every cell in $E$, and the modifications will be two, // BB for B' vector pre(N + 1); BIT B(N), BB(N);, > Given an interger array $A$ of length $n$. > We define array $B$ where $B_i = \sum_{j = 1}^{i, What about modifications? We simply maintain $B$ and $B'$ on two Binary Indexed Trees (or one, it's, }{A_j}$ and another prefix sum $B'_i = \sum_{j = 1}^{i}{j \cdot A_j}$, and then $C_i$ will be $(i

Full text and comments »

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

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

Full text and comments »

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

44.
By E869120, 7 years ago, In English
My winning theory in IOI 2018 & 2019 — Why I won 2 golds in IOI Dear Codeforces community.<br /> According to [IOI 2019 Results](http://stats.ioinformatics.org/results/2019), I got the 25th place and got successful gold medals twice in a row.<br /> Although it was pretty close to the gold-medal border (only 6.14pts / 600 difference) and it was lower performance than IOI 2018, which I participated when I was orange in Codeforces, I had many chances to get more points in this IOI, even for top 10. Since there are not so many people who have got two gold medals in IOI (and there were many requests like "I want [user:E869120,2019-08-14] to talk about how to get gold in IOI" like [this comment](https://codeforces.me/blog/entry/66909?#comment-510127) and [this comment](https://codeforces.me/blog/entry/66909?#comment-513129)). I want to write something about IOI, which may be useful for people who will participate in IOI next year and also some years later.<br /> ![ ](https://i.ibb.co/TLmqRRX/E869120-IOI-01.png)<br /> <br /> ### A. First of all At...
/> * Know famous algorithms like segment tree, union find, set, map, sqrt decomposition, Convex

Full text and comments »

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

45.
By prabowo, history, 6 years ago, In English
[Tutorial] Reachability Tree / DSU-tree This is not to be confused with [DSU on Tree (Sack)](https://codeforces.me/blog/entry/44351). ### What can a Reachability Tree do? Suppose you are given a weighted (connected) undirected graph of $N$ vertices and $M$ edges. Let's define an ordering of the edges, for example, the edges are ordered in the ascending/descending order of their weights. The reachability tree can help you with: - Find the minimal/maximal weight of the edges when traversing from vertex $u$ to vertex $v$. - Find the set of vertices that are reachable from a given vertex using the first $x$ edges, for some arbitrary $x$. You can store some information in this set of reachable vertices, such as the maximum value or the sum of values of all the reachable vertices. ### Constructing a Reachability Tree The reachability tree is a rooted tree that consists of $N + M$ nodes. The tree will have $N$ leaves which represent the original vertices of the graph, and the rest of $M$ internal nodes represent th...
[Tutorial] Reachability Tree / DSU-tree, #### [APIO 2020 – Swapping Cities](https://tlx.toki.id/problems/apio-2020/B), This is not to be confused with [DSU on Tree (Sack)](https://codeforces.me/blog/entry/44351

Full text and comments »

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

46.
By dolphingarlic, history, 6 years ago, In English
[Tutorial] Path sum queries on a tree using a Fenwick tree ## Introduction I've come across several problems that require you to be able to efficiently find the sum of some values on a path from $A$ to $B$ in a tree. One can solve these problems using tree decomposition techniques like heavy-light decomposition or centroid decomposition, but that's a bit of an overkill and not very elegant in my opinion. In this blog post, I will describe a way to solve these types of problems using just a DFS, a Fenwick tree, and LCA (as well as a way to solve JOIOC 2013 Synchronization this way). **Note: Whenever I talk about edge $(u, v)$ in this post, I assume that $u$ is the parent of $v$.** ## Prerequisites - DFS - Preorder traversal (DFS order) - Fenwick tree - Binary lifting and LCA ## The idea Say you have the following problem: > Given a tree with $N$ nodes, each node $i$ has a value $a_i$ that is initially 0. Support the following 2 types of operations in $O(\log N)$ time: > > 1. Increase the value of $a_i$ by $X$ > 2....
[Tutorial] Path sum queries on a tree using a Fenwick tree, $u$ by $X$, we increase $b[tin_u]$ by $X$ and decrease $b[tout_u + 1]$ by $X$. Then when we want to, ^ v, b = y ^ v;, find the sum of some values on a path from $A$ to $B$ in a tree. One can solve these problems using, values on a path from $A$ to $B$ in a tree. One can solve these problems using tree decomposition, want to increase the range $[A, B]$ by $X$ in an array/Fenwick tree $BIT$, then we increase $BIT[A, $ and the time we exit it be $tout_i$. Additionally, let $b$ be an array/Fenwick tree of size $2N$., ) { int a, b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a, )$, update $b[tin_v]$ and $b[tout_v + 1]$ and make queries similarly., if (t == 1) { if (anc[b][0] == a) swap(a, b); update(tin[a], 1

Full text and comments »

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

47.
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...
: 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

48.
By cgy4ever, 12 years ago, In English
Codeforces Round #270 Editorial [problem:472A] One way to solve this is by bruteforce: there are O(n) different ways to decomose n as sum of two number. If we can check if a number is a prime in O(1) then the whole algorithm can run in O(n). You can use Sieve of Eratosthenes to do the pre-calculation. And another way is try to prove this theorem. The prove is simple: if n is odd number, then 9 and (n-9) is an answer (n-9 is an even number at least 4, so a composite number), and if n is even number, then 8 and (n-8) is an answer (n-8 is an even number at least 4, also must be a composite number). [problem:472B] This task can be solve by greedy: the k people with highest floor goes together, and next k people with highest floor goes together and so on. So the answer is 2 * ((f[n]-1) + (f[n-k]-1) + (f[n-2k]-1) + ...) . It is a bit tricky to prove the correctness of greedy, since people can get off the elevator and take it again. We can give a lower bound of the answer by flow analysis: between floor i ...
length edge, it must belong the the tree, ..., for the k-th minimal length edge(a,b), if there is, path from a to b in the tree, that means a and b can be connected by edges with less length, but a

Full text and comments »

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

49.
By rng_58, 14 years ago, In English
Codeforces Round #162 Tutorial #### [Div2 A Colorful Stones (Simplified Edition)](http://codeforces.me/problemset/problem/265/A) (Author: [user:rng_58,2013-01-21]) In this problem you just need to implement what is written in the statement. Make a variable that holds the position of Liss, and simulate the instructions one by one. #### [Div2 B Roadside Trees (Simplified Edition)](http://codeforces.me/problemset/problem/265/B) (Author: [user:snuke,2013-01-21]) The optimal path of Liss is as follows: First she starts from the root of tree 1. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_1, h_2)$. Jump to the tree 2. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_2, h_3)$, $\cdots$ and so on. #### [Div1 A / Div2 C Escape from Stones](http://codeforces.me/problemset/problem/264/A) (Author: [user:DEGwer,2013-01-21]) In this problem, there are many simple algorithms which works in $O(n)$. One of them (which I intended) is following: You should...
by one. #### [Div2 B Roadside Trees (Simplified Edition)](http://codeforces.me/problemset, #### [Div2 B Roadside Trees (Simplified Edition)](http://codeforces.me/problemset/problem/265/B

Full text and comments »

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

50.
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...
we have some function $rec(a, b, edges)$, where $a$ is the start of the time interval, $b$ is the

Full text and comments »

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

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

Full text and comments »

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

52.
By zltzlt, history, 2 years ago, In English
Codeforces Round 949 (Div. 2) Editorial Thank you for participating! Sorry for being much harder than usual Div. 2 :( But we still hope you find some of our problems interesting. <spoiler summary="Rating predictions (Inspired by sum's editorial)"> It seems like a joke now... | Person | A | B | C | D | E | F | | :-----------: | :-----------: | :-----------: | :-----------: | :-----------: | :-----------: | :-----------: | | [user: zltzlt, 2024-5-31] | 800 | 1400 | 1600 | 2000 | 2300 | 2800 | | [user: small_peter, 2024-5-31] | 800 | 1400 | 1700 | 1600 | | | | [user: WRuperD, 2024-5-31] | 800 | 1300 | 1600 | 2000 | | 2800 | | [user: yinhee, 2024-5-31] | 800 | 1000 | 1500 | 2100 | 2200 | 2700 | | [user: sinsop90, 2024-5-31] | 1000 | 1300 | 1500 | 2000 | 2200 | | | [user: Yujiahe,2024-05-28] | 800 | 1100 | 1600 | 1900 | | 2700 | | [user: CharlieV, 2024-5-31] | | | | 2400 | 2500 | 3000 | | [user: JWRuixi, 2024-5-31] | | | | 1800 | | | | [user: Edwin__VanCleef, 2024-5-31] | | | 1600 | 1800 | | | [u...
#define bl bool ll my_pow(ll a,ll b,ll mod){ ll res=1; if(!b) return 1; while(b ){ if(b, editorial)"> It seems like a joke now... | Person | A | B | C | D | E | F

Full text and comments »

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

53.
By darkkcyan, history, 6 years ago, In English
[Not tutorial] Sort before insert — A small extension to Merge sort tree Hello Codeforces! This is my first ever blog on Codeforces, and today I wanted to <s>gain contributions</s> share my small invention during my upsolving. I don't know if there existed a similar idea yet, but as far as I can tell, the editorial for the problem that I have solved does not use my idea. I think it would be nice to share with you guys and have your opinions on this idea. <h1>Prerequisite</h1> You should understand what is a segment and what is a merge-sort tree first. All the code in this blog is in <a href="https://codeforces.me/blog/entry/18051">efficient style</a>, therefore you should at least recognize part of it before reading the code. <h1>Idea explanation</h1> <h2>How do we build Merge-sort tree again?</h2> Merge sort tree is a Segment tree, each node of which contains a sorted set/vector of every element in its range. We build it in a bottom-up manner. To build the parent nodes, we merge 2 sets/vectors of the children the same as we do in the merge-...
[Not tutorial] Sort before insert — A small extension to Merge sort tree, line $x = y$ from it, and another line parallel to $Ox$ from it. Let's call these lines $a$ and $b, points $(x, y)$, we add it to the tree with the range $[0, y]$. For each querying points $(x, y)$, we, -sort algorithm in $O(\text{number of elements})$, hence the name Merge-sort tree. <b>But there, <b>But there is anotherb> way., <b>Some advantages of "sort before insert" over the classical wayb> * We can handle, > b; for (int i = 0; i < (int)a.size(); ++i) { b.emplace_back(a[i], i, But the main drawback is (<b>or is it???b>), this is heavily offline processing., Let `A` be the array we are building the merge-sort tree on, `it[i]` be the vector that contains, tree. Can we do the same with <b>range-like updateb>? Yes, yes we can!

Full text and comments »

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

54.
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$ ...
tree is a connected-acyclic graph.There are too many types of trees, like : rooted trees, weighted

Full text and comments »

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

55.
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...
thing you will learn at any competitive programming course, such as binary exponentiation, segmenttree

Full text and comments »

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

56.
By YoyOyoYOy000y000, history, 7 years ago, In English
Centroid Decomposition on a tree(Beginner) ## When Centroid Decomposition comes? 1. Suppose a problem says that how many paths have a length exactly k in a tree. 2. Or, how many paths have xor k. 3. Sum of all xor path in a tree. 4. update a node Black to white or white to black. now query the shortest path from a node to a white node. etc. **So, it is clear, when a paths problem comes then we can use Centroid Decomposition.** **For a single node query or from a specific node, DSU on Tree may do it.** ## Algorithm: ### 1. Find a centroid of current tree T. `What is Centroid? ` Simply Centroid is a node if we delete it. It makes some subtrees where every subtree size must be less than **sz/2** { sz is the size of the current tree T.} `How can we find it?` => Take a node random node of current tree T. Now if it's every subtree size less than sz/2. Then it is a centroid. => If not, go to the highest size of the subtree. **Note: In a tree only two Centroid possible F...
Centroid Decomposition on a tree(Beginner), ) { int a, b; cin >> a >> b; a--; b--; tree[a].push_back(b); tree[b].push_back(a

Full text and comments »

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

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

Full text and comments »

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

58.
By Alexdat2000, 4 years ago, translation, In English
Editorial of Codeforces Round #862 (Div. 2) Thank you for participating! We hope you enjoyed the problems! [problem:1805A]<br> Idea and preparation: [user:Alexdat2000,2023-04-02] <div class="spoiler"> <b class="spoiler-title">Hint 1</b> <div class="spoiler-content" style="display: none;"> Recall the basic properties of the $\oplus$ operation: $A \oplus 0 = A$, $A \oplus A = 0$, $A \oplus B = B \oplus A$. </div></div> <div class="spoiler"> <b class="spoiler-title">Hint 2</b> <div class="spoiler-content" style="display: none;"> Consider the cases of even and odd array lengths. </div></div> <div class="spoiler"> <b class="spoiler-title">Editorial</b> <div class="spoiler-content" style="display: none;"> [tutorial:1805A]</div></div> <spoiler summary="Solution"> ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) xor = 0 for x in a: xor ^= x if xor == 0: print(0) else: if n % 2 == 1: print(xor) else:...
<b class="spoiler-title">Hint 1b> , <b class="spoiler-title">Hint 2b> , <b class="spoiler-title">Hint 3b> , preparation: [user:Alexdat2000,2023-04-02] <b class="spoiler-title">Hint 1b

Full text and comments »

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

59.
By Dardy, history, 6 years ago, In English
[Tutorial] Catalan Numbers and Catalan Convolution Catalan Numbers is a well known sequence of integers that appear in combinatorics, there is a chance that you might have run into such counting problems and you might have even solved them with DP without realizing that they are a known sequence. Here is a problem to get us started. ### Binary Trees Count Find the count of different binary trees with $n$ nodes, we'll denote to that by $C_n$. This can be solved by observing the substructure of the problem: ![binary tree](/predownloaded/db/de/dbde9fa6024b3b59c37bbc1fa9e8a76c0f12fd21.png) From the root, the left subtree $a$ can be _any_ binary tree of size $x$, the right subtree $b$ can be _any_ binary tree of size $y$, such that $x+y=n-1$ (as we took one node as the root). With the base case at $C_0=1$ as the empty tree is a valid tree of size $0$. This directly gives us the answer by the following recurrence relation: (Segner's recurrence relation) $$ C_{n+1} = \displaystyle\sum_{i=0}^{n}{C_i C_{n-i}}, n \geq 0; C_0=1 $$ ...
From the root, the left subtree $a$ can be _any_ binary tree of size $x$, the right subtree $b$ can

Full text and comments »

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

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

Full text and comments »

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

61.
By tourist, 16 years ago, translation, In English
Codeforces Beta Round #17 Tutorial <a href="http://codeforces.me/blog/entry/447">Contest discussion</a><br><b><br>Problem A. Noldbach problem<br><br></b>To solve this problem you were to find prime numbers in range $[2..N]$. The constraints were pretty small, so you could do that in any way - using the Sieve of Eratosthenes or simply looping over all possible divisors of a number.<br>Take every pair of neighboring prime numbers and check if their sum increased by $1$ is a prime number too. Count the number of these pairs, compare it to $K$ and output the result.<br><br><b>Problem B. Hierarchy</b><br>[cut]<br>Note that if employee, except one, has exactly one supervisor, then our hierarchy will be tree-like for sure.<br>For each employee consider all applications in which he appears as a subordinate. If for more than one employee there are no such applications at all, it's obvious that $-1$ is the answer. In other case, for each employee find such an application with minimal cost and add these costs to get the answer.<br...
<b>Problem B. Hierarchyb> [cut] Note that if employee, except one, has exactly one, Contest discussion <http://codeforces.me/blog/entry/447> <b> Problem A. Noldbach

Full text and comments »

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

62.
By Zlobober, history, 11 years ago, translation, In English
Editorial for VK Cup 2015 — Finals Thanks everybody for participating. Tasks follow in the order of the original contest (the mirror order is given in the brackets). [problem:562A] -------------- (in mirror: [problem:566C]) Let's think about formal statement of the problem. We are given a tricky definition of a distance on the tre: $\rho(a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_i$. We need to choose a place $x$ for a competition such that the sum of distances from all vertices of the tree with their weights is minimum possible: $f(x) = w_1 \rho(1, x) + w_2 \rho(x, 2) + \ldots + w_n \rho(x, n)$. Let's understand how function $f(x)$ works. Allow yourself to put point $x$ not only in vertices of the tree, but also in any point inside each edge by naturally expanding the distance definition (for example, the middle of the edge of length $4$ km is located $2$ km from both ends of this edge). **Fact 1**. For any path $x \in [a, b]$ in the tree the function $\rho(i, x)$ is convex. Actually, the ...
on the tre: $\rho(a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_i$. We need to choose a, $ such that there is a path $c -- a -- b -- d$ in the tree. In such manner we may find all internal, ). **Fact 1**. For any path $x \in [a, b]$ in the tree the function $\rho(i, x)$ is convex. Actually, the, **Fact 1**. For any path $x \in [a, b]$ in the tree the function $\rho(i, x)$ is convex. Actually

Full text and comments »

Tutorial of VK Cup 2015 - Finals
  • Vote: I like it
  • +100
  • Vote: I do not like it

63.
By WLZ, history, 3 years ago, In English
A Slight Generalization of Push-Free Segment Trees Hi everyone! I'd like to share a simple way to use the [push-free segment tree](https://codeforces.me/blog/entry/112890) in some cases where the updates aren't commutative (spoiler: they need to be invertible). The uses cases of this trick are rather limited, though. The problem ------------------ We want to solve the following problem: Given an array $a_0, a_1, \dots, a_{N-1}$, whose elements satisfy certain properties (see [here](https://atcoder.github.io/ac-library/production/document_en/segtree.html)), answer $Q$ queries of the following types: - (Range queries): Given $0 \leq l < r \leq N$, find $a_l \cdot a_{l+1} \cdots a_{r-1}$ (endpoints are left inclusive and right exclusive). - (Range updates): Given $0 \leq l < r \leq N$ and a mapping $f$, update $a_i$ to $f(a_i)$ for all $i \in [l, r)$. $f$ has to satisfy the properties described [here](https://atcoder.github.io/ac-library/production/document_en/lazysegtree.html). Push-free segment trees ------------------ ...
$0 \leq l < r \leq N$ and $b$, $c$ ($b \ne 0$), update $a_i$ to $b \cdot a_i + c$ for all $l \leq i, { ... }; // Segment tree element type const S e = ...; // The identity element S op(S a, Sb, ~~~~~ struct S { ... }; // Segment tree element type const S e, The inverse of $f(x) = bx + c$ is $f^{-1}(x) = \frac x b - \frac c b$. Note that the condition $b, struct F { mint a, b; }; S mapping(F l, S r) { return S{r.a * l.a + r.size * l.b, r.size}; } F, using S = array; S op(S a, const S &b) { for (int i = 0; i < K; i++) a[i] += b

Full text and comments »

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

64.
By brunomont, history, 5 years ago, In English
[Tutorial] Dynamic Suffix Arrays Hello, Codeforces! In this blog I will describe yet another <s>useless</s> unconventional data structure. This time, I will show how to maintain an extended suffix array (suffix array, inverse of suffix array, and $lcp$ array) while being able to add or remove some character at the <b>beginning</b> of the string in $\mathcal{O}(\log n)$ amortized time. It can be used to <s>overkill</s> solve problem M from [2020-2021 ACM-ICPC Latin American Regionals](https://codeforces.me/gym/103185), which my team couldn't solve during the contest. I learned it from [here](https://oi-wiki.org/string/suffix-bst/) (Chinese), but it is not shown how to maintain the $lcp$ array. Here is the whole code of the data structure. To read this blog, I recommend you ignore this code for now, but use it if you have questions about helper functions, constructors, etc, since I will pass over some implementation details in the explanations. <spoiler summary="Full code"> ~~~~~ struct dyn_sa { struct ...
a binary search tree called <b>Amortized weight-balanced treesb> (see below for references). The, of the string (and, equivalently, a single node in the binary search tree), and the previous, . Instead, we will use a binary search tree called <b>Amortized weight-balanced treesb> (see below

Full text and comments »

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

65.
By Noam527, history, 4 years ago, In English
Attempting to Extend Segment Trees to Arbitrary Subsets Throughout the last several weeks I have tried to invent and solve, a generalization of segment trees (although now it doesn't fit to name it "segment trees"... see for yourself). The results are very few (and not good, if you ask me), but the problem was very appealing and fun to think about. The purpose of this blogpost is to share my experience with this problem, in order to provide curiousity to at least a few people, and also to let bright-minded users tackle this problem together, and hopefully achieve better results. Since I want to share my experience, I will also put some possibly challenging parts under spoilers, if you want to attempt it yourself. So, there is no tl;dr. Sorry :) The Motivation and The Problem ------------------------------ As the title suggests, the motivation was from inspection of segment trees. Define the following problem, which we will try to solve throughout this post: Given $n$ elements $a_0, \ldots, a_{n-1}$, initially $0$, and $m$ subs...
choosing a new $N$ (for instance, in a tree we had $N = 2n$ since we also initialized another array $b, nodes in the segment tree, setting $S_i$ for every element as the set of $O(\log n)$ ranges that

Full text and comments »

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

66.
By null_awe, 2 years ago, In English
Codeforces Global Round 26 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-06-08] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:null_awe,2024-06-08] | 800 | 1000 | 1200 | 1700 | 2200 | 2400 | 2500 | 2900 | 3400 | | [user:buffering,2024-06-08] | 800 | 1000 | 1300 | 1800 | 2300 | 2400 | 2600 | 3100 | 3500 | | [user:redpanda,2024-06-08] | 800 | 1100 | 1200 | 1800 | | | | | | | [user:thescrasse,2024-06-08] | 800 | 1000 | 1200 | 1600 | 2200 | 2500 | 2500 | 3100 | 3400 | | [user:bronze_coder,2024-06-08] | 800 | 1000 | 1600 | 1800 | 2400 | | | 2700 | 3500 | | [user:awesomeguy856,20...
, if our original points are $A$ and $B$, then we need to consider rooting our tree at either $T_1$ or

Full text and comments »

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

67.
By oursaco, history, 3 years ago, In English
Codeforces Round 914 (Div. 2) Editorial Sorry for the weak pretests on A :(. We hope you enjoyed the round nonetheless. [problem:1904A] Idea: [user:Apple_Method,2023-12-09] <br> Preparation: [user:Apple_Method,2023-12-09]/[user:oursaco,2023-12-09] <br> Analysis: [user:lunchbox,2023-12-09] <spoiler summary="Solution"> There are at most $8$ positions of the knight that can attack a single cell. Therefore, we can find all $8$ positions that attack the king and the $8$ positions that attack the queen and count the number of positions that appear in both of these lists. </spoiler> <spoiler summary="Code"> ```c++ #include <bits/stdc++.h> using namespace std; int dx[4] = {-1, 1, -1, 1}, dy[4] = {-1, -1, 1, 1}; int main(){ int t; cin >> t; for(int i = 0; i < t; i++){ int a, b; cin >> a >> b; int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; set<pair<int, int>> st1, st2; for(int j = 0; j < 4; j++){ st1.insert({x1+dx[j]*a, y1+dy[j]*b}); ...
depth of a node on the tree. We can re-root the tree from $a$ to $b$ by subtracting one from all

Full text and comments »

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

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

Full text and comments »

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

69.
By aryanc403, 12 hours ago, In English
Codeforces Round 1137 Discussion Stream (with Hints) The editorial video for [contest:2289] is now available [here](https://youtu.be/fdB2s_PBKlI). Do check out the [CF Video Editorial Finder](https://codeforces.me/blog/entry/154724) browser extension — it adds links to my video editorials directly from the contest/problems page. You can join in if something in this blog is unclear or if you have more questions. [problem:2289A] <spoiler summary="Hint 1"> What are we really counting here? Focus on the number of odd divisors vs even divisors of $x$. </spoiler> <spoiler summary="Hint 2"> Artem moves first and can choose any parity. He'll pick the parity with more divisors!<br> The second player wins only if the count of odd divisors equals the count of even divisors. </spoiler> <spoiler summary="Hint 3"> Case 1: If $x$ is odd, what can we say about all its divisors?<br> <br> All divisors of an odd number are odd. Artem chooses an odd card, and the second player has no even cards to play. Artem wins immediately. </...
Method 3: <b>Fenwick Tree (BIT)b> or <b>Segment Treeb> with coordinate compression

Full text and comments »

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

70.
By makrav, 4 months ago, In English
Codeforces Round 1111 (Div. 2) Editorial Thank you for participating in the round! [problem:2247A] - Idea: [user:PvPro,2026-07-18] - Solution: [user:PvPro,2026-07-18] <spoiler summary = "Hints"> <spoiler summary = "Hint 1"> Try to find an invariant </spoiler> <spoiler summary = "Hint 2"> Consider the sum of all elements in the array </spoiler> </spoiler> <spoiler summary = "Solution"> It's easy to see that $\left( \sum\limits_{i = 1}^n a_i \right) \bmod 4$ does not change after a single operation. Therefore, if $\left( \sum\limits_{i = 1}^n a_i \right) \bmod 4 \neq 0$, then the answer is "NO". Otherwise, let's make $a_1 = 1, a_2 = -1, a_3 = 1, \dots, a_{n - 1} = (-1)^n$. We can always do that by performing operations with indices $1, 2, 3, \dots n - 1$ in this order, and after operation number $i$ we set the $i$-th element to the value we want. After that, $| \sum\limits_{i = 1}^n a_i | \leq 2$, so it is equal to zero because it's the only number divisible by $4$ in that range. </spoiler> ...
the direct parent of $B$ in a tree built from the cell $(1, 1)$ and if $B$ is the direct parent of $A

Full text and comments »

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

71.
By .o., 12 years ago, In English
Good Bye 2014 Editorial First of all, sorry for the late editorial. I was too exhausted and immediately went to bed after the round finished, and didn't write the editorial. There are many pictures in this editorial, to cover up my poor English skills! If you have detected any errors or have questions, feel free to ask questions by comments. Unfortunately, the authors only know English, so we can't answer you if you write comments in Russian. ## [problem:500A] Let's assume that I am in the cell $i$ ($1 \le i \le n$). If $i \le n-1$, I have two choices: to stay at cell $i$, or to go to cell $(i + a_{i})$. If $i = t$, we are at the target cell, so I should print "YES" and terminate. If $i > t$, I cannot go to cell $t$ because I can't use the portal backwards, so one should print "NO" and terminate. Otherwise, I must go to cell $(i + a_{i})$. Using this method, I visit each cell at most once, and there are $n$ cells, so the problem can be solved in linear time. #### What is test 13? There are 9...
is not in the subtree of vertex $u$. So, $A \cup B$ is the set of vertices in thetree, and $A \cap B, trees, which is well known. $size(B)$ equals to $N - size(A)$.

Full text and comments »

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

72.
By Kevin114514, history, 4 years ago, In English
CodeForces Round 872(Div. 1&2) Editorial ## A. LuoTianyi and the Palindrome String Consider the substring of $s$ from the second character to the last, or $s_2s_3\cdots s_n$. If it's not palindrome, then the answer must be $n-1$. What if it's palindrome? This implies that $s_2=s_n$, $s_3=s_{n-1}$, and so on. Meanwhile, the fact that $s$ is palindrome implies $s_1=s_n$, $s_2=s_{n-1}$, etc. So we get $s_1=s_n=s_2=s_{n-1}=\cdots$ or that all characters in $s$ is the same. In this situation, every subsequence of $s$ is palindrome of course, so the answer should be $-1$. <spoiler summary="Code"> ```cpp #pragma GCC optimize(3,"Ofast","inline") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //#define ll int #define ft first #define sd second //#define endl '\n' #define pb push_back #define ll long long #define pll pair<ll,ll> #define no cout<<"NO"<<'\n' #define no_ cout<<"No"<<'\n' #def...
components merge into each other. We use segment trees to maintain the $b$ value of the vertices and the $d

Full text and comments »

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

73.
By Proof_by_QED, history, 17 months ago, In English
EPIC Institute of Technology Round Summer 2025 (Codeforces Round 1036, Div. 1 + Div. 2) Editorial Thanks for participation! We hope you loved the contest. #### [problem:2124A] Problem Credits: [user:Lilypad,2025-07-01] <br> <spoiler summary="Hint"> When is there definitely *not* a solution? </spoiler> <spoiler summary="Solution"> First, note that since relative order is preserved no matter which elements are deleted, if $a$ is originally sorted in nondecreasing order, the array cannot be a derangement no matter which elements are deleted. If $a$ is not sorted, we can note that any two elements that form an inversion pair satisfies the requirements. The total runtime is $O(n)$. </spoiler> <spoiler summary="Code"> ``` #include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int> arr(n); for(auto &x : arr) cin >> x; for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(arr[i] > arr[j]){ cout << "YES\n2\n"; cout << arr[i] << " " << a...
$p_i$. This means that we can see the input array $b$ as the depths in a tree, where $j$ is the, Using this, let's come up with a recursive function that traverses this tree and finds the

Full text and comments »

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

74.
By kartik8800, history, 6 years ago, In English
Dynamic Programming on Trees Hello Codeforces!! In this blog, I want to present to you a beginner-friendly video lecture series on dynamic programming on trees/an editorial for the CSES tree algorithms section. [CSES](https://cses.fi/problemset/) is a brilliant problemset for people wanting to get started at competitive programming and get good at it. My aim till now has been to make the explanations intuitive, crisp and clear. I feel even a beginner will be able to benefit from these video lectures. So let's get started.<br>[Link to the problems](https://cses.fi/problemset/)<br> Subordinates ------------ Explanation : [https://youtu.be/fGznXJ-LTbI](https://youtu.be/fGznXJ-LTbI)<br> AC code : https://github.com/kartik8800/CSES/blob/master/Subordinates Tree Matching ------------ Somehow I feel some other nice approaches are also possible, please do share.<br> Explanation : [https://youtu.be/RuNAYVTn9qM](https://youtu.be/RuNAYVTn9qM)<br> AC code : https://github.com/kartik8800/CSES/blob/...
Appleman and tree ------------ problem statement: [https://codeforces.me/problemset/problem/461, Problem Statement : what is the distance between nodes a and b? Short explanation : Let LCA(a, lvl[i] : level of node i in the tree. Ans to query distance(a,b) = (lvl[a] — lvl[x

Full text and comments »

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

75.
By ssk4988, history, 7 months ago, In English
Tree Diameter Implementation In this blog, I will go over a clean way to find the diameter of a tree (and recover the nodes on the diameter). If you are unsure of what the diameter of a tree means, consult [this blog](https://codeforces.me/blog/entry/101271). The standard algorithm for finding the endpoints of a diameter is as follows: 1. Pick an arbitrary node (such as node $0$) and find the farthest node from it using a DFS. Let's call this new node $a$. 2. Find the farthest node from $a$ with another DFS. Let's call this new node $b$. The path from $a$ to $b$ is a diameter of a tree. Note that there are multiple valid diameters in a tree. Implementations of this algorithm use a DFS that returns the deepest leaf in a node's subtree and the depth of that leaf. A typical implementation in C++ is below. ~~~~~ auto dfs = [&](int u, int p, auto &&dfs) -> pair<int, int> { pair<int, int> res{-1, u}; for(int v : adj[u]) if(v != p) res = max(res, dfs(v, u, dfs)); res.first++; ...
Tree Diameter Implementation, ); auto [dist2, b] = dfs(a, -1, dfs); vector diameter; for(int x = b; x != -1; x = parent[x, ++; return res; }; auto [dist1, a] = dfs(0, -1, dfs); auto [dist2, b] = dfs(a, -1, dfs); ~~~~~, . Let's call this new node $b$. The path from $a$ to $b$ is a diameter of a tree . Note that there are, 2. Find the farthest node from $a$ with another DFS. Let's call this new node $b $., The path from $a$ to $b$ is a diameter of a tree. Note that there are multiple valid diameters in a

Full text and comments »

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

76.
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...
be a tree, the diameter of the tree is at least $2$ when it comes to each node has an edge with node

Full text and comments »

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

77.
By ramchandra, 6 years ago, In English
Splay tree tutorial This tutorial is about the splay tree, a self-balancing binary search tree. ##### Key features: * $O(\log n)$ amortized operations. * $O(n)$ construction time complexity (you can simply build a binary search tree) * Memory-efficient: no additional space needed apart from the binary search tree. The key idea behind the splay tree is the splay function, which rotates nodes so as to balance the tree. Since this consists only of tree rotations, this does not affect the binary search tree ordering. ##### Tree rotation A tree rotation inverts the relationship between a parent and a child node, _without_ affecting the in order traversal of the binary search tree. See the animation below. ![Tree rotation](/predownloaded/bc/87/bc87ae5e4f0a40597786b727489d11a148522560.png) ([Animation source](https://commons.wikimedia.org/wiki/File:Tree_rotation_animation_250x250.gif): Wikipedia user Tar-Elessar, licensed under CC-BY-SA 4.0) ##### Splay operation During a splay s...
Splay tree tutorial, become the root of the tree*/ for(;parent;rotate()) { if (parent->parent) { (side, ). So, simply attach b as the right child of a. `a` will then be the joined tree . To erase a node, To join two splay trees a and b, where all the keys in a are less than all the keys inb, splay the

Full text and comments »

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

78.
By feecIe6418, history, 2 years ago, In English
Editorial of Codeforces Round 958 (Div. 2) Thanks for participation! **Update**: added alternative solutions/proofs for A,B,D,F [problem:1988A] <spoiler summary="Hint 1"> The optimal sequence of operations is very simple. </spoiler> <spoiler summary="Solution"> The optimal sequence of operations is adding $k-1$ 1-s into the set each time, at the same time decreasing $n$ by $k-1$. This implies that the answer is $\lceil \frac{n-1}{k-1}\rceil$. <spoiler summary="Why?"> I failed to find a Div2-A level proof. If you have a simpler proof please share it in the comments. Consider the number of elements that is $\equiv 1\pmod{(k-1)}$ in the set. The number of such elements increase by at most $k-1$ in each operation, and the aforementioned sequence of operation achieves the maximum increment. --- A simpler proof in the comments: consider the number of elements in the set. It increases by at most $k-1$ each time, and our construction reaches the maximum increment. </spoiler> </spoiler> <spoiler summar...
Consider an vertex with the maximum $b$, equal to $u$. Root the tree at this vertex $x$. The

Full text and comments »

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

79.
By ch_egor, 7 years ago, In Russian
Разбор контеста на стажировку в Яндексе 2019 Привет! В феврале стартовал набор на [летнюю стажировку](http://yandex.ru/yaintern/?utm_source=cf) для разработчиков и аналитиков в [user:Yandex,2020-03-24]. Мы подготовили [тренировку](https://codeforces.me/gym/102558), куда вошли задачи контеста для разработчиков бэкенда, которые были использованы в процессе отбора в прошлом году. **Задачи соревнования подготовлены:** - [problem:102558A] подготовил и разобрал [user:Pavluha,2020-03-20] - [problem:102558B] подготовил и разобрал [user:ch_egor,2020-03-20] - [problem:102558C] подготовил и разобрал [user:Lollipop,2020-03-20] - [problem:102558D] подготовил и разобрал [user:Lollipop,2020-03-20] - [problem:102558E] подготовил [user:halyavin,2020-03-20], разобрал [user:Lollipop,2020-03-20] - [problem:102558F] подготовил и разобрал [user:ch_egor,2020-03-20] А также [user:Chmel_Tolstiy,2020-03-23], [user:Andreikkaa,2020-03-23], [user:dalex,2020-03-23], [user:BogolyubskiyAlexey,2020-03-23], [user:VovanF98,2020-03-23], ...
) if nx.value == b: need_add = False tree = remove(tree, r), if need_add: tree = add(tree, Node(r, b)), if pr.x + 1 == l and pr.value == b: tree = remove(tree, pr.x)

Full text and comments »

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

80.
By kartik8800, 7 years ago, In English
CSES Range Queries section editorial **UPD:** some video editorials on range query data structures: [youtubePlaylist](https://www.youtube.com/playlist?list=PLb3g_Z8nEv1isaHPaXL1j-pSo60812JtY) Hello Codeforces, In this blog I will try to write a well detailed editorial for the CSES Range Queries section. The motivation for this editorial comes from https://codeforces.me/blog/entry/70018. Quoting [user:icecuber,2020-05-09] "I think [CSES](https://cses.fi/problemset/) is a nice collection of important CP problems, and would like it to have editorials. Without editorials users will get stuck on problems, and give up without learning the solution. I think this slows down learning significantly compared to solving problems with editorials. Therefore, I encourage others who want to contribute, to write editorials for other sections of CSES." So here I am writing an editorial for the range queries section. If you find any error or maybe have a better solution to some problem please do share. Range Sum Queries I =...
,b] we shall do a brute force. So build a segment tree over the buckets and calculate the sum, <b> Approach 2 b> This approach is more efficient and some might also find it easier to, <b>Define : DP[i][j]b> as the number of trees in the rectangle described by (1,1) and (i,j)., Now let's try to generate the answer for some interior node <b>Pb> of the segmenttree assuming, So build a segment tree over the buckets and calculate the sum over all completely included buckets, So try solving the problem under the constraint that p,a,b <= 10^7. Now the problem is much

Full text and comments »

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

81.
By spike1236, 21 month(s) ago, translation, In English
Virtual trees method This article explores the concept of *virtual trees*, proves their key properties, describes an efficient algorithm for their construction, and then applies the method to solve a specific problem using dynamic programming (DP) on trees. ## Introduction Many tree-related problems require working with a subset of vertices while preserving the tree structure induced by their pairwise lowest common ancestors (LCA). The concept of a *virtual tree* allows us to transition from the original tree $T$ with $N$ vertices to a substructure whose size linearly depends on the size of the selected set $X$. This significantly accelerates algorithms, particularly for DP computations. ## Definition of a Virtual Tree Let $T$ be a given rooted tree, and $X$ be some subset of its vertices. A **virtual tree** $A(X)$ is defined as follows: $$ A(X) = \{ \operatorname{lca}(x,y) \mid x,y \in X \}, $$ where $\operatorname{lca}(x,y)$ denotes the lowest common ancestor of vertices $x$ and $y$ in tr...
// Function to build a virtual tree for color c and perform DP. void calc_aux(int c, int &ans, ] < tin[b]; }); vector verstk = {1}; // Initialize stack with the root of tree T (vertex 1

Full text and comments »

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

82.
By tibinyte2006, 2 years ago, In English
[Tutorial] Li Chao Tree Extended 2 Hello, Codeforces! <font color='white'>new round dropping soon btw</font> There are ways to modify [Li Chao Tree](https://cp-algorithms.com/geometry/convex_hull_trick.html) to support more powerful types of operations, some of which are already described [here](https://codeforces.me/blog/entry/86731). This tutorial will focus on extending the aforementioned data structure to solve the following problem: - Operation 1: Add a new line - Operation 2: For a given point, find the line that yields the $k$-th minimum value at that point We will assume, without loss of generality, that $k$ does not change during the queries. Our goal is to perform those operations in $O(k \cdot log C)$ each. Note that a simple Li Chao Tree solves our problem for $k=1$. <hr> #### The Idea Since a normal Li Chao Tree stores the best line in each node, it is natural to think that all we need to do is to keep the best $k$ lines. ( where the _best_ line is defined as the line that gives the mini...
[Tutorial] Li Chao Tree Extended 2, modify [Li Chao Tree ](https://cp-algorithms.com/geometry/convex_hull_trick.html) to support more, ~~~~~ struct line { int a, b; int eval(int x, Suppose it will be above $a$ lines in the first half and $b$ in the second. By the claim above, it, nth_element(a[node].begin(), a[node].begin() + 2 * k - 2, a[node].end(), [&](line a, lineb

Full text and comments »

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

83.
By satyam343, 4 years ago, In English
Codeforces Round #838 (Div. 2) Editorial Thank you for participation! I hope you liked atleast one problem from the set (: We tried hard to have an interesting problemset. It is sad to see people disliking the round only because some problems were hard. Please read the intended solutions to know why we decided to put the problems(especially D) at current positions. [problem:1762A] Idea:[user:satyam_343,2022-12-16] <spoiler summary="Hint 1"> If sum is even, answer is $0$. Otherwise we need to change parity of atleast one element of $a$. </spoiler> <spoiler summary="Hint 2"> It it optimal to change parity of atmost one element. </spoiler> <spoiler summary="Hint 3"> Answer can be atmost $20$, as we need to divide any integer $x$ ($1 \leq x \leq 10^6$) atmost $20$ times to change its parity. </spoiler> <spoiler summary="Solution"> We are assuming initial sum is odd. Suppose $f(x)(1 \leq x \leq 10^6)$ gives the minimum number of operations needed to change parity of $x$. Iterate from $i=1$ to ...
=998244353; const ll MAX=500500; vector fact(MAX+2,1),inv_fact(MAX+2,1); ll binpow(ll a,llb,ll

Full text and comments »

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

84.
By rembocoder, 4 years ago, translation, In English
Simple DP optimizations No, I don't mean Convex Hull Trick and Knuth optimization. I mean simpler and more common methods. _This is a continuation of my series of posts on DP, to understand the terminology read the [prologue](https://codeforces.me/blog/entry/102542)._ ### Transitions from a segment Very often after building the DP graph one can discover that the transitions into a state go not from a random set of vertices, but from some segment of values for one of the parameters. _For example, from states `dp[i][j]` with some constant `i` and `j` lying in a segment `[a, b]`._ **In such cases one may not implement each transition separately, but to implement them all at once.** If by implementing a transition we mean adding from `dp[A]` to `dp[B]`, then we can use prefix sums. In case if we need to find the _best_ transition into `dp[B]`, then we can use Segment Tree. #### An Example [AtCoder DP Contest: Problem M](https://atcoder.jp/contests/dp/tasks/dp_m) _Find the number of integer seq...
sums. In case if we need to find the _best_ transition into `dp[B]`, then we can use SegmentTree.

Full text and comments »

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

85.
By SecondThread, history, 7 years ago, In English
Why problem writers should stop saying “It is guaranteed that” Please Stop Guaranteeing Things ================== There are two common meanings for something being “guaranteed”, and often it is up to the reader to guess the author’s intended meaning. This is annoying and creates unnecessary barriers to entry. **Meaning #1:** The thing we are guaranteeing is provably true for the given input. The thing we are guaranteeing is simply true. We don’t want to provide a proof since it would be long, unnecessary, and annoying to read, and might spoil the solution, but you have our word that an answer always exists. Example: We give you two positive integers A and B (1 <= A, B <= 100). Find some positive integer C (1 <= C <= 200) such that C < A + B. **It is guaranteed that some C exists.** **Meaning #2:** The only input that is legal is input for which this is true. The thing we are guaranteeing might not always be true without this guarantee. Thankfully, we are providing this guarantee so that you only need to concern yourself with solving t...
integers A and B (1 <= A, B <= 100). Find some positive integer C (1 <= C <= 200) such that C < A +B

Full text and comments »

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

86.
By KADR, 16 years ago, translation, In English
All-Ukrainian School Olympiad in Informatics: editorial (A,B,C,D,E,F) <p></p><div>The editorial is now completed.</div><div><br></div><div><div><b>Problem A: Gift (Roman Iedemskyi)</b></div><div><br></div><div>Suppose that the pair $(A,B)$ is an optimal solution, where $A$ is the number of gold coins in a gift and $B$ is a number of silver coins. It is easy to see &nbsp;that there exist two (probably equal) indexes $i$ and $j$ such that $g_i=A$ and $s_j=B$. It is true, because in the other case we could decrease either $A$ or $B$ without changing connectivity of the graph.</div><div><br></div><div>Let $R(A,B)$ be the graph in which for all $i$ the following statement holds: $g_i \leq A \wedge s_i \leq B$.</div><div><br></div><div>Let $T(A)$ be the weighted graph in which for all edges $g_i \leq A$. For each edge $i$ we will assign a weight equal to $s_i$. Let's find a spanning tree of this graph, which has the property that its maximal edge is minimal possible. It can be shown that for the fixed $A$ the minimal value of $B$ for which graph $R(A,B)$ is st...
All-Ukrainian School Olympiad in Informatics: editorial (A,B,C,D,E,F), The editorial is now completed. <b>Problem A: Gift (Roman, will assign a weight equal to $s_i$. Let's find a spanning tree of this graph, which has the property, Claim. Minimal spanning tree of a graph has the property that its maximal edge is, Proof. Let $L$ be the minimal spanning tree of a graph. Suppose there exists a spanning, Suppose that for some value of $i$ we have already found minimal spanning tree in every

Full text and comments »

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

87.
By ko_osaga, history, 14 months ago, In English
Squarepoint Challenge (Codeforces Round 1055, Div. 1 + Div. 2) Editorial Thank you for your participation! Problem A, B were authored by [user:djm03178,2025-10-03]. Problem C was authored by [user:As_dfsdf,2025-10-03]. Problem D was authored by [user:qwerasdfzxcl,2025-10-03]. Problem E, F, G, H1, H2 were authored by [user:ko_osaga,2025-10-03]. [problem:2152A] <spoiler summary="Spoiler"> [tutorial:2152A] </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; set<int> s; for (int i = 0; i < n; i++) { int x; cin >> x; s.insert(x); } cout << s.size() * 2 - 1 << '\n'; } } ~~~~~ </spoiler> [problem:2152B] <spoiler summary="Spoiler"> [tutorial:2152B] </spoiler> <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; wh...
Thank you for your participation! Problem A, B were authored by [user:djm03178,2025-10-03

Full text and comments »

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

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

Full text and comments »

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

89.
By SpyrosAliv, 12 months ago, In English
Codeforces Round 1063 Editorial <spoiler summary="Comment"> B turned out to be harder than expected. I apologize for this, but I hope there are still problems that are fun and educational for you to solve in this round. Regardless, I hope this round encourages authors to include communication problems in their future rounds, and in earlier positions as well. </spoiler> [Problem A &mdash; Souvlaki VS. Kalamaki](https://codeforces.me/contest/2163/problem/A) <spoiler summary="Solution"> Suppose it Kalamaki's turn on some even round $2k$. Kalamaki can swap element $a_{2k}$ with $a_{2k+1}$. If $a_{2k} > a_{2k+1}$, he will not swap the elements, but if $a_{2k} < a_{2k+1}$, he will swap them. In both cases he wins the game, because the array will never be sorted. Therefore, if $a_{2k} \neq a_{2k+1}$, Kalamaki will win no matter what. Now assume every time Kalamaki plays, the two elements he can swap have the same value, because otherwise we have shown that he wins. Suppose that it is Souvlaki's turn on round...
template using oset = tree, rb_tree_tag

Full text and comments »

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

90.
By NetSpeed1, 23 months ago, In English
Codeforces Global Round 28 Editorial [problem:2048A] Author: [user:Little09,2024-12-19] <spoiler summary="Hint 1"> How much does the number decrease when we remove two consecutive $3$ s? </spoiler> <spoiler summary="Tutorial"> ### [problem:2048A] When we transform $\overline{x33y}$ into $\overline{xy}$ (where $x$ and $y$ are decimal numbers), the actual value changes from $10^{p+2} \cdot x + 33 \cdot 10^p + y$ to $10^p \cdot x + y$. The decrease is $99 \cdot 10^p \cdot x + 33 \cdot 10^p$. It is easy to see that $33 \mid (99 \cdot 10^p \cdot x + 33 \cdot 10^p)$. Therefore, we can replace the operation of removing two consecutive $3$ s with a series of $-33$ operations. Hence, we only need to determine whether $x$ can be reduced to $0$ using a series of $-33$ operations, which is equivalent to checking whether $x \bmod 33$ equals zero. </spoiler> [problem:2048B] Author: [user:wsyear,2024-12-19] <spoiler summary="Hint 1"> If the permutation is sufficiently long, what is the maximum number of leng...
Construct a **min Cartesian tree** for the sequence $b$. It is easy to observe that we will only

Full text and comments »

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

91.
By snuke, 12 years ago, In English
Codeforces Round #263 Tutorial [Div2 A Appleman and Easy Task](http://codeforces.me/contest/462/problem/A) (Author: [user:wolf_sothe,2014-08-26]) This is a simple implementation problem. You can solve by searching adjacent cells of every cell. [Div2 B Appleman and Card Game](http://codeforces.me/contest/462/problem/B) (Author: [user:wolf_sothe,2014-08-26]) This is simple greedy problem, but it seemed to be reading-hard. The statement says, "Choose K cards from N cards, the score of each card is (the number of cards which has the same character in <b>K</b> cards. (not in N cards)" It is clear that this total score is (the number of 'A' in K cards)^2 + (the number of 'B' in K cards)^2 + ... + (the number of 'Z' in K cards)^2 This value will be maximized by the simple greedy algorithm, take K cards from most appearred character in N cards, the second most appearred character in N cards, and so on. [Div1 A / Div2 C Appleman and Toastman](http://codeforces.me/contest/461/problem/A) (Author: [user:ho...
[Div1 B / Div2 D Appleman and Tree](http://codeforces.me/contest/461/problem/B ) (Author

Full text and comments »

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

92.
By awang11, history, 9 months ago, In English
Codeforces Round 1085 (Div. 1 + Div. 2) Editorial <center> <table class="tex-tabular bordertable" style="border-left: none; border-right: none; border-top: 1px solid; border-bottom: 1px solid; border-collapse: collapse;"> <tbody> <tr> <td class="tex-tabular-text-align-center" style="border-left: none; border-right: none; border-top: none; border-bottom: none;"> <span class="tex-font-size-small"> <span class="tex-font-style-it"> <a href="https://www.youtube.com/watch?v=HCYKLnT0UNU">Trophy Presentations — Asuka Ota, Ryo Nagamatsu, Mario Kart Wii</a> </span> </span> </td> </tr> </tbody> </table> </center> **UPD 1:** added hints, problem credits, more specific acknowledgements and some remarks. Implementations are on the way, sorry for making y'all wait! **UPD 2:** Implementations are finally here. [problem:2207A] Author: [user:awang11,2026-03-09] Preparers: [user:awang11,2026-03-09], [user:IceSerpent,2026-03-09] Anal...
struct Tree { typedef ll T; static constexpr T unit = 1e9; T f(T a, T b) { return

Full text and comments »

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

93.
By Ahnaf.Shahriar.Asif, history, 7 years ago, In English
DP Tutorial and Problem List Today I've listed some DP tutorials and problems. Actually, I made it for my personal practice. But I think It may Help others too. Update: I write stuff [Here](https://duoblogger.github.io) in Bengali. I probably have one or two basic DP tutorials too. If you understand Bengali, it may help. **Note: If you have some other tutorial links and nice problems, mention them. I'll add them here. It'll help me too.** ## Dynamic programming: * [Topcoder Tutorial](https://www.topcoder.com/community/competitive-programming/tutorials/dynamic-programming-from-novice-to-advanced/) * [Dynamic Programming,from novice to advanced](https://www.cnblogs.com/drizzlecrj/archive/2007/10/26/939159.html) * [Learn DP and other tricks](https://www.codechef.com/certification/data-structures-and-algorithms/prepare#foundation) * [Non-trivial DP tricks](https://codeforces.me/blog/entry/47764) * [Everything about Dynamic Programming](https://codeforces.me/blog/entry/43256) * [Digit DP 1](https://...
* [Appleman and Trees](https://codeforces.me/contest/461/problem/B) * [Counting On Trees](https

Full text and comments »

94.
By Wind_Eagle, history, 5 years ago, translation, In English
How to train: why it's not enough to just do a lot of tasks Hello, Codeforces! I, like many of you, read blogs periodically. Lately, blogs from low-rated users who ask me how to raise their ratings have been catching my attention. I want to tell you a little bit about my opinion on these blogs. So what do these blogs look like? Usually this is a blog with a title something like <b>"I need help right now!"</b> or <b>"How to improve my rating, help me!"</b> When you open this blog, you see the most detailed description of the problem, such as: "I have solved 500 problems, but no improvement" or "I have solved 100 problems with rating >= 1500, but my rating is not increasing". And in the comments they usually write "you haven't solved enough, solve more" or "solve more difficult problems". <b>In my opinion, this is incorrect and misleads such users. So, imagine that you do not know anything at all about sports programming, or even about the basics of Olympic math. You at best (because many people don't even do that) have learned a programmin...
so many gray people who learn the Cartesian tree and Mo algorithm — they don't quite, The situation with problems B, C, and D is even worse. To solve them, you usually need to already

Full text and comments »

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

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

Full text and comments »

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

96.
By riadwaw, 12 years ago, translation, In English
Tutorial CodeForces Round 289 (Div.2) (Second Winter Computer Camp Selection 2015) [problem:509A] In this problem one needed to implement what was written in the statement: create matrix (two-dimensional array) using given rules and find maximal value in the table. It is also possible to see that maximal element is always in bottom-right corner. Easier solution with recursion also was enough to get AC: ~~~~~ def elem(row, col): if row == 1 or col == 1: return 1 return elem(row - 1, col) + elem(row, col - 1) ~~~~~ One may see the [Pascal's triangle](http://en.wikipedia.org/wiki/Pascal%27s_triangle) in the given matrix and understand that answer is equal to $\binom{2n - 2}{ n - 1}$ Prepared by: [user:AlexDmitriev,2015-01-31] Author of editorial: [user:AlexDmitriev,2015-01-31] [problem:509B] Suppose there are two piles with number of pebbles differed by more than $k$, then there is no solution: $a_i = \sum_{c=1}^k b_{i, c} \le \sum_{c=1}^k (b_{j, c} + 1) = a_j + k $ Now let $M = \max a_i \le \min a_i + k = m + k$. ...
Consider a tree with $n$ vertices rooted at vertex 1 and let $b$ be the pseudocode’s (DFS

Full text and comments »

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

97.
By adamant, history, 4 years ago, In English
Big integers with negative digits: The Trygub numbers Hi everyone! Today we will talk about something that might be useful in programming competitions. Yay! Also great thanks to [user:antontrygubO_o,2023-04-30] for sharing this with me and others in a Discord server. Let's implement a data structure that maintains a big number $N$ in base $b$ and supports the following: - Given (possibly negative) integers $|x|, |y| \leq n$, add $x b^y$ to $N$. - Given $k$ and assuming $N \geq 0$, print the $k$-th digit of $N$. - Check if $N$ is positive, negative or equals to $0$. Each operation should take at most $O(\log n)$ amortized time and $O(q)$ memory. While some approach you may think of immediately would imply using segment tree, or a similar structure, the solution proposed here only requires `std::map`, so it's much shorter and easier to implement (at the slight expense of increased constant factor). It may be used in the following problems: - [#2302. 「NOI2017」整数](https://loj.ac/p/2302) - [problem:1817E] - [problem:1810F] ...
a Discord server. Let's implement a data structure that maintains a big number $N$ in base $b

Full text and comments »

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

98.
By DanAlex, history, 11 years ago, In English
How to sweep like a Sir ### Cutting to the chase Clearly you don't need a PhD in Computing to sweep in the yard , but one might be useful in order to know linear and radial sweep algorithms. So , what's all about ? It's just what it sounds it is , sweeping linear ( up to down , for example ) or radial ( making a 360 degrees loop ). How this can help? [cut] Well... ### Linear sweep Suppose you a set of objects in an Euclidean plane. We need to extract information about some objects. The method of linear sweeping takes a line and moves it on a fixed direction. Usually the line taken would be vertical and the direction would be left to right or up to down. ![ ](https://upload.wikimedia.org/wikipedia/commons/2/25/Fortunes-algorithm.gif) Quite abstract for the moment , huh ? Let's go to a more specific example. #### Rectangle union area This example is well known. You have a set of rectangles with edges parallel to the OX and OY axes. What is their union area. Well , first of all , let'...
by the point projections of the ends of the edge. For example D and C will be projected inB and A

Full text and comments »

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

99.
By Bashca, 6 years ago, In English
Fenwick Tree generalization using Centroids Hello, Codeforces community! (Again) After asking many times, I realized that the central idea of this blog was not being understood, and I’ve finally decided to rewrite it. This time I want to be clearer and provide more details. This is not about the classic centroid decomposition, but I’ll try to keep it self-contained so the concept is understandable within this blog. --- ## What is a Centroid? In a tree, a centroid is a node that, when removed along with its incident edges, minimizes the size of the largest remaining connected component, see figure 1. <center> <img src="/predownloaded/03/3f/033f954d1d44920150b706caa12c0045f41bced4.png" alt="centroid of a tree and remaining components"> <br> <I>figure 1. Centroid of a tree and remaining components</i> </center> **Claim**: Let $W(v)$ be the size of the largest component after removing node $v$, and $n$ be the total number of nodes. If $v$ is a centroid, then: $$W(v) \le \frac{n}{2}$$ **Proof**: Supp...
Fenwick Tree generalization using Centroids, a Centroid? In a tree, a centroid is a node that, when removed along with its incident edges, know $value(a) + value(b) - 2 * value(LCA(a, b))$ and check if it's equal to $0$., ); int m; scanf("%d%d", &n, &m); for (int i=0; ib; scanf("%d%d, +i); } for (int i=0; ib; scanf("%d%d", &a, &b); g[a, ; (b) one is an ancestor of the other, but their emission sets partially overlap; (c) one is an

Full text and comments »

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

100.
By errorgorn, history, 5 years ago, In English
Codeforces Round #723 (Div. 2) Editorial [problem:1526A] ------------------ Setter: [user:antontrygubO_o,2021-05-28] Preparer: [user:errorgorn,2021-05-28] <spoiler summary="Hint 1"> Notice that the array size is even length. Usually in such problems, we would split the array into $2$ equal parts. Can you figure out what those $2$ parts are? </spoiler> <spoiler summary="Hint 2"> We sort the array and split it into the big half and the small half. </spoiler> <spoiler summary="Solution"> The main idea is that we can split the numbers into the two halves, the big half and small half, we can place the bigger half at the odd positions and the smaller half at the even positions. This works because the smallest big number is larger than the biggest small number. Hence, the mean of any two small numbers is smaller than any big number, and the mean of any two big numbers is bigger than any small number. </spoiler> <spoiler summary="Code (C++)"> ```c++ //雪花飄飄北風嘯嘯 //天地一片蒼茫 #include <bits/stdc++.h> #inc...
indexed_set tree,rb_tree_tag,tree_order_statistics_node_update> //change less to, /tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef tree

Full text and comments »

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

101.
By omsincoconut, 5 weeks ago, In English
WorldQuant Round 1 (Codeforces Round 1128, Div. 1 + 2) Editorial <spoiler summary="Rating predictions"> | Predictor | A | B | C | D1 | D2 | E | F1 | F2 | G | H | |-----------|---|---|---|----|----|---|----|----|---|---| | Predicted | 486 | 927 | 839 | 1160 | 2236 | 1694 | 2406 | 3639 | 2607 | 3250 | | [user:nifeshe,2026-10-18] | 800 | 900 | 1100 | 1400 | 2600 | 2000 | 2500 | 3500 | 2900 | 3400 | | [user:ttamx,2026-10-18] | 800 | 1000 | 1200 | 1400 | 2500 | 1800 | 2100 | 3500 | 2800 | 3100 | | [user:ItzSleepyXD,2026-10-18] | ? | ? | 1000 | ? | ? | ? | 2100 | 2800 | ? | ? | | [user:simplelife,2026-10-18] | 800 | 1000 | 1100 | 1500 | ? | 1900 | 2300 | 3500 | ? | 3000 | | [user:wakanda-forever,2026-10-18] | 900 | 1000 | 1100 | ? | ? | 2000 | 2100 | ? | ? | ? | | [user:Marszpace,2026-10-18] | 800 | 1000 | 1100 | 1500 | ? | 1900 | ~2200 | ? | ? | ? | | [user:Argentum47,2026-10-18] | 800 | 1200 | 1200 | 1600 | ? | 1900 | 2300 | ? | ? | 2700 | | [user:omsincoconut,2026-10-18] | 800 | 1100 | 1300 | ? | ? | ? | 2400 | 3500 | 2600 | 3100 | | [user:...
template using oset = tree, rb_tree_tag

Full text and comments »

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

102.
By artew, 3 years ago, translation, In English
Codeforces Round #932 (Div. 2) Editorial [problem:1935A] Idea: [user:i_love_penguins,2024-02-24] <br> Preparation: [user:i_love_penguins,2024-02-24] <br> Editorial: [user:i_love_penguins,2024-02-24] <spoiler summary="Hints"> <spoiler summary="Hint 1"> The answer will always have either the prefix $s$, or the reversed string $s$. </spoiler> <spoiler summary="Hint 2"> Adding the string to the end is required no more than once. </spoiler> </spoiler> <spoiler summary="Solution"> Let $t$ be the reversed string $s$. Notice that it is advantageous for us to use operation 1 (adding the reversed string at the end) no more than once. Indeed, having obtained some string, we will simply spend the remaining operations on flipping the string. Thus, we will get the original string or the reversed one, depending on the parity of the number of remaining operations. It is easy to see that the answer will always have either the prefix $s$, or $t$. Then, we find two lexicographically minimal strings with the prefix $s...
vertex $v$ in the tree is $deg_v$, then it's clear that it's necessary to add $deg_v - 1$ edges. Consider

Full text and comments »

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

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

Full text and comments »

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

104.
By lrvideckis, history, 4 years ago, In English
2n memory segment tree by choosing midpoint Hi Codeforces! If you calculate midpoint like ~~~~~ int get_midpoint(int l, int r) {//[l, r) int pow_2 = 1 << __lg(r-l);//bit_floor(unsigned(r-l)); return min(l + pow_2, r - pow_2/2); } ~~~~~ then your segment tree requires only $2 \times n$ memory. <spoiler summary="test"> ~~~~~ #include <bits/stdc++.h> using namespace std; int get_midpoint(int l, int r) {//[l, r) int pow_2 = 1 << __lg(r-l);//bit_floor(unsigned(r-l)); return min(l + pow_2, r - pow_2/2); } int n; set<int> internal_nodes, leaf_nodes; map<int, int> depth_of_segments_not_pow2; void build(int v, int l, int r) {//[l, r) if(r-l == 1) { const int depth_leaf = __lg(v), max_depth = __lg(2*n-1); if(l == 0) {//left-most leaf assert(v == int(bit_ceil(unsigned(n)))); assert(depth_leaf == max_depth); } assert(depth_leaf == max_depth || depth_leaf == max_depth - 1); if((n&(n-1)) == 0) assert(depth_leaf == max_depth); assert(n <= v && v < 2*n); assert(!leaf_nodes.co...
2n memory segment tree by choosing midpoint, ); } ~~~~~ then your segment tree requires only $2 \times n$ memory. , ,r)$ to $[0,r-l)$ and the corresponding segment trees have the same structure, hint: `min(a + x,b

Full text and comments »

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

105.
By cry, 2 years ago, In English
Codeforces Round 962 (Div. 3) Editorial [problem:1996A] Problem Credits: [user:cry,2024-07-19] <br> Analysis: [user:cry,2024-07-19] <spoiler summary="Solution "> If $n$ is a multiple of $4$, then you can have $\frac{n}{4}$ cows. Otherwise, you must have at least one chicken, so you can have $\frac{n-2}{4}$ cows and $1$ chicken. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--){ int n; cin >> n; cout << (n + 2) / 4 << "\n"; } } ``` </spoiler> [problem:1996B] Problem Credits: [user:sum,2024-07-19] <br> Analysis: [user:cry,2024-07-19] <spoiler summary="Solution "> Let's define every $k$ by $k$ block of cells by its value in the top left corner, since all cells in the block must have the same value. So, we can just print out the value of the cell in every $k$'th row and every $k$'th column. </spoiler> <spoil...
There are two configurations to satisfy every, for $a$ and $cnt2_c$ is defined similarly for $b$. Both $cnt_c$ and $cnt2_c$ can be obtained by, reach $b$, we toggle back to the first. We can track maintained roads by performing a range addition on

Full text and comments »

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

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

Full text and comments »

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

107.
By magnus.hegdahl, 5 years ago, In English
[Tutorial] Commutative Segment Trees # Commutative Segment Trees ## Preface This blog is about an alternative way to implement segment trees. Knowing segment tree already should not be necessary to understand this blog, but it is mostly targeted towards people who already know segment trees but don't know how to for example create a merge sort tree that supports updates. <span style="color:green">Pros:</span> - You don't need a fast merge function (which allows you to for example extend to 2D) - Very easy to implement - Fast <span style="color:red">Cons:</span> - Merging has to be commutative - Can't easily be turned lazy (meaning only update or query can be on a range, not both) Disclaimer: This way of implementing segment tree may be what you think of as "a standard segment tree". But the reason I made this blog is that I talked to people who were very familiar with segment trees but did not know how to make a 2D segment tree (which is a trivial modification of this way to implement segment t...
segment trees. Knowing segment tree already should not be necessary to understand this blog, but it, ### Generalization of [CF 406 Div.1 B. Legacy](https://codeforces.me/contest/786/problem/B), Now for counting ones in $s(i, k)$ quickly we can make another array $b$ with the same definition

Full text and comments »

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

108.
By adamant, 12 years ago, translation, In English
Palindromic tree: behind the scenes Hi everyone! As some of you may know, on this summer camp in Petrozavodsk [user:MikhailRubinchik,2014-09-25] presented a new data structure, palindromic tree. I had the honor to participate in the study of the structure for the six months before that, and I want to tell about it now :) [cut]<br> But firstly a brief explanation. If you alredy know basic ideas of the structure, you may go to the <a href="#inter">interest part</a>. Let's to each palindrome assign corresponding string equal to its right half, i.e., its radius and the boolean variable indicating its parity. Now let's merge all our radii of subpalindromes of string $S$ in two prefix trees for even and odd lengths separately. Claim: such trie will be $\mathit O(n)$ in memory. Indeed, there can be no more than $n$ distinct subpalindromes in the string, and each node in trie corresponds with only one unique palindrome. Therefore, we have no more than $n + 2$ nodes. Let's show that such structure can be constructed ...
Palindromic tree: behind the scenes, if we for example take a string $aaaaaaa ... aab$, and then start each time to remove and return $b, ,2014-09-25] presented a new data structure, palindromic tree. I had the honor to participate in the

Full text and comments »

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

109.
By PrinceOfPersia, history, 10 years ago, In English
Codeforces Round #362 (Editorial) [Here](https://gitlab.com/amirmd76/cf-round-362/tree/master) is git repository to solutions of problems of this contest. ### Div.2 A You should check two cases for YES: 1. $x\ mod\ s = t\ mod\ s$ and $t \leq x$ 2. $x\ mod\ s = (t + 1)\ mod\ s$ and $t+1 < x$ ![ ](http://espresso.codeforces.com/72731d179aee0e03fb8a446ab4bb2d2c333953b9.png) Time Complexity: $\mathcal O(1)$ [Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/2A) ### Div.2 B Nothing special, right? just find the position of letters `.` and `e` with string searching methods (like `.find`) and do the rest. ![ ](http://espresso.codeforces.com/67436d52032041dc54647c27e506f956e344f5cb.png) Time Complexity: $\mathcal O(n)$ [Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/2B) ### A Do what problem wants from you. The only thing is to find the path between the two vertices (or LCA) in the tree. You can do this in $\mathcal O(lg(n))$ since the height of the tree is...
[Codes](https://gitlab.com/amirmd76/cf-round-362/tree/master/B)

Full text and comments »

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

110.
By gelastropod, history, 8 days ago, In English
Interesting property of trees _This blog is coauthored by [user:gohchingjayk,2026-11-15]._ Hello Codeforces! In this blog, we will first introduce this property, and then use it to improve the solution to [problem:2260F]! =D ### What is the property? <p><b>Theorem 1.</b> <i>Suppose we have a set $S$ which is a subset of the vertices on a rooted tree. Now, let $T = \lbrace \operatorname{LCA}(u, v) \mid u, v \in S \rbrace$. We claim that $|T \setminus S| \le |S| - 1$.</i></p> <p><i>Proof.</i> Consider the Eulerian Tour of the tree. Let $pre_u$ be the first visit of node $u$ in the Eulerian Tour. It is known that $\operatorname{LCA}(u, v)$ is the node of the minimum depth between $pre_u$ and $pre_v$ (inclusive). </p> Now, consider 2 nodes, $u, v \in S$. Suppose there exists node $x \in S$ such that $pre_u < pre_x < pre_v$. Observe that the node of minimum depth between $pre_u$ and $pre_v$ is either $\operatorname{LCA}(u, x)$ or $\operatorname{LCA}(x, v)$. There are exactly $|S| - 1$ pairs $u, v \i...
### What is the property? <b>Theorem 1.b> Suppose we have a set $S$ which is a subset of , ]! =D ### What is the property? <b>Theorem 1.b> Suppose we have a set $S$ which is a subset

Full text and comments »

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

111.
By Nakagawa.Kanon, history, 3 months ago, In English
IOI 2026 day 1 — My solutions for them ![ ](/predownloaded/77/c3/77c355894f49137e2eda44b44cc2e53a9fd7371e.png) Since there is not much discussion going on I decided to make a post about my solution for the problem, be aware that I will go straight to the full point solution and won't discuss the partial score to save time for you. I'm quite busy lately so I don't have enough time to implement the code and submit to the online judge. Please give your opinion with your comments **P1** Putting ball with a value in the leaves, it will ascend to the root as much as possible and only stop when another ball blocking them, then harvest from them the dfs order of the vertices based on the value of the ball on each vertex, then discard all the balls and begin anew. There is a limit on how many different value you can use (B) and number of them you harvest (K) that seems quite low compared to number of vertices (N ~ 1000) and leaves (M ~ 200) (B + K <= 44) An unga bunga experiment you will urge to try is simply to c...
We can have the structure of full tree like this but it will cost B + K = M + 1 = 201 > 44

Full text and comments »

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

112.
By henotrix, 15 months ago, In English
Codeforces Round 1045 (Div. 2) Editorial Unfortunately, the round turns out to be very unbalanced :( I'm deeply sorry about this issue. I hope you still enjoy the problems. <spoiler summary="Rate the contest! (definitely not copied from past contests)"> <spoiler summary="Quality"> * Excellent contest * Good contest * Average contest * Bad contest * Horrible contest </spoiler> <spoiler summary="Difficulty"> * Trivial contest * Easy contest * Average contest * Hard contest * Impossible contest </spoiler> </spoiler> [problem:2134A] <spoiler summary="Hint 1"> Check the parity of numbers $a$, $b$, and $n$. </spoiler> <spoiler summary="Solution"> Let us first consider the $b$ blue cells. Since all $b$ cells appear in the final painting, for the coloring to be symmetric, they must be placed at the middle of the grid...
perform the operation with $a$ as the parent of $u$ (in the rooted tree), $b = u$, and $c = v$. One can

Full text and comments »

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

113.
By Noble_Mushtak, history, 4 years ago, In English
Every Technique and Algorithm I Used to Become Grandmaster Hi everyone, I became grandmaster today so I decided to go down memory lane and review every problem I have ever done in a CodeForces contest to look back and see every technique and algorithm I had to use to become a grandmaster. I am not sure how useful this is, I mostly think it's fun to look at all the old solutions I wrote and how different it was from how I write code now. The main takeaway is that, as many people have said before, you don't need to know or memorize a bunch of advanced algorithms to become grandmaster. As you will see, there are many problems where I just used "ad hoc reasoning," meaning there's not a standard technique I used to solve the problem and you just need to make some clever mathematical observations to solve the problem. Also, there are many popular algorithms that I have never needed in a CodeForces contest despite being a grandmaster: - Sparse tables, Fenwick trees, and segment trees - String algos, like rolling hashes, Knuth-Morris-Pratt, suffix...
- [Problem B](https://codeforces.me/contest/1746/submission/176319980): Greedy with stacks, - [Problem B](https://codeforces.me/contest/1764/submission/182656701): Ad hoc reasoning with, grids - [Problem B](https://codeforces.me/contest/1534/submission/119348809): Ad hoc reasoning and, number theory - [Problem B ](https://codeforces.me/contest/1633/submission/144665541): Greedy, tree sets - [Problem B ](https://codeforces.me/contest/1770/submission/187259308): Ad hoc reasoning

Full text and comments »

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

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

Full text and comments »

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

115.
By Errichto, 10 years ago, In English
Codeforces Round #356 — Editorial # [problem:680A] Iterate over all pairs and triples of numbers, and for each of them check if all two/three numbers are equal. If yes then consider the sum of remaining numbers as the answer (the final answer will be the minimum of considered sums). Below you can see two ways to implement the solution. <spoiler summary="code1"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int t[5]; int s = 0; for(int i = 0; i < 5; ++i) { scanf("%d", &t[i]); s += t[i]; } int best = s; // discard 2 cards for(int a = 0; a < 5; ++a) for(int b = a + 1; b < 5; ++b) if(t[a] == t[b]) best = min(best, s - 2 * t[a]); // or discard 3 cards for(int a = 0; a < 5; ++a) for(int b = a + 1; b < 5; ++b) for(int c = b + 1; c < 5; ++c) if(t[a] == t[b] && t[a] == t[c]) best = min(best, s - 3 * t[a]); printf("%d\n", best); return 0; } ~~~~~ </spoiler> <spoiler summary=...
that if $t[i] \ne t[i+1]$ then the $i$-th value is correctly represented in the tree. Otherwise, it

Full text and comments »

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

116.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 133 English Solutions Since AtCoder often doesn't release English editorials to their beginner contests, I thought I'd write up my solutions. Feel free to add a comment if anything was unclear! A &mdash; T or T ------------------ Our alternatives here are sending all $N$ people on the train, for a total of $N \cdot A$ yen, or using the taxi, for a total of $B$ yen. We should thus print the minimum of these two values. Code: https://atcoder.jp/contests/abc133/submissions/6265526 B &mdash; Good Distance ------------------ We reword the problem slightly: for how many points $y$ and $z$ is $\sum_{k=1}^D (y_i-z_i)^2$ a perfect square? Given the small input constraints, we know that this sum is going to be at most $10 \cdot (20-20)^2 = 16000$. Hence, we can simply compute a list of all perfect squares less than $16000$ and iterate over all $\dbinom{N}{2}$ pairs of points. For each pair of points, we compute the summation and check if it is equal to any of our squares. If so, we increment th...
want to answer queries. Note that within a tree, the distance between A and B, if these two nodes have

Full text and comments »

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

117.
By bicsi, history, 3 weeks ago, In English
Optimal Incremental MST in 20 lines of code Hello Codeforces! Some of you might know `BottleneckTree.h` from [my KACTL fork](https://github.com/bicsi/kactl/blob/master/content/graph/BottleneckTree.h) (although it's a little obscure for an ICPC notebook; oh well). [user:freak93,2026-11-05] and I wrote it in 2021. The header says the complexity is "probably $O(\log n)$ amortized". It all started from a 2020 solution by [user:RestingRajarshi,2026-11-05] (more on that at the end). After about 6 years of on-and-off thinking about it, and with the help of Claude, we finally have an answer: it's not :). There are inputs where it takes $\Omega(\sqrt n)$ per operation. The good news is that a small change in the main loop fixes it, and this time we have a proof. We wrote a paper about it: [Incremental Minimum Spanning Trees on a Napkin](https://arxiv.org/abs/2611.05713). I think the structure is super elegant and short enough to be useful in contests, so I'm writing a blog about it. Prerequisites: none, really. It helps to know ...
cost on a path from $x$ to $y$. The usual way to do this is with a link-cut tree. That's $O(\log n

Full text and comments »

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

118.
By zscoder, history, 10 years ago, In English
[Tutorial] Slope Trick Hi everyone! Following my [last article](http://codeforces.me/blog/entry/47764), today I'm writing about a not-so-common trick that has nevertheless appeared in some problems before and might be helpful to you. I'm not sure if this trick has been given a name yet so I'd refer to it as "Slope Trick" here. Disclaimer : It would be helpful to have a pen and paper with you to sketch the graphs so that you can visualize these claims easier. Example Problem 1 : [problem:713C] This solution originated from [user:koosaga,2016-10-16]'s comment in the editorial post [here](http://codeforces.me/blog/entry/47094?#comment-315161). The solution below will solve this problem in $O(n\log n)$, wheareas the intended solution is $O(n^2)$. So, the first step is to get rid of the strictly increasing condition. To do so, we apply `a[i] -= i` for all $i$ and thus we just have to find the minimum number of moves to change it to a non-decreasing sequence. Define $f_{i}(x)$ as the minimum n...
$a$ of this node as the sum of all $a$s of its children, and similarly for $b $. Also, we combine all

Full text and comments »

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

119.
By awoo, history, 14 months ago, translation, In English
Educational Codeforces Round 182 Editorial [problem:2144A] Idea: [user:BledDest,2025-09-16] <spoiler summary="Tutorial"> [tutorial:2144A] </spoiler> <spoiler summary="Solution (BledDest)"> ~~~~~ t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) if sum(a) % 3 == 0: print("1 2") else: print("0 0") ~~~~~ </spoiler> [problem:2144B] Idea: [user:BledDest,2025-09-16] <spoiler summary="Tutorial"> [tutorial:2144B] </spoiler> <spoiler summary="Solution (BledDest)"> ~~~~~ #include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> p(n); vector<int> pos0; vector<int> used(n); for(int i = 0; i < n; i++) { cin >> p[i]; --p[i]; if(p[i] == -1) pos0.push_back(i); else used[p[i]] = 1; } if(pos0.size() == 1) { int unused = 0; for(int i = 0; i < n; i++) if(used[i] == 0...
vector calc(const vector& a, const vector& b) { int n = a.size(); int m

Full text and comments »

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

120.
By dragonslayerintraining, history, 7 years ago, In English
Dynamic convex hull implementation I finally figured out a nice way to implement dynamic convex hull with a reasonable constant factor! I expect this will be "well known in China" though. Consider the problem of finding [nested convex hulls](https://en.wikipedia.org/wiki/Convex_layers) in $O(n\log^2{n})$. The simplest way I know of is to make a convex hull data structure that supports point deletions, which is what I do here. It should be possible to extend this implementation to handle insertions as well. This implementation is based on this [paper](https://www.sciencedirect.com/science/article/pii/002200008190012X) by Overmars and van Leeuwen that describes a data structure for online fully dynamic convex hull in $O(\log^2{n})$ per operation. Directly implementing that is complicated and has a bad constant factor, so we'll do it a bit differently using ideas from [user:FizzyDavid,2020-04-13]'s [solution](https://codeforces.me/blog/entry/72611?#comment-569105) to [1270H](https://codeforces.me/contest/1270/probl...
We have two segment tree nodes $p$ and $q$ that we want to find the bridge between. Let $a$ and $b

Full text and comments »

121.
By ekzhang, history, 6 years ago, In English
[Tutorial] Kinetic Tournament (Used in FBHC Round 2) Background ------------------ During Facebook Hacker Cup Round 2 today, Problem D caught my attention. It reminded me of a particular data structure called a **kinetic tournament**, which is not very well known in this community. However, it offers an extremely clean and slick solution to the problem, in my opinion. I first learned about this data structure from [user:dragonslayerintraining,2020-08-30], who described a variant of it in this [Codeforces blog comment](https://codeforces.me/blog/entry/68534#comment-530381). Since the data structure is so interesting, I feel like it deserves a longer explanation, some template code, and more examples. That's why I am writing this blog post. Kinetic Tournaments ------------------ Briefly, the functionality of the data structure is a mix between a line container, i.e., "convex hull trick", and a segment tree. Suppose that you have an array containing pairs of nonnegative integers, $A[i]$ and $B[i]$. You also have a global...
is a mix between a line container, i.e., "convex hull trick", and a segment tree. Suppose that, lines, $A$ and $B$, such that $A(x_1) < B(x_1)$, $A(x_2) > B(x_2)$, and $A(x_3) <B(x_3)$, where

Full text and comments »

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

122.
By Ermiooo159, 13 months ago, In English
GPT Can Code, but Can It Panic at Pretest 3? <h3>The Setup</h3> You: “Solve this problem.” GPT: “writes 200 lines of perfectly formatted <code>C++17</code> with descriptive variable names and a poetic docstring.” You: “It’s WA on test 3.” GPT: “Have you tried using long long?” --- <h3>How GPT Thinks It Codes:</h3> > "I analyzed 10^8 lines of ICPC gold-medal solutions and learned optimal dynamic programming patterns." <h3>How GPT Actually Codes:</h3> > "Let's just sort the array and pray." --- <h3>Debugging with GPT</h3> You: “It’s TLE.” GPT: “Hmm, maybe use <code>unordered_map</code>.” You: “Still TLE.” GPT: “Then switch to <code>map</code> for more structure.” You: “It’s slower.” GPT: “At least it’s elegant.” --- <h3>GPT’s Logic in Action</h3> Test 1: Works. Test 2: Works. Test 3: Segmentation fault. GPT: “That’s impossible. Theoretically flawless.” Then it proudly explains: > "Maybe the problem statement is wrong." > — confidently, like a true C...
, and <b>multiset for emotional comfortb>. It has used segment tree exactly

Full text and comments »

Tags ai, meme, fun
  • Vote: I like it
  • +106
  • Vote: I do not like it

123.
By neal, 8 years ago, In English
Blowing up unordered_map, and how to stop getting hacked on it C++ has always had the convenient data structures `std::set` and `std::map`, which are tree data structures whose operations take $O(\log n)$ time. With C++11, we finally received a hash set and hash map in `std::unordered_set` and `std::unordered_map`. Unfortunately, I've seen a lot of people on Codeforces get hacked or fail system tests when using these. In this post I'll explain how it's possible to break these data structures and what you can do in order to continue using your favorite hash maps without worrying about being hacked [cut] . So how are they hackable? We always assume hash maps are $O(1)$ per operation (insert, erase, access, etc.). But this depends on a key assumption, which is that each item _only runs into $O(1)$ collisions on average_. If our input data is completely random, this is a reasonable assumption. But this is no longer a safe bet when the input isn't random, especially so if someone is adversarially designing inputs to our code (a.k.a. hacking ph...
C++ has always had the convenient data structures `std::set` and `std::map`, which aretree data

Full text and comments »

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

124.
By Edvard, history, 11 years ago, translation, In English
Editorial of Educational Codeforces Round 10 ### [problem:652A] The problem was suggested by [user:unprost,2016-03-26]. Let's consider three cases. 1. $h_1+8a \ge h_2$ &mdash; in this case the caterpillar will get the apple on the same day, so the answer is $0$. 2. The first condition is false and $a \le b$ &mdash; in this case the caterpillar will never get the apple, because it can't do that on the first day and after each night it will be lower than one day before. 3. If the first two conditions are false easy to see that the answer equals to $\lceil \frac{h_2-h_1-8a}{12(a-b)} \rceil$. <spoiler summary="C++ solution"> ~~~~~ int h1, h2; int a, b; bool read() { return !!(cin >> h1 >> h2 >> a >> b); } void solve() { if (h1 + 8 * a >= h2) puts("0"); else if (a > b) { int num = h2 - h1 - 8 * a, den = 12 * (a - b); cout << (num + den - 1) / den << endl; } else puts("-1"); } ~~~~~ </spoiler> Also this problem can be so...
$ and $B$. Statement: the answer is *YES* if and only if on the path in the tree from the vertex $A$ to

Full text and comments »

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

125.
By snowysecret, 5 years ago, In English
Editorial for Codeforces Round #761 (Div. 2) Thanks for participating, hope you enjoyed the problems! Implementations for the problems are chosen randomly among testers, and I made some changes to their codes (for example, deleted meaningless comment lines). Please do not hesitate to provide feedback in the comments, so I can improve in setting problems next time. **UPD**: Sorry but there is a checker bug in problem E. All submissions of problem E will be rejudged soon. **UPD2:** Rejudge done, the round remains rated. <spoiler summary="Statistics"> Number of FST for rated participants: - Problem A: $29$ - Problem B: $90$ - Problem C: $12$ - Problem D1: $4$ - Problem D2: $0$ - Problem E: $6$ Number of AK: $22$ Number of clarifications: $85$ </spoiler> [problem:1617A] <spoiler summary="Hint"> When is the lexicographically smallest permutation of $S$ (i.e. the sorted string) not the answer? </spoiler> <spoiler summary="Solution"> If there are no occurrences of `a`, `b` or `c` in $S$, ...
summary="Statistics"> Number of FST for rated participants: - Problem A: $29$ - ProblemB: $90

Full text and comments »

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

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

Full text and comments »

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

127.
By tokitsukaze, 5 years ago, In English
Codeforces Round #789 Editorial [problem:1678A] Idea: [user:tokitsukaze,2022-05-08] <br /> Prepare: [user:tokitsukaze,2022-05-08] <spoiler summary="Tutorial"> We observe that when there is $0$ in the sequence, it is optimal to choose $0$ and any number other than $0$ for each operation. Therefore, when there is $0$ in the sequence, let $cnt$ be the number of $0$s, the answer is $n - cnt$. Otherwise, when $0$ does not exist in the sequence, there are two situations: 1. When there exist two equal numbers in the sequence, we can perform the operation $1$ time to convert it into the situation of having $0$ in the sequence. So the answer must be $n$. 2. When all numbers in the sequence are distinct, we can perform the operation $2$ times to convert it into the situation of having $0$ in the sequence. So the answer must be $n + 1$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main(){ int t; scanf("%i",&t); while(t--){ int n; scan...
node in the segment tree has to maintain $a*R+b$,which like a linear function.

Full text and comments »

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

128.
By tridipta2806, history, 8 months ago, In English
Insomnia'26 Editorial ####[Problem A : Ancient Trees](https://codeforces.me/gym/680528/problem/A) Problem Idea: [user:shorya1835,2026-03-23], Problem Preparation: [user:aastik231205,2026-03-23] <spoiler summary="Hint 1"> You are allowed to use intermediate vertices in your sequence. Does it ever actually help? For any three vertices $a$, $b$, $c$, what is the relationship between $c(a,b) + c(b,c)$ and $c(a,c)$? Recall that for non-negative integers, $x + y \geq x \oplus y$. </spoiler> <spoiler summary="Answer for Hint 1"> Since, $c(a,b) + c(b,c) \geq c(a,b) \oplus c(b,c)$, Splitting the path doesn't minimize the distance at all. Hence $d(u,v) = c(u,v)$ always. </spoiler> <spoiler summary="Hint 2"> Since $d(u,v) = c(u,v)$ always, we can maintain a running mask $M$ (XOR of all Type 1 updates so far). A path with $\ell$ edges has its XOR-distance changed only if $\ell$ is odd, flipping their XOR-distance by $M$, depending only on the running XOR of Type 1 queries so far. Can you precomput...
this tree the <b>abs-MSTb>., Because our initial tree is the <b>Maximum Absolute Spanning Treeb>, every non- tree edge $n_i

Full text and comments »

Tutorial of Insomnia-26
  • Vote: I like it
  • +113
  • Vote: I do not like it

129.
By __baozii__, 10 months ago, In English
Codeforces Round 1077 (Div. 1, Div. 2) Editorial We hope you enjoyed the problems! <spoiler summary="Rate the contest!"> <spoiler summary="Quality"> - Excellent contest - Good contest - Average contest - Bad contest - Horrible contest </spoiler> <spoiler summary="Difficulty"> - Trivial contest - Easy contest - Average contest - Hard contest - Impossible contest </spoiler> </spoiler> [problem:2188A] - Idea: [user:__baozii__,2026-01-29], [user:Tobo,2026-01-29] - Solution: [user:__baozii__,2026-01-29] - Editorial: [user:__baozii__,2026-01-29] <spoiler summary="Solution"> For $|p_{n-1}-p_n|$ to be divisible by $n-1$, either $p_{n-1}=1$ and $p_n=n$, or $p_{n-1}=n$ and $p_n=1$. Either way, we can construct $p$ backwards. For $i$ from $n-2$ to $1$, there will only by one possible choice for $p_i$, where $...
Construct the optimal tree by following the approach used in F1. Two

Full text and comments »

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

130.
By yeputons, 16 years ago, translation, In English
Codeforces Beta Round #54 (Div.2) - разбор A-D <div align="center"><b>Problem A. Chat room<br></b><div align="left">Solution is greedy algorithm. The first thing we do is find in our string the first letter 'h'. Then we find letter 'e' which is righter that found 'h'. If we find the whole word 'hello' in such way, obliviously, answer is YES.<br>Now let's prove that if answer exists, we find it. Let see on position of the 'h' in right answer. If we move it to the first 'h' in our string, nothing changes. But now we can say that our greedy algorithm correctly Now let's do such with the second letter, and so on.<br>We have greedy algorithm with work time O(n), where n - length of the input.<br></div><br><div align="left"><div align="center"><b>Problem B. Coins<br></b><div align="left">This problem also have greedy solution: we run down all number from 2 and greater and while denomination of the last added to answer coin is divisible by current number, we divide and increase answer.<br>You can prove correctness, if you take a look at p...
<b>Problem A. Chat room b>Solution is greedy algorithm, <b>Problem C. Trees.b> The first thing we notice

Full text and comments »

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

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

Full text and comments »

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

132.
By MinakoKojima, 14 years ago, In English
Codeforces Round #172 Editorial Overview ... ================== In DIV 1, there are 3 normal tasks accompanied with 2 challenge tasks. About 40 competitors solve first three tasks during the contest and I believe there will be more if we extended the duration a little bit. Task D is a standard data-structure problem hidden behind a classical maximum cost flow model. This kind of problem are usually trick-less, but hard to implement especially under the pressure. Because of this, it becomes tonight's draw-breaker. Task E is a extended version on a classical DP && Math problem. There are many solutions to the original problem, one is giving a global view under the state transition, and using a data structure to handle it carefully. However, this one is even more harder, few people have ever tried it except [user:Jacob,2013-03-11]. (Although is wrong.) As a seasoned competitor, [user:Petr,2013-03-10] took the C-B-A order which proved to be the best choice through out the night. And after quickly solved C and...
://codeforces.ru/problemset/problem/280/B) - [Problem C. Game on Tree ](http://codeforces.me/problemset/problem

Full text and comments »

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

133.
By Malomalomalomalo, history, 9 years ago, In English
Understanding Fenwick Trees / Binary Indexed Trees Im writing this both to help others and test myself so I will try to explain everything at a basic level. Any feedback is appreciated. A Fenwick Tree (a.k.a. Binary Indexed Tree, or BIT) is a fairly common data structure. BITs are used to efficiently answer certain types of range queries, on ranges from a root to some distant node. They also allow quick updates on individual data points. An example of a range query would be this: "What is the sum of the numbers indexed from [1,x]?" An example of an update would be this: "Increase the number indexed by x by v." A BIT can perform both of these operations in O(log N) time, and takes O(N) memory. (least significant bit will be abbreviated to LSB and in this post means the bit with the first one in the binary representation. Length of an interval ending at index x is shown by len(x)) <h2>So how do BITs work?</h2> BITs take advantage of the fact that ranges can be broken down into other ranges, and combined quickly. Addi...
level. Any feedback is appreciated. A Fenwick Tree (a.k.a. Binary Indexed Tree , or BIT) is a, Assume intervals ending at a and b with len(a)=len(b) intersect, and without loss of generality let, Basically: b = [B]10...00 and a=[A]10...00 with [B]>[A]. b-len(b) = [B]00...00 which is still, Thats it! Note that you can query for ranges [a,b] by performing query(b )-query(a-1). The same code

Full text and comments »

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

134.
By AlexSkidanov, 12 years ago, In English
MemSQL Start[c]UP 2.0 Round 1 and 2 Editorials Round1 ====== Problem B --------- The critical observation in this problem is that the points will be at the corners or very close to the corners. After that one simple solution would be to generate a set of all the points that are within 4 cells from some corner, and consider all quadruplets of points from that set. Problem C --------- When the magician reveals the card, he has $1 \over k$ chance to reveal the same exact card that you have chosen. With the remaining ${k-1} \over k$ chance he will reveal some other card. Since all the cards in all $m$ decks are equally likely to be in the $n$ cards that he uses to perform the trick, he is equally likely to reveal any card among the $n \times m - 1$ cards (-1 for the card that you have chosen, which we assume he has not revealed). There are only $m - 1$ cards that can be revealed that have the same value as the card you chose but are not the card you chose. Thus, the resulting probability is ${1 \over k} + {{k-1} \over k} \time...
array, suffix tree or suffix automata. The easiest solution uses a compressed suffixtree. Build one

Full text and comments »

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

135.
By Abito, history, 3 years ago, In English
Merge Sort Tree (and similar stuff) Sometimes I encounter a type of range queries that I don't know how to do using segment tree, so I use a merge sort tree instead. It can answer queries in $O(log^2 n ) $. I decided to share this because it can be useful to many in contests. First, we know that a node in a segment tree stores the answer for a range of length $2^x$ for some $x$, but we can also store in it all the elements in the range sorted in a vector (using merge sort algo) or set or whatever. Here I am going to give a few examples how we can use this to our advantage. Problem 1: Static Count of Lesser Elements range queries. ------------------ We are given an array $a_1, a_2, a_3... a_n$ and an integer $q$. The $i$_th of the next $q$ lines has three integers $l_i , r_i , x_i$. The answer for this query is how many $a_j$ such that $l_i \le j \le r_i$ and $a_j < x$. <spoiler summary="Solution"> Let's create a merge sort tree where each node has a sorted vector containing all elements in the range of this node....
Merge Sort Tree (and similar stuff), Sometimes I encounter a type of range queries that I don't know how to do using segmenttree, so I, [CF — 816B](https://codeforces.me/problemset/problem/816/B)

Full text and comments »

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

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

Full text and comments »

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

137.
By chromate00, 4 years ago, In English
Sort-Fenwick: Fenwick Trees are More Powerful than I Thought Just today, I came up with this trick while solving a problem that (originally) required a merge-sort tree. While I knew that it could be solved by a merge-sort tree, I thought implementing it would be relatively tedious. This being said, I do not mean to say that I do not like the data structure, I think its concepts are very clever. However, I do like algorithms whose implementation is very elegant. For this reason, I prefer the fenwick tree over the segment tree on many problems. This was another case of me considering how a fenwick tree could replace the usual implementation. And just today the idea came to me, which turned into a method which could almost replace merge-sort trees. (Note that some people may have found this earlier than I did, and I think most people who did would have found this independently like I did too) ----- So, as a disclaimer before explaining the method, I should tell you that this method is not really better (time complexity-wise) than the merge-so...
$$a+b=N \Rightarrow O(a \log a) + O(b \log b) = O(N \log N)$$, $$a+b=N \Rightarrow \log a, \log b < \log N$$ $$O(a \log a) + O(b \log b) = O((a+b) \max (\log a, -sort tree. While I knew that it could be solved by a merge-sort tree, I thought implementing it would

Full text and comments »

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

138.
By Fype, 7 years ago, In English
Segment Tree Problems I gathered up a lot of Segment problems :) --> **upd1** : more segment :D **upd2** : now there is e-olymp problems. thanks to [user:dmkozyrev,2019-12-06]. codeforces : [Xenia and Bit Operations](http://codeforces.me/problemset/problem/339/D) [Knight Tournament](https://codeforces.me/contest/356/problem/A) [Bash and a Tough Math Puzzle](https://codeforces.me/problemset/problem/914/D) [Pashmak and Parmida's problem](https://codeforces.me/contest/459/problem/D) [Enemy is weak](https://codeforces.me/contest/61/problem/E) [Circular RMQ](https://codeforces.me/contest/52/problem/C) [REQ](https://codeforces.me/contest/594/problem/D) [Lucky Queries](https://codeforces.me/contest/145/problem/E) [XOR on Segment](http://codeforces.me/problemset/problem/242/E) [Sereja and Brackets](http://codeforces.me/problemset/problem/380/C) [Ant Colony](http://codeforces.me/problemset/problem/474/F) [Babaei and Birthday Cake](https://codeforces...
Segment Tree Problems, /E) [Pillars](https://codeforces.me/contest/474/problem/E) [On Changing Tree ](https, ://codeforces.com/contest/474/problem/E) [On Changing Tree ](https://codeforces.me/contest/396/problem/C

Full text and comments »

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

139.
By beyondpluto, history, 4 years ago, In English
Nitpy-TnP-week-05 -TREES(EDITORIAL) ### <a href="https://www.hackerrank.com/contests/nitpy-cse23-tp-05/challenges/binary-tree-array"> B. Binary-tree-array: </a> <spoiler summary="Tutorial"> <a href="https://www.hackerrank.com/contests/nitpy-cse23-tp-05/challenges/binary-tree-array"> B. Binary-tree-array: </a> ------------------------------------------------------------------------------------------------------------------------ Just convert the string into binary notation.<br> ie:L to 0 and R to 1.<br> let that value be b in decimal.<br> then the answer will be `2^n+b`. <br>where 2^n is the position of first node at height n, and b is distance between first node at height n and position of node having sequence of traversal(from root 1) as binary representation of b. <br>note: hidden node will be at height n. <br>Overall complexity: O(29*q) worst case.<br> </spoiler> <spoiler summary="code"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int h, q; cin >> h >> q; ...
### B <https://www.hackerrank.com/contests/nitpy-cse23-tp-05/challenges/binary-<B>tree</B>-array>, /challenges/binary-tree-array"> B. Binary-tree-array: ------------------------------------------------------------------------------------------------------------------------

Full text and comments »

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

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

Full text and comments »

141.
By MarioYC, 15 years ago, In English
Cartesian tree <p</p><div>Today I read about cartesian tree(treap) from e-maxx's page, since it is in russian I decided to translate some parts.</div><div><br /></div><div>Also here are some related links:</div><div><br /></div><div><a href="http://e-maxx.ru/algo/treap">http://e-maxx.ru/algo/treap</a></div><div><a href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.30.8602">http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.30.8602</a></div><div><a href="http://book.huihoo.com/pdf/cs-373-combinatorial-algorithms/notes/04-treaps.pdf">http://book.huihoo.com/pdf/cs-373-combinatorial-algorithms/notes/04-treaps.pdf</a></div><div><a href="http://infoarena.ro/treapuri">http://infoarena.ro/treapuri</a> (a different implementation)<br /></div><div><span><a href="http://habrahabr.ru/blogs/algorithm/101818/">http://habrahabr.ru/blogs/algorithm/101818/</a><br /></span><span><a href="http://habrahabr.ru/blogs/algorithm/102006/">http://habrahabr.ru/blogs/algorithm/102006/</a><br /></span><span><a href...
Cartesian tree, Today I read about cartesian tree(treap) from e-maxx's page, since it is in russian I, <b>Advantages:b>, <b>Notation:b>, <b>Operations:b>

Full text and comments »

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

142.
By brunomont, history, 6 years ago, In English
[Tutorial] A powerful representation of integer sets Hello, Codeforces! This blog is heavily inspired by [user:TLE,2020-10-22]'s blog [using merging segment tree to solve problems about sorted list](https://codeforces.me/blog/entry/49446). I don't know exactly how well known this data structure is, but I thought it would be nice to share it anyway, along with some more operations that are possible with it. What it can do ------------------ We want a data structure that we can think of a set/multiset of **non-negative integers**, or even as a sorted array. We want to support all of the following operations: 1. Create an empty structure; 2. Insert an element to the structure; 3. Remove an element from the structure; 4. Print the $k$'th smallest element (if we think of the structure as a sorted array $a$, we are asking for $a[k]$); 5. Print how many numbers less than $x$ there are in the set (similar to lower_bound in a std::vector); 6. Split the structure into two: one containing the $k$ smallest elements, and the other ...
$A$ $x$ maps to $u$ and in set $B$ $x$ maps to $v$, it can be made so that in the merged set $x

Full text and comments »

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

143.
By EbTech, history, 7 years ago, In English
Generalizing Segment Trees with Rust This blog post outlines the design of a very general data structure for associative range queries, in the Rust programming language. In the "real world", self-balancing binary search trees can be augmented to handle a variety of range queries. However, for contest problems, statically allocated variants are much easier to code and usually suffice. The contest community has come to know these data structures as _segment trees_. Here, I will generalize most of the segment trees that you can find in the wild into one polymorphic data structure, that can easily be copy-pasted during online competitions. I will call it an _ARQ tree_. ARQ is pronounced "arc", which has a similar meaning to "segment", but also stands for "Associative Range Query". It supports highly customizable range queries, the main requirement being that the aggregation operation must be _associative_. ### Associativity and Semigroups We begin with an array $a_0, a_1, a_2, \ldots, a_{n-1}$. Each $a_i$ belongs to...
formal notation: **Associative Law:** $+: S \times S \rightarrow S$ satisfies $a + (b + c) = (a, { match self { Some(ref a) => match other { Some(ref b, **Associative Law:** $+: S \times S \rightarrow S$ satisfies $a + (b + c) = (a + b) + c$ for all $a, **Distributive Law:** $f(a + b) = f(a) + f(b)$ for all $f \in F$, $a, b \in S$, /// Require for all a,b,c: op(a, op(b, c)) = op(op(a, b), c) fn op(a: &Self::S, b: &Self::S, In typical instances where computing $a + b$ or $f(a)$ take $O(1)$ time, we wish to support each, fn op(&a: &i64, &b: &i64) -> i64 { a.min(b) } fn identity() -> i64

Full text and comments »

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

144.
By eren__, 18 months ago, In English
Codeforces Round 1024 (Div. 1, Div. 2) Editorial Thank you for participating! We hope you enjoyed the problems and, most importantly, had fun! <br> ##[problem:2102A] <spoiler summary="Hints"> <spoiler summary="Hint 1">If you have the first $p$ elements, what happens to the rest?</spoiler> <spoiler summary="Hint 2">What happens if $n\%p\neq0$?</spoiler> <spoiler summary="Hint 3">How can the fact that we can also use negative numbers be useful?</spoiler> </spoiler> <spoiler summary="Solution"> The first thing to realize is that if the first $p$ elements of the array are determined, the rest will be unique ($a_i = a_{i-p}$ to hold the sum). If $p$ divides $n$, there will be $\frac{n}{p}$ blocks, each summing to $q$, so their total sum which is $q\cdot \frac{n}{p}$ should be equal to $m$. If not, the incomplete block that is created at the end can be used to cover any difference in sum, so it's always possible! </spoiler> <spoiler summary="Code (Python 3)">``` t = int(input()) for _ in range(t):...
result for each edge of the tree, considering it will be a special edge in some colourings. Call, Make the tree rooted from an arbitrary node. Define $dp_{v, i, a, b, j}$ as if you're in vertext $v

Full text and comments »

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

145.
By Konijntje, history, 11 years ago, In English
Splay tree and its implementation. I chose Splay tree as my Balanced Binary Search Tree if I have to implement it. There are few reasons. 1. It always give amortized O(lg n) time complexity. This is reason why I'm not using treap or skip list. But I think skip list is meaningful than only usage for BBST. 2. It is easy to remember. Unlike other balanced binary tree, such as Red-black tree or AVL tree or 2-3 tree, it has same logic for searching, finding and deleting. Also, Making node as root is straight-forward. I have implemented Red-black tree once with guidebook in IOI training camp. It took long. (maybe 2h?) But I implemented Splay tree with only 1h in my first implementation. I only saw wikipedia once to implement it just before I started to code. My code is following. Its major part is Splay and It is very simple! Anything other is same with just BST. Maybe implementation of Erase is easier than other BST. ~~~~~ #include<cstdio> #include<cstdlib> struct Node{ Node *l; Node *r; ...
Splay tree and its implementation., ; }; Node *root; void rightRotate(Node *P) { Node *T=P->l; Node *B=T->r; Node *D=P->p; if, I chose Splay tree as my Balanced Binary Search Tree if I have to implement it. There are few, P->p=T; P->l=B; } void leftRotate(Node *P) { Node *T=P->r; Node *B=T->l; Node *D=P->p, P->p=T; P->r=B; }

Full text and comments »

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

146.
By send_nodes, history, 9 years ago, In English
Codeforces Round #420 (Div. 2) Editorial First, I really need to apologize for the round. There was a serious problem in D that was even covered in the sample test, that the main solution did not handle correctly. I should have been much more careful with this problem and looked for these kind of cases. Unfortunately, it was a big enough issue that caused the round to be unrated. I know this upset a lot of people, but it's tricky to find a solution to this kind of problem after the problem has happened. I still hope the problems were good quality. If you learned something new from the round, or from this editorial, then the round was worth it. I would advise to solve the problems you couldn't solve during the contest, so you can take away something from the round. **If you want any further clarification on a problem, please ask in comments!** [821A &mdash; Okabe and Future Gadget Laboratory](http://codeforces.me/problemset/problem/821/A) We can simulate exactly what's described in the statement: loop over all c...
[821B — Okabe and Banana Trees](http://codeforces.me/problemset/problem/821/B)

Full text and comments »

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

147.
By smax, 4 years ago, In English
[Tutorial] Fully Dynamic Trees Supporting Path/Subtree Aggregates and Lazy Path/Subtree Updates Hey everyone! Usually when I post stuff on CF I just drop an external link to my blog, but this time I would like to also paste the same content natively on CF to see if it leads to more engagement. You can read the exact same article on my blog [here](https://mzhang2021.github.io/cp-blog/ds5/). Also, special thanks to [user:alien_lover,2022-06-10] and [user:gabrielwu,2022-06-10] for proofreading. --- ## Motivation We will solve **[this problem](https://dmoj.ca/problem/ds5)**. ## Prologue The original name of this problem is [SONE1](https://darkbzoj.cc/problem/3153), originating from the fiery depths of Chinese OI. Amazingly, the Chinese have figured out how to augment the link/cut tree to solve this problem (ref [1](https://www.cnblogs.com/clrs97/p/4403244.html), [2](https://blog.csdn.net/iamzky/article/details/43494481)). Maintaining subtree aggregates with a LCT isn't difficult, and there's a well-known [Codeforces article](https://codeforces.me/blog/entry/67637) ...
an effect (e.g. applying an affine function $x := ax + b$ to a range), then this breaks down., link/cut tree to solve this problem (ref [1](https://www.cnblogs.com/clrs97/p/4403244.html), [2

Full text and comments »

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

148.
By Ripatti, 16 years ago, translation, In English
Solutions for Codeforces Beta Round #68 <b>A.</b> You can do exactly what is written in a statement. Only one pitfall in this problem is that room leader may have number of points less than zero.<br>[cut]<br><b>B.</b> In this problem you may find optimal strategy for a stowaway. Next you may just simulate a game.<br><br>Optimal strategy for the stowaway is placing from a conrtoller as far as possible. In the moving minute the stowaway should go into wagon that farther to the controller. In the idle minute stowaway should go into wagon in which the controller enter as later as possible. It is always the first or the last wagon of train.<br><br>You may also wrote some dynamic programming solution or a solution fot classic game.<br><br><b>C.</b> Define a trajectory as a line that center of a billiard ball is drawing while it is moving. At begin of moving, the ball chose one from no more than two trajectoties and is moving <span id="result_box" class="short_text" lang="en"><span title="Нажмите, чтобы увидеть альтернативный перев...
<b>Online solution.b> There can be written some balanced or decart tree.

Full text and comments »

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

149.
By brunomont, 6 years ago, In English
[Tutorial] Range minimum query in O(1) with linear time construction <spoiler summary="TL; DR"> Build a sparse table over blocks of size $b = 30 \geq \log{n}$. Now we only need to answer queries of size smaller than $b$. For that, simulate a minqueue of size $b$ over the array, and store a mask of the elements that are currently active in the minqueue. Let $\text{mask[r]}$ be the minqueue mask when the simulation is at position $\text{r}$. Now we can see that, if $r-l+1 \leq b$, then `query(l, r) = r - most_significant_set_bit(mask[r] & ((1<<(r-l+1))-1))`. ~~~~~ template<typename T> struct rmq { vector<T> v; int n; static const int b = 30; vector<int> mask, t; int op(int x, int y) { return v[x] < v[y] ? x : y; } int msb(int x) { return __builtin_clz(1)-__builtin_clz(x); } int small(int r, int sz = b) { return r-msb(mask[r]&((1<<sz)-1)); } rmq(const vector<T>& v_) : v(v_), n(v.size()), mask(n), t(n) { for (int i = 0, at = 0; i < n; mask[i++] = at |= 1) { at = (at<<1)&((1<<b)-1); while (at and op(i, i-msb(at&-at)) == i) at ...
Build a sparse table over blocks of size $b = 30 \geq \log{n}$. Now

Full text and comments »

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

150.
By prabowo, history, 16 months ago, In English
How I understand Floor Sum Hi everyone, Today we are going to compute $$\begin{gather}\sum_{x=0}^{n-1} \left\lfloor \frac{ax + b}{m} \right\rfloor\end{gather}$$ in $\mathcal{O}(\log(m))$. This topic has been discussed elsewhere, but I find the proofs that are currently available online to be too artificial for me. So here is my attempt to describe how I understand this topic using illustrations, albeit in a less rigorous manner. [cut] <br /> ## 1. Floor Sum Let us define $$\begin{gather}S(a, b, m, n) = \sum_{x=0}^{n-1} \left\lfloor \frac{ax + b}{m} \right\rfloor\end{gather}$$ Here, we are going to assume that $a < m$ and $b < m$. If they are not, it is not hard to reduce them into $a \rightarrow a \bmod m$ and $b \rightarrow b \bmod m$, which I am not going to discuss here. The sum above is equivalent to counting the number of lattice points below the curve $y = \frac{ax + b}{m}$ bounded by $0 \le x < n$. As an instance, the sum for $(a, b, m, n) = (3, 2, 5, 10)$ can be illustra...
\frac{ax + b}{m} \right\rfloor\end{gather}$$ in $\mathcal{O}(\log(m))$. This topic has been

Full text and comments »

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

151.
By willy108, history, 4 years ago, In English
Teamscode Spring 2023 Editorial This is the editorial for a recent contest [Teamscode](https://www.teamscode.org/). The problems are open for upsolving on [this gym](https://codeforces.me/gym/104287). Problems were prepared by [user:oursaco,2023-04-06], [user:dutin,2023-04-06], [user:thehunterjames,2023-04-06], [user:Bossologist,2023-04-06], [user:Esomer,2023-04-06], and me. ### [A. What do you do when the contest starts? Are you busy? Will you solve Bingo?](https://codeforces.me/gym/104287/problem/A) <spoiler summary = "Editorial"> <spoiler summary = "Are you busy?"> 1. WorldEnd/SukaSuka 2. Bocchi the Rock </spoiler> <spoiler summary = "No Sweep"> 1. Thomas </spoiler> <spoiler summary = "Multiplication Table"> 1. Lycoris Recoil </spoiler> <spoiler summary = "Greatest Common Multiple"> 1. Bokuben </spoiler> <spoiler summary = "A Certain Scientific Tree Problem"> 1. A Certain Scientific Railgun </spoiler> <spoiler summary = "Two and Three"> 1. Quintessential Quintluplets...
Now, if our tree is rooted at $x$, we can effectively split the tree over every edge attached to $x

Full text and comments »

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

152.
By Geothermal, history, 7 years ago, In English
AtCoder Beginner Contest 153 English Solutions #A &mdash; Serval vs Monster Unpacking the problem, we need to find the least multiple of $A$ that is greater than $H$. This is equal to $H$ divided by $A$, rounded up, or $\lceil \frac{H}{A} \rceil$. Using the integer division provided by most programming languages, we can compute this as $\frac{H + A - 1}{A}$, rounded down. (This is correct because when $H$ is equal to $0$ mod $A$, the $A-1$ component will be discarded, but otherwise, adding $A-1$ will be enough to push $H$ to the next multiple of $A$, effectively adding $1$ to the result similarly to rounding up.) Runtime: $O(1)$. [Click here for my submission.](https://atcoder.jp/contests/abc153/submissions/9730029) --- #B &mdash; Common Raccoon vs Monster Given that we can't use the same move twice, our best option is to just use all the moves once, so the amount of damage we can deal is the sum of $A_i$ over all $i$. We can compute this sum and then compare it to $H$, printing Yes if the sum is at least $H$ an...
, we update the segment tree by subtracting $AB$ over the range $[i, j]$ and add $B$ to our answer

Full text and comments »

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

153.
By Zlobober, 12 years ago, translation, In English
VK Cup Round 1 (+ online mirror) editorial Problemsets slightly differ in main round and in an online mirror, in editorial problems follow in an order of the main round. [problem:524A] ============== This problem didn't appear in an online mirror. Its editorial will be left as an exercise in Russian language for those who are curious what it is about =) [problem:524B] ============== In an original version there was no constraint that no more than n / 2 friends should lie. This version can be solved pretty easy. Iterate over all possible values of $H$. For a fixed $H$ we have to minimize total width of all rectangles on the photo. So, for each rectangle we need to choose in which orientation it fits into photo having the minimum possible width. [problem:529B] ============== In an online mirror version the problem was slightly harder. Let's call people with $w \leq h$ \textit{high}, and remaining people \textit{wide}. Let's fix photo height $H$. Let's consider several following cases: * If a high person fi...
standing in the right side of a rectangle located in rows from $a$ to $b$ with the left side in a

Full text and comments »

Tutorial of VK Cup 2015 - Round 1
  • Vote: I like it
  • +90
  • Vote: I do not like it

154.
By roosephu, 12 years ago, In English
ZeptoLab Code Rush 2015 — Editorial Hello everyone, I hope you can enjoy this special round for Zepto Lab. Here are the solutions of this round. # [A. King of Thieves](http://codeforces.me/contest/526/problem/A) This task is easy for many of you. We can just iterate over all possible $i_1$ and $i_2 - i_1$, then we can compute $i_{3, \dots, 5}$, and check whether this subsequence satisfies the condition mentioned in the task. # [B. Om Nom and Dark Park](http://codeforces.me/contest/526/problem/B) We use greedy and recursion to solve this task. For each tree rooted at $v$, we adjust its two subtrees at first, using recursion. Then we increase one edge from $v$'s child to $v$. # [C. Om Nom and Candies](http://codeforces.me/contest/526/problem/C) If there is a kind of candy which weighs greater than $ \sqrt{C} $, then we can iterate over the number of it to buy, which is less than $ \sqrt{C} $. Otherwise, without loss of generality we suppose $\frac{H_b}{W_b} < \frac{H_r}{W_r} $. If the number of the...
. Assuming the longest path in the tree is $ (a, b) $ , we could find that whatever the query is, $ S $ will

Full text and comments »

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

155.
By YuukaKazami, 14 years ago, In English
Codeforces Round #146 Tutorial ### [problem:236A] It is a very simple problem, just count how many distinct chars in the input and output the correct answer. ### [problem:236B] First of all, we can make a table of size a*b*c to store every number's d value. Then we can just brute force through every tripe to calculate the answer. ### [problem:235A] It is a simple problem, but many competitors used some wrong guesses and failed. First of all, we should check if n is at most 3 and then we can simply output 1,2,6. Now there are two cases: When n is odd, the answer is obviously n(n-1)(n-2). When n is even, we can still get at least (n-1)(n-2)(n-3), so these three numbers in the optimal answer would not be very small compared to n. So we can just iterate every 3 number triple in [n-50,n] and update the answer. ### [problem:235B] Let us take a deep look at how this score is calculated. For an $n$ long 'O' block, it contributes $n^2$ to the answer. Let us reformat this problem a bit and consider ...
First let us assume there's a connected sub-graph of the tree containing both A andB, if the sub

Full text and comments »

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

156.
By cry, 2 years ago, In English
Codeforces Round 979 Editorial Below is a timeline of the changes made to the round from start to finish. I hope this can depict what setting a contest is actually like for aspiring problemsetters. Please give me feedback about this in the comments. What else about the round would you like to know? Was this helpful? <spoiler summary="Round Timeline"> To denote problems, I will use quotes to denote the number of problems proposed for that postion so far (e.g. A' represents the first A proposed for the round, A'' represents second A proposed, etc). If the problem is in the final set, then it will be **bolded**. For dates, I will use the american standard notation (mm/dd). Also, I will not go in detail about why problems were rejected/unused because they might appear in the future. 8/11: [contest:1998] has just concluded and [user:sum,2024-10-18] has shipped himself off to college and won't have time due to <s>attending frat parties</s> his studies. I invite [user:vgoofficial,2024-10-18] to problemset with m...
() mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree

Full text and comments »

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

157.
By DNR, 2 years ago, In English
Funny construction for Suffix Tree/Fast set split (Leader Split Trick) ## Outline - Problem - Algorithm - Complexity Analysis - Code - Example Problems Hello, in this blog I'll share a funny way to construct a suffix tree in $O(n \log^2{n})$ time, for a given string $S$ of length $n$. I am going to call the underlying idea the "Leader Split Trick". It can probably be used to solve other problems too. ## Problem A suffix tree of a string $S$ is a [radix tree](https://en.wikipedia.org/wiki/Radix_tree) constructed from all the suffixes of $S$. It's easy to see that it has $O(n)$ nodes. It can be constructed in $O(n)$ using [this](https://codeforces.me/blog/entry/16780). I am going to share a simple and practically useless way of building it in a worse time complexity, $O(n\log^2{n})$. ## Algorithm <spoiler summary="Notation"> <ul> <li> When I refer to "suffix $i$" ahead, I mean the suffix $S[i, n]$. </li> <li> $l_i$ is the leaf node corresponding to suffix $i$ in the final suffix tree. </li> </ul> </spoiler> Initially, we st...
Funny construction for Suffix Tree/Fast set split (Leader Split Trick), , in this blog I'll share a funny way to construct a suffix tree in $O(n \log^2{n})$ time, for a given, > We have $n$ singleton sets, and are given some set merge operations. When merging sets $A$ and $B

Full text and comments »

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

158.
By mohammedehab2002, history, 7 years ago, In English
Codeforces round #628 editorial ### [problem:1325A] $a=1$ and $b=x-1$ always work. Code link: https://pastebin.com/ddHKD09B First AC: [user:Sevlll,2020-03-14] **Bonus task:** can you count the valid pairs? ### [problem:1325B] Let the number of distinct elements in $a$ be called $d$. Clearly, the answer is limited by $d$. Now, you can construct your subsequence as follows: take the smallest element from the first copy, the second smallest element from the second copy, and so on. Since there are enough copies to take every element, the answer is $d$. Code link: https://pastebin.com/hjcxUDmY First AC: [user:socho,2020-03-14] ### [problem:1325C] Notice that there will be a path that passes through the edge labeled $0$ and the edge labeled $1$ no matter how you label the edges, so there's always a path with $MEX$ $2$ or more. If any node has degree 3 or more, you can distribute the labels $0$, $1$, and $2$ to edges incident to this node and distribute the rest of the labels arbitrarily. Other...
### [problem:1325A] $a=1$ and $b=x-1$ always work. Code link: https://pastebin.com/ddHKD09B

Full text and comments »

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

159.
By Shayan, 12 months ago, In English
Codeforces Round 1065 (Div. 3) — Solution Discussion [A, B, C, D, F] **Note: The text editorials will be provided by the authors of the round. This video tutorial acts as an additional resource for those who prefer video over text, not as a substitute for the text editorial.** ### [2171A &mdash; Shizuku Hoshikawa and Farm Legs](https://codeforces.me/contest/2171/problem/A) <spoiler summary="Video"> <iframe width="800" height="450" src="https://www.youtube.com/embed/IWGqL9LOOhU?si=41lBHRE3WzfrOdSa&amp;start=311" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> </spoiler> ### [2171B &mdash; Yuu Koito and Minimum Absolute Sum](https://codeforces.me/contest/2171/problem/B) <spoiler summary="Video"> <iframe width="800" height="450" src="https://www.youtube.com/embed/IWGqL9LOOhU?si=41lBHRE3WzfrOdSa&amp;start=581" title="YouTube video player" frameborder="0" allow="ac...
Codeforces Round 1065 (Div. 3) — Solution Discussion [A, B, C, D, F]

Full text and comments »

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

160.
By kelzzin2_fan, 2 years ago, In English
[Tutorial] Disjoint Sets Union (DSU) Extensions with Auxiliary Nodes: Move and Erase Hello Codeforces community, this is my first educational blog on a topic, hopefully some will find it useful despite it not being difficult in nature. Note: This is not meant to be an introduction to Disjoint Sets Union, if needed, please refer to this [tutorial](https://codeforces.me/edu/course/2/lesson/7) before reading the following. This is a tutorial based on this [article](https://oi-wiki.org/ds/dsu/). Here, I'll include some new ideas and implementation details of mine as well. Thanks [user:DavidTan,2024-06-17] and [user:nickyfoo,2024-06-17] for proof-reading and also [user:kelzzin2,2024-06-17] for exisiting. DSU Recap ========= For those who need a quick recap, DSU are meant to support 2 main operations: - $union(a,b)$: merge the 2 sets that contain $a$ and $b$. - $find(a)$: return some identifier that represents the set that $a$ is in. Note that $find(a) = find(b)$ iff $a$ and $b$ are in the same set. How this is done is by representing the sets as forests. ...
same tree that $b$ belongs to, they are in the same set. We check this if the root of thetree they

Full text and comments »

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

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

Full text and comments »

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

162.
By jay_jayjay, history, 15 months ago, In English
Teamscode Summer 2025 Contest Official Editorial Thanks for participating in TeamsCode, and I hope you enjoyed the problems! All problems were written and prepared by [user:hyforces,2025-08-20], [user:Yam,2025-08-20], [user:culver0412,2025-08-20], [user:alexlikemath007,2025-08-20], [user:Jasonwei08,2025-08-20], [user:n685,2025-08-20], [user:HaccerKat,2025-08-20], [user:jay_jayjay,2025-08-20], [user:feining_for_gm,2025-08-20], [user:Mustela_Erminea,2025-08-20], [user:eysbutno,2025-08-20], [user:furyna,2025-08-20], [user:iframe_,2025-08-20], [user:Nyctivoe,2025-08-20], [user:TheYashB,2025-08-20], [user:gggg0,2025-08-20], [user:training4usaco,2025-08-20], [user:ThatRowletOwlet,2025-08-20], and [user:superhelen,2025-08-20]. Also thanks to our testers for valuable feedback, and the Teamscode web and logistics teams for making this contest possible! Also thanks to [user:omeganot,2025-08-24] for writing an unofficial editorial [here](https://codeforces.me/blog/entry/145620). [Novice A/](https://codeforces.me/gym/106042/proble...
# [Novice G/](https://codeforces.me/gym/106042/problem/G)[Advanced B: Max BinaryTree Width](https

Full text and comments »

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

163.
By bobr_babizon, 2 years ago, translation, In English
Перевод статьи ko_osaga по Kinetic Segment Tree. Я очень много слышу о данной теме, но не смог найти какие-то ресурсы на русском или английском языке и решил сделать перевод статьи [user:ko_osaga,2024-06-13]. Данный перевод может содержать много неточностей, а также в нем не доступны ссылки, который есть в оригинальной статье. В этой статье представлено новое дерево отрезков, называемое Kinetic Segment Tree. Элемент считается Kinetic, если он перемещается со временем, то есть, если элемент представляет собой линейную или многочленную функцию. Деревья отрезков часто встречаются на соревнованиях, как и Kinetic элементы (например, трик с выпуклой оболочкой), поэтому изучение их комбинации также может быть полезным. Также стоит отметить, что Kinetic свойства можно выявить даже в задачах, не связанных напрямую с Kinetic элементами (например, использование CHT в оптимизации DP), и рассмотреть, как Kinetic Segment Tree может быть применен. Об этой структуре данных уже упоминалось в статьях на Codeforces, но недавно я нашел время для б...
Translation of the article by ko_osaga on Kinetic Segment Tree., Перевод статьи ko_osaga по Kinetic Segment Tree., Technically, the Kinetic Segment Tree is similar to Segment Tree Beats. Like other segment trees, This problem can be solved using the Kinetic Segment Tree offline in $O(Q \log^2 Q)$. All segments, Технически, Kinetic Segment Tree похож на Segment Tree Beats. Как и другие деревья отрезков, в, Эту задачу можно решить с помощью Kinetic Segment Tree оффлайн за $O(Q \log^2 Q)$. Все отрезки

Full text and comments »

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

164.
By SpyrosAliv, 2 years ago, In English
Editorial for TheForces Round #38 [Problem A &mdash; Cyclic Tree](https://codeforces.me/gym/105622/problem/A) First Solve: [user:arvindf232,2024-12-17] <spoiler summary="Hint"> What happens when adding an edge between two nodes with distance of $k$ (amount of edges in the simple path from one node to another is $k$)? </spoiler> <spoiler summary="Solution"> Suppose that the amount of edges in the simple path from $u$ to $v$ is $k$. Adding a new edge $(u, v)$ will create a new cycle of $k$ nodes (with $k+1$ edges). Therefore, in order to create a cycle of size at least $3$, it is enough to find any two nodes that are not adjacent and connect them. Due to the small constraints, it is enough to try all possible pairs of nodes and check if they're neighbors or not. </spoiler> <spoiler summary="Implementation 1"> ```c++ #include <bits/stdc++.h> using namespace std; vector<set<int>> tree; void solve() { int n; cin >> n; tree.resize(n+1); for (int i = 1; i < n; i++) { in...
[Problem B — Tree Game](https://codeforces.me/gym/105622/problem/B) (Idea by

Full text and comments »

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

165.
By PrinceOfPersia, 12 years ago, In English
Hello 2015 Contest Hey everbody. **Hello 2015** is a Div.1 + Div.2 contest that will be held in gym [soon](http://www.timeanddate.com/worldclock/fixedtime.html?msg=Hello+2015&iso=20150107T19&p1=246&ah=3). As I said, there will be 2 divisions and in each divisions, users of that division can participate ( $(- \infty,1699]$ and $[1700,9999]$). So, anybody who participates in the wrong division will be **out of competition** (manually). ![ ](http://www.diwalisms2wishes.in/wp-content/uploads/2014/12/New-Year-1st-Jan-Tamil-E-Cards-2015-download.jpg) Duration is 3 hours and there will be 6 problems in each division. Last 4 problems of Div.2 will be same as first 4 problems of Div.1 . Problems are written by me ([user:PrinceOfPersia,2015-01-11]) and tester's [user:M.Mahdi,2015-01-11]. The problems will be sorted according to the estimated order of difficulty according to my opinion but I strongly recommend you to read all of the problems.(sentence from [user:matrix,2015-01-11] :D). Problems ...
Div.1 A : Binary search, B : Dijkstra, C : DP,Two pointers,queue, D : 2-sat, E: Hash, Segmenttree

Full text and comments »

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

166.
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...
] > \ldots < a[i_{10}]$. 2. **Paths in tree** Given a tree of length $N$ ($N \le 10^5$), find the

Full text and comments »

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

167.
By AboAbdoMC, 3 years ago, In English
[EDITORIAL] Syrian Private Universities Collegiate Programming Contest 2023 [A &mdash; G Game](https://codeforces.me/gym/104426/problem/A) Author: [user:Blade-Master,2023-07-10] <spoiler summary="Tutorial"> </spoiler> <spoiler summary="Solution"> </spoiler> [B &mdash; Permutation Tree](https://codeforces.me/gym/104426/problem/B) Author: [user:Space-Time-,2023-07-10] <spoiler summary="Tutorial"> This problem is solved greedily. Let $v$ be the minimum unassigned node in the tree. We have to assign it the minimum possible value. This can be done by assigning each unassigned value on the simple path from the root $x$ to $v$ the minimum possible value. This can be done in $O(n)$. </spoiler> <spoiler summary="Solution"> ~~~~~ #include<bits/stdc++.h> using namespace std; int n , x , p [200005] , k , pr [200005]; vector < int > gr [200005]; void dfs ( int x , int pt ) { pr [x] = pt; for ( auto u : gr [x] ) { if ( u == pt ) continue; dfs ( u , x ); } } int up ( int x ) { if ( p...
[B — Permutation Tree](https://codeforces.me/gym/104426/problem/B)

Full text and comments »

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

168.
By ifsmirnov, history, 11 years ago, translation, In English
Codeforces Round #349 Editorial [problem:667A] To know how much water you consume per second you should divide consumed volume, $v$, by the area of the cup, $\dfrac{\pi d^2} 4$. Then you should compare thisit with $e$. If your speed of drinking is greater, then you'll drink all the water in $\dfrac{h}{\tfrac{4v}{\pi d^2}-e}$ seconds. Otherwise you would never do it. [problem:667B] It is possible to make a convex polygon with given side lengths if and only if a generalized triangle inequality holds: the length of the longest side is less than the sum of lengths of other sides. It is impossible to make a convex polygon from a given set, so there is a side which is longest than (or equals to) than sum of others. Assume it is greater by $k$; then it is sufficient to add a rod of length $k+1$. More, it is clear that adding any shorter length wouldn't satisfy the inequality. Thus the answer for the problem is $\texttt{max}(l_1, \dots, l_n) - (l_1 + \dots + l_n - \texttt{max}(l_1, \dots, l_n)) + 1$. [probl...
] which has the largest amount of occurrences of substring s[a,  b]'' approaching. Let's build

Full text and comments »

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

169.
By colorBlindCoder, history, 15 months ago, In English
MAANG Interview: Interesting Binary Tree Coloring problem Hey folks My friend shared a question asked to him in a MAANG interview: `You are given a Binary tree, each of the nodes of the tree is coloured with a colour belonging to {R, G, B}. You have to find all possible root nodes of the tree s.t. any path from the root to any node follows the colour pattern of R -> G -> B -> R -> G -> B -> R -> .... It need not start from R, it can start from any colour but needs to follow the RGB pattern cyclically.` My Solution: My first observation is that: _there can only be a single node that can be a root of such a tree_. We can prove this by saying if there are two such nodes (let's say A and B), then the path from A to B follows the RGB pattern as well as the path from B to A, which is not possible; hence, there can only be a single root following the constraints. My other observation is: If we choose some other node as root (than the one that follows the constraints), if we go down; path along one of the child will follow RGB patte...
MAANG Interview: Interesting Binary Tree Coloring problem, {R, G, B}. You have to find all possible root nodes of the tree s.t. any path from the root to any

Full text and comments »

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

170.
By wangmarui, history, 11 months ago, In English
Hello 2026 Editorial We'd like to thank you all for participating in the contest, and hope you enjoyed it. Any feedback would be appreciated! <spoiler summary="Rate The Contest!"> - Great contest - Good contest - Average contest - Bad contest </spoiler> ## [2183A &mdash; Binary Array Game](https://codeforces.me/contest/2183/problem/A) Idea & Preparation: [user:wangmarui,2025-12-23] <spoiler summary="Rate The Problem!"> - Good Problem - Okay Problem - Bad Problem - Didn't Solve </spoiler> <spoiler summary="Hint 1"> If the sequence $a$ consists entirely of $1$ s, what will Alice do? </spoiler> <spoiler summary="Hint 2"> Consider discussing the values of $a_1$ and $a_n$. </spoiler> <spoiler summary="Solution"> First, if the entire sequence consists of $1$ s, Alice wins immediately by operating on the whole sequen...
#define ll long long #define cll const ll #define forl(i,a,b) for(re ll (i)=(a);i<=(b);(i

Full text and comments »

Tutorial of Hello 2026
  • Vote: I like it
  • +146
  • Vote: I do not like it

171.
By khatribiru, history, 9 years ago, In English
Persistent segment tree ( Problems ) This blog is just the list of problems for Persistent segment tree. Before start you can learn the topic from [here](https://blog.anudeep2011.com/persistent-segment-trees-explained-with-spoj-problems/) , [here](https://www.geeksforgeeks.org/persistent-segment-tree-set-1-introduction/) & [here](https://drive.google.com/file/d/0BwGLW04WRv0ITEZjRWlMSFc2bk0/view) 1.[SPOJ,MKTHNUM,K-th Number](http://www.spoj.com/problems/MKTHNUM/) 2.[SPOJ,DQUERY,D-query](http://www.spoj.com/problems/DQUERY/) 3.[SPOJ,COT,Count on a tree](http://www.spoj.com/problems/COT/) 4.[SPOJ,TTM,To the moon](http://www.spoj.com/problems/TTM/) 5.[lightoj,1188,Fast Queries](https://vjudge.net/problem/LightOJ-1188) 6.[CF,813E,Army Creation](http://codeforces.me/problemset/problem/813/E) 7.[CF,707D,Persistent Bookcase](http://codeforces.me/contest/707/problem/D) 8.[CF,762E,Radio stations](http://codeforces.me/problemset/problem/762/E) 9.[Hackerrank,Kth Number](https://www.hackerrank.com/contest...
Persistent segment tree ( Problems ), 20.[CF,833B,The Bakery](http://codeforces.me/problemset/problem/833/B), This blog is just the list of problems for Persistent segment tree. Before start you can learn the

Full text and comments »

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

172.
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...
/wikipedia/commons/thumb/b /b1/Edmonds_lifting_path.svg/500px-Edmonds_lifting_path.svg.png) Let's

Full text and comments »

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

173.
By GM_Dan4Life, 2 years ago, In English
[Tutorial] Solving Range (Chmin, Chmax, Add, Assign) + Point queries Hi Codeforces! This is my first attempt at a tutorial blog XD. Disclaimer: No headaches occured during the making of this blog Problem statement ----------------- Given an integer array $A$ of length $n$ and $q$ of the following 5 types of queries: 1. For all $i \in [l,r]$, change $A_i$ to $\max(A_i, v)$ 2. For all $i \in [l,r]$, change $A_i$ to $\min(A_i, v)$ 3. For all $i \in [l,r]$, change $A_i$ to $A_i + v$ 4. For all $i \in [l,r]$, change $A_i$ to $v$ 5. Output $A_i$ - $ 1 \leq n,q \leq 10^6 $ - $ 1 \leq l \leq r \leq n $ - $ -10^9 \leq A_i, v \leq 10^9 $ The above is solvable with techniques like [Segment Tree Beats](https://codeforces.me/blog/entry/57319) in $\mathcal{O}(n+q\log^2{n})$, but as a binary search enthusiast, you didn't learn segment tree beats? Don't worry, here's an easier, faster, and shorter solution that solves this particular problem in $\mathcal{O}(n+q\log{n})$ Prerequisites ------------- You should know the following t...
Each node in the segment tree will contain the pair of integers $[a,b]$ which determines the

Full text and comments »

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

174.
By sofyanalam, 4 months ago, In English
[Tutorial] Solution for Codeforces Round 1111: E. Build a Tree [cut] In this post, I want to share my approach to solving **Problem E: Build a Tree** from Codeforces Round 1111. <spoiler summary="The Math Intuition"> The problem asks us to construct a tree with $n$ vertices such that $\sum_{i=1}^{n} dist(i, (i \bmod n) + 1) = k$. Let $dist(i, j) = dep(i) + dep(j) - 2 \cdot dep(LCA(i, j))$. Summing this over the cycle $i=1 \dots n$: $$\sum_{i=1}^n dist(i, (i \bmod n) + 1) = 2 \sum_{i=1}^n dep(i) - 2 \sum_{i=1}^n dep(LCA(i, (i \bmod n) + 1))$$ **Key takeaways from this equation:** 1. **$k$ must be even:** Since the RHS is multiplied by $2$, the total sum $k$ must be an even number. If $k$ is odd, no such tree exists. 2. **Minimum $k$ is $2(n-1)$:** This occurs when the tree is a "star graph" (all nodes connected to the root), which keeps depths minimal. 3. **Maximizing $k$:** To reach a higher $k$, we need to maximize depths and minimize the $dep(LCA)$ terms. The LCA of adjacent nodes $(i, i+1)$ becomes $0$ (the root) ...
[Tutorial] Solution for Codeforces Round 1111: E. Build a Tree, ); tree(a,even); tree(b,odd); } ~~~~~

Full text and comments »

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

175.
By HubRis504, history, 3 months ago, In English
Unusual Style Changes in plagues' Submissions Some time ago, [user:plagues,2026-08-31] published [The most outrageous cheating in the history of Huawei Challenge](https://codeforces.me/blog/entry/156293), questioning whether several highly ranked accounts in the Huawei Challenge might have collaborated with each other. The original post was written with considerable confidence in labeling those accounts as cheaters. While some of the cases it discussed may have had relatively strong supporting evidence, many of the other connections were based on weaker correlations or incidents that, as far as I know, have not been independently substantiated. This post does not attempt to evaluate or revisit those allegations. However, that post drew my attention to this account. I noticed an unusual period in [user:plagues,2026-08-31]'s rating trajectory, so I reviewed 59 of his `CONTESTANT` submissions from the following six contests. There are several differences in coding style and apparent origin among these submissions that I believe d...
because they were used for different purposes. However, please explain why `BIT` became `B`, and why

Full text and comments »

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

176.
By jjang36524, 5 years ago, In English
Tutorial and tips to reach Master. "As mentioned earlier, practice hard. This is the only common factor that experts have. And for whom reached expert, I'll write a sequel from expert to master soon." (From my blog, Tutorial and tips to reach Expert). That soon happened to be 1.5 years after the first blog...... First, I'm sorry for the immense delay. Many bad things happened to me, like not staying in the Master rating range, having a health problem, etc. That's why I wrote the blog this late. Introduction ------------------ This is a sequel, but I am going to write the steps to Expert from scratch since the original blog([https://codeforces.me/blog/entry/81882](https://codeforces.me/blog/entry/81882)) has poor quality. Your journey is going to be divided into 4 sections. Each section contains the knowledge you need to have, the practice you must do, the performance you need to have in a contest, etc to advance to the specific rating. Section 1. From the beginning to escaping Gray(1200) ---------------...
[https://codeforces.me/problemset/problem/1583/B ](https://codeforces.me/problemset/problem/1583/B

Full text and comments »

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

177.
By pavook, history, 4 years ago, In English
Benchmarks of different segment tree implementations Sometimes I wonder, what implementation of a segment tree to use. Usually, I handwave that some will suit, and that works in most of the cases. But today I decided to back up the choice with some data and I ran benchmarks against 4 implementations: <ul> <li> Simple recursive divide-and-conquer implementation <spoiler summary="Code"> ~~~ struct SimpleRecursiveSegmentTree { unsigned size; private: std::vector<long long> t; void _build(const std::vector<int> &v, unsigned p, unsigned l, unsigned r) { if (r == l + 1) { t[p] = v[l]; return; } unsigned m = (l + r) / 2; _build(v, 2 * p + 1, l, m); _build(v, 2 * p + 2, m, r); t[p] = t[2 * p + 1] + t[2 * p + 2]; } long long _get(unsigned p, unsigned l, unsigned r, unsigned a, unsigned b) const { if (b <= l || r <= a) { return 0LL; } if (a <= l && r <= b) { ...
Benchmarks of different segment tree implementations, long long _get(unsigned p, unsigned l, unsigned r, unsigned a, unsigned b

Full text and comments »

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

178.
By Errichto, 11 years ago, In English
Good Bye 2015 Editorial [problem:611A] There are two ways to solve this problem. The first is to hard-code numbers of days in months, check the first day of the year and then iterate over days/months &mdash; [http://ideone.com/4TYPCc](http://ideone.com/4TYPCc) The second way is to check all possible cases by hand. The 2016 consists of 52 weeks and two extra days. The answer for "x of week" will be either 52 or 53. You must also count the number of months with all 31 days and care about February. [http://ideone.com/Bf9QLz](http://ideone.com/Bf9QLz) [problem:611B] Each number with exactly one zero can be obtained by taking the number without any zeros (e.g. $63_{10} = 111111_{2}$) and subtracting some power of two, e.g. $63_{10} - 16_{10} = 111111_{2} - 10000_{2} = 101111_{2}$. Subtracting a power of two changes one digit from '1' to '0' and this is what we want. But how can we iterate over numbers without any zeros? It turns out that each of them is of form $2^x-1$ for some $x$ (you can c...
+1, \ldots, y$. Let $dp[b][c]$ define the number of ways to split some prefix (into increasing

Full text and comments »

Tutorial of Good Bye 2015
  • Vote: I like it
  • +184
  • Vote: I do not like it

179.
By Noobish_Monk, history, 2 years ago, In English
"YAY I'M GM!!!" blog So recently I became red on CF and my happiness knows no boundaries. For achieving the red color, I would like to thank those who helped me the most. [user:dmikhalin,2024-12-01], my first informatics teacher who inspired me to do competitive programming [user:gmusya,2024-12-01], teacher in B parallel of the main programming club in Russia, who answered many of my questions and helped my a lot And all the teachers of parallel A! I'd like to tell a timeline of my progression. Three years ago when I ended 8th grade I got a giant boost of motivation after I learned segment tree and dsu from CF EDU (that's actually useful try it). In summer school I got to expert (that was so cool, I still remember how I solved problem F from div 3, back then it was difficult). Then I continued to grind CF. Before 9th class I learned that there is a strong programming club from Tinkoff, so I decided to try to get there. Easily the best decision, this club gave me a gigantic boost during these ...
boost of motivation after I learned segment tree and dsu from CF EDU (that's actually useful try it

Full text and comments »

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

180.
By duality, 3 years ago, In English
Codeforces Round #884 (Div. 1 + Div. 2) Editorial Video editorials for [B](https://www.youtube.com/watch?v=5nzUni8dFLQ), [C](https://www.youtube.com/watch?v=8mz7gnAJ5QM), and [D](https://www.youtube.com/watch?v=ahnNAwpGwHc) are available on [user:ak2006,2023-07-11]'s channel. ### [problem:1844A] <spoiler summary="Hint 1"> There exists a small $n$ where the second player can win. </spoiler> <spoiler summary="Hint 2"> If $a \ge 2$, then $n = 1$ works. </spoiler> <spoiler summary="Solution"> [tutorial:1844A] </spoiler> <spoiler summary="Implementation"> ~~~~~ #include <bits/stdc++.h> using namespace std; int main() { int t,a,b; scanf("%d",&t); while (t--) { scanf("%d %d",&a,&b); printf("%d\n",a+b); } return 0; } ~~~~~ </spoiler> ### [problem:1844B] <spoiler summary="Hint 1"> In order for $(l,r)$ to contribute to the primality, we must have $\operatorname{MEX}(a_l,\dots,a_r) \ge 2$, so there is some value $1$ between indices $l$ and $r$. </spoiler> <spoile...
Video editorials for [B](https://www.youtube.com/watch?v=5nzUni8dFLQ), [C](https://www.youtube.com

Full text and comments »

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

181.
By darkshadows, 12 years ago, In English
CodeCraft'15 IIIT Hyderabad Editorial [problem:100589A] ------------------ Given a rooted tree(at node 1) of **N** nodes,you have to handle a total of **Q** operations of type: **1 U L X**: Increase coins by **X** of all nodes at a distance of **L** from root. **2 X**: Report sum of all coins in subtree rooted at **X**. **N** <= 10<sup>5</sup> **Q** <= 10<sup>4</sup> #### Difficulty: Medium-Hard ####Explanation: This approach uses a very specific technique of maintaining a buffer of update queries and updating the whole tree once buffer size exceeds a constant limit(we maintain this limit as sqrt(M)). ~~~~~ buffer=[] q=input while q--: query = input() if query==update: buffer.add(query) else: //say query is “2 X” //the answer that has been already calculated for node X prevans= ans(X) for i=0 to buffer.size(): //add to prevans the effect of buffer[i] //let’s say buffer[i]=”1 U L...
us the Lowest Common Ancestor of two nodes **A** and **B** in the same tree. **Dist(A,B

Full text and comments »

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

182.
By Jon.Snow, 6 years ago, In English
CSES Tree section editorial Hello Codeforces, [CSES](https://cses.fi/problemset/list) is a nice collection of classical CP problems which encourages you to learn a lot of basic and advanced concepts. Having editorials would help people to not get stuck on a problem for long. Here are my solutions to the tree section of the problem-set. Looking forward to read corrections/feedback/better solutions in the comment section. Happy coding! Subordinates ------------------ This can be solved using basic DP approach in linear time. <br> $subordinates[u] = \sum\limits_{v:children[u]}^{} subordinates[v]$ where v is a child of u <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; const int SZ = 200005; int n, m, x; vector<int> adj[SZ]; int S[SZ]; void dfs(int u,int l, int p) { S[u] = 1; for (int v: adj[u]) { if (v != p) { dfs(v, l+1, u); S[u] += S[v]; } } } int main() { cin >> n; for(int i = 2; i <=n ; i++) { cin >> x; ...
CSES Tree section editorial, for(int i = 0; i < n-1; i++) { cin >> a >> b; adj[a].push_back(b); adj[b ].push_back(a); }, while(q--) { cin >> a >> b; int lca = LCA(a,b); cout << L[a] + L[b] - 2*L[lca] << endl

Full text and comments »

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

183.
By KaiZeR, 13 years ago, translation, In English
Editorial Codeforces Round #247 (Div. 2) [problem:431A] ------------- To solve this problem, you must only do the process described in statement. ~~~~~ for i = 1 .. s.size() if (s[i] = '1') ans += a[1]; else ... ~~~~~ **Complexity**: $O(N)$<br> **Solution**: [submission:6676675] [problem:431B] ------------- In this problem, according to the small limits, we can brute all permutations and choose the best answer of all. The easeast way to do this &mdash; use standart C++ function _next_permutation_, or simply write 5 _for_. For each permutation we can simulate the process, which was described in a statement, or notice that first with second student, and second with the third will communicate one time, and third with fourth student, and fourth with fifth &mdash; will communicate two times. Another pairs of students will never communicate to each other during they stay in queue.<br> **Complexity**: $O(n!)$<br> **Solution**: [submission:6676695] [problem:431C] ------------- This problem can be solved by ...
To quickly find for $a[0] + a[1] + ... + a[d- 1]$ and $b[0] + ... + b[d-1]$, and perform queries of

Full text and comments »

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

184.
By mango_lassi, history, 8 years ago, In English
Problem H (Game on the Tree) from CCPC 2018 [This problem](https://codeforces.me/gym/102055/problem/H) I have a solution I think is correct but can't get it to pass, and apparently even my n^2 code (standard game theory iterating through all states solution) that should obviously work gets WA. They both give the same answers for random small inputs. I can't find editorials or test data for the contest, so seeing so many teams have +1 or more in this problem, is there some tricky corner case I might have missed? My code if it is of any interest: <spoiler summary="code"> ~~~~~ #include <iostream> #include <vector> #include <utility> #include <algorithm> using namespace std; const int INF = (int)1e9 + 7; bool findCycle(int i, vector<int>& cycle, vector<int>& par, const vector<vector<int>>& conns) { for (auto t : conns[i]) { if (par[i] == t) continue; if (par[t] != -1) { if (par[t] == i) swap(t, i); while(i != t) { cycle.push_back(i); i = par[i]; } cycle.push_back(i); re...
Problem H (Game on the Tree) from CCPC 2018, int a, b; cin >> a >> b; --a; --b;, vector> conns(n); for (int i = 0; i < n; ++i) { int a, b; cin >> a >> b; --a

Full text and comments »

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

185.
By bfsof123, 21 month(s) ago, In English
Learning Notes on the Hopcroft-Tarjan planarity algorithm (With C++ Implementation) **Section 1. Introduction** I have been struggling for weeks to understand the first linear-time planarity algorithm, the [Hopcroft-Tarjan algorithm (HT)](https://www.cs.princeton.edu/courses/archive/fall05/cos528/handouts/Efficient%20Planarity.pdf). Fortunately, I successfully understood it and implemented it. In fact it is very hard to find a verified HT implementation online. Some code, e.g., [LEDA](https://en.wikipedia.org/wiki/Library_of_Efficient_Data_types_and_Algorithms) is not open source. Other open-source planarity tests, e.g., [networkx (LR planarity)](https://github.com/networkx/networkx/blob/main/networkx/algorithms/planarity.py), [boost (Boyer-Myrvold)](https://www.boost.org/doc/libs/1_53_0/libs/graph/doc/boyer_myrvold.html), [Pigale (LR planarity)](https://pigale.sourceforge.net/), use other algorithms. There is [an implementation by Shawn Anderson](https://github.com/shawnwanderson/Hopcroft-Tarjan-Planarity-Testing), however it is partial. I would like to open a blo...
A path $v_i$->(tree arcs)->$a$--(frond)->$b$ has a conflict with path $v_k\,(k > i)$->(tree arcs

Full text and comments »

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

186.
By Aveiro_quanyue, history, 4 years ago, In English
A note on a nowcoder problem -- Centroid decomposition (点分治) Nowcoder problem (Chinese) [link](https://ac.nowcoder.com/acm/contest/51721/E). The submission is private because I don't want to publish my Nowcoder account, but you can copy the code at the end of this blog and paste it to the answer sheet, it will get AC. [English version](https://codeforces.me/blog/entry/114434) First I would like to thank [user:ShaoNianTongXue5307,2023-03-28] for his idea! This is a learning note, most for myself. Most of this blog is not original. **Part 1: Problem Statement:** A tree $T=(V, E)$ has $n$ vertices and $n-1$ edges, the weight of each vertex $i$ is $a_i$. For each edge $e$, you can determine its direction, i.e., for two vertices $u, v$, there are two states: $u \rightarrow v$ and $v \rightarrow u$. There are $2^{n-1}$ states in total. For each state $S$, we define $f(S)$ as $f(S) := \sum\limits_{(u, v) \in V \times V, v\,\text{is reachable from}\,u} |a_u - a_v|$. Compute the sum of $f(S)$ over all $2^{n-1}$ states $S$, mo...
has a size at most half the size of the original tree. For example, the centroids for the path A--B--C

Full text and comments »

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

187.
By lucifer1004, history, 6 years ago, In English
My Editorial for Google Kick Start 2021 Round B # Google Kick Start 2021 Round B Tutorial [中文版 | Chinese version](https://cp-wiki.vercel.app/tutorial/kick-start/2021B/) Here are my solutions to Google Kick Start 2021 Round B. Some of them (C & D) are not optimal, albeit they passed all the test cases. ## Problem A &mdash; [Increasing Substring](https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435a5b/000000000077a882) We simply go ahead and try appending the current letter after the last letter. Complexity: - Time complexity is $\mathcal{O}(|S|)$. - Space complexity is $\mathcal{O}(|S|)$. <spoiler summary="Code (C++)"> ~~~~~ #include <cstdio> #include <iostream> #include <vector> using namespace std; template <typename T> void read(T &x) { x = 0; char c = getchar(); T sig = 1; for (; !isdigit(c); c = getchar()) if (c == '-') sig = -1; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= sig; } class Solution { public: void solve(i...
My Editorial for Google Kick Start 2021 Round B, The official solution uses the segment tree. However, we can also use the blocking technique to

Full text and comments »

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

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

Full text and comments »

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

189.
By shorya1835, 21 month(s) ago, In English
Editorial for Insomnia'25 [A \- XO-OR](https://codeforces.me/gym/590997/problem/A) <spoiler summary="Solution"> To solve this problem optimally, we need to ensure that we maximize the size of the set $S$ while satisfying the given constraints on XOR and OR operations. A necessary condition for a valid set is that $ y $ must be a **subset** of $ v $. In terms of bits, this means every bit that is set in $ y $ must also be set in $ v $. If $ y > x $, then at least one bit in $ y $ is missing from $ x $, making it impossible to construct a valid set where the XOR of elements results in $ y $. Thus, in such cases, the answer is immediately $ -1 $. To understand how we construct valid sets, consider forming all possible subsets of the bits set in $ v $. The total number of such subsets is $ 2^{pc} $, where $ pc $ is the number of set bits in $ v $. Each individual bit contributes exactly $ 2^{(pc - 1)} $ times across all subsets, meaning the overall XOR of the entire set cancels out to $ 0 $ when $ pc \ge...
#define ordered_set tree, rb_tree_tag,tree_order_statistics_node_update, ; typedef pair pi; typedef pair pl; #define ordered_set tree

Full text and comments »

Tutorial of Insomnia 2025
  • Vote: I like it
  • +73
  • Vote: I do not like it

190.
By ACGN, history, 2 years ago, In English
Codeforces Round 987 (Div. 2) Editorial <spoiler summary="A little backstory about the round (ACGN)">The Highschool CPers (HSCP) Discord server was created in April 2022 by [user:pwned,2024-11-14], which over time grew into a close-knit community of highschool competitive programmers. I joined in the same month of its creation, and in the next month I approached [user:pwned,2024-11-14] about the possibility of setting a contest. Thus the HSCP round concept was born. Over the next month or so, the initial problems were born; the current problems A and F were produced in June-July 2022. We had several problem ideas by then, enough to set a div.2 round. However, as I was going to be busy in my 5th year of high school, and may not be that responsive to coordinators, the contest was in the ownership of [user:pwned,2024-11-14], who needed to wait until he reached master in order to propose the set on Codeforces. However, this step took almost 1.5 years as he would stay at candidate master for 57 consecutive contests, eve...
apparent. The original problems A, C, E became the current A, D, F, and three new problems (forB, C

Full text and comments »

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

191.
By voinchuguna, 4 years ago, In Russian
Sqrt Beats, Treap Beats? Prerequisites ---------- If you are familiar with the _Segment Tree_, you have probably heard of _Segment Tree Beats_ (or _STB_). This concept usually means a set of ideas related to changing the conditions for visiting a vertex of the tree (article by the author of this method: https://codeforces.me/blog/entry/57319). However, this method can be used not only with a Segment Tree, but also with many other structures on segments (e.g. _Sqrt Decomposition_, _Treap_). ### Why are we still here...? There are two reasons why we might want to use STB outside of Segment Trees: 1) There are types of queries that Segment Trees can't process, but other structures can (e.g. we can't split and merge Segment Trees in general). 2) Sometimes it's easier (or more efficient) to implement solution using Sqrt Decomposition instead of Segment Tree. For example, it's way easier to vectorize Sqrt Decomposition than Segment Trees (you can write something similar to _B-trees_) or we can trade m...
Segment Tree: $O(n * B)$, memory complexity of Sqrt Decomposition: $O(n + \sqrt{n} *B)$ where $B

Full text and comments »

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

192.
By adamant, 10 years ago, translation, In English
General ideas **// Finally translated!** Hi everyone! Do you like ad hoc problems? I do hate them! That's why I decided to make a list of ideas and tricks which can be useful in mane cases. Enjoy and add more if I missed something. :) [cut]<br> **1. Merging many sets in $O(n\log{n})$ amortized.** If you have some sets and you often need to merge some of theme, you can do it in naive way but in such manner that you always move elements from the smaller one to the larger. Thus every element will be moved only $O(\log{n})$ times since its new set always will be at least twice as large as the old one. Some versions of DSU are based on this trick. Also you can use this trick when you merge sets of vertices in subtrees while having dfs. **2. Tricks in statements, part 1.** As you may know, authors can try to hide some special properties of input to make problem less obvious. Once I saw constraints like $\relax 1 \leq a \leq b \leq 10^5, \dots, ab \leq 10^5$. Ha-ha, nice joke. It is actually...
constraints like $\relax 1 \leq a \leq b \leq 10^5, \dots, ab \leq 10^5$. Ha-ha, nice joke. It is

Full text and comments »

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

193.
By oversolver, 5 years ago, In English
[Tutorial] Fast and simple RSQ with range addition (not segment tree!) #### TL;DR: `range_sum_range_add` with only two BITs. Suppose we have (sub)task to proceed following queries: - `range_sum(l, r)` - `range_add(l, r, x)` Most familiar solution is segment tree with lazy propagation. And maybe you didn't knew, but such segment tree **does not needs pushes**! <spoiler summary="code of segment tree without pushes"> ~~~~~ template<class T> struct rsq_add_segt { explicit rsq_add_segt(size_t sz = 0, const T &val = 0) { for(d=1; d<sz; d<<=1); t.assign(d*2, {val, {}}); } rsq_add_segt(const vector<auto> &vals): rsq_add_segt(size(vals)) { for(size_t i=0; i<size(vals); ++i) t[i+d].first = vals[i]; for(size_t i=d; i-->1; ) t[i].first = t[i*2].first + t[i*2+1].first; } void add(size_t l, size_t r, const T &val) { if(l>=r) return ; _add(l, r, val, 0, d, 1); } T operator()(size_t l, size_t r) const { if(l>=r) return {}; return _calc(l, r, 0, d, 1); } private: size_t d; //t[i] = pair of #(su...
[Tutorial] Fast and simple RSQ with range addition (not segment tree!), T sum_until(size_t pos) const { T a{}, b{}; for(size_t i=pos; i--; i&=i+1) a+=f[i].first

Full text and comments »

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

194.
By Proofy, history, 5 years ago, In English
Characteristics of the optimal solution, a technique for finding observations in a problem Introduction ------------------ Some of you smart people out there may find the contents of this blog so obvious, that it does not deserve to be called a "technique." It is just the totally normal thought process that comes across our minds when we try to solve a problem! However, I often find it useful (and others may relate) to state my thoughts explicitly when trying to conquer a problem, whether I write it down on a sheet of paper, comment it in my code, or just talk out loud like a crazy guy :D. I observe that one of the things that makes a problem-solver better than another (other than practice and knowledge about certain topics/algorithms, of course) is the way of thinking and approaching a problem. So, to make myself a better problem-solver, I sometimes go about thinking about how I think and try to improve this way of thinking generically and generally about any problem. It is, to many great problem-solvers, one of the byproducts of practicing problems a lot that develo...
We note that if we have a tree that we partitioned into 2 trees with XOR values $a$ and $b$, then

Full text and comments »

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

195.
By mouse_wireless, history, 8 years ago, In English
Nifty implementation of multi-dimensional Binary Indexed Trees using templates. _Prelude: this post assumes the reader already know the concepts behind Binary Indexed Trees, as I will not be explaining them here._ Let's talk about 2-dimensional Binary Indexed Trees. The implementation of 2D BIT usually goes as follows: 1. Implement a standard, 1D BIT, with update and query functions; 2. Implement 2D update and query; these look exactly the same as the 1D case, except basic operations are replaced by calls to the 1D versions of these operations. This is OK and works well for most cases. However, there are some issues with this implementation: 1. 2D methods are usually implemented (for coding speed reasons), by copy-pasting the 1D code and changing the operations. Copy-pasting is always risky, since it's so easy to miss a change you're supposed to make. 2. It doesn't feel "clean". There's duplicate code in there that makes the source harder to read (and maybe debug). Also, if you've messed up something in one of the dimensions (for example, you wrote `...
~~~~~ BIT b; b.update(x, y, z, P); b.query(x1, x2, y1, y2, z1, z2); ~~~~~

Full text and comments »

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

196.
By EvenImage, 4 years ago, In English
Problems that I authored so far Since competitive programming is dying, and I'm almost retired, so it's time to review the problems I authored. Hi everyone! I wanted to write such a blog for a long time, motivated by similar blogs, [by](https://codeforces.me/blog/entry/113093) [user:antontrygubO_o,2023-02-25], [by](https://codeforces.me/blog/entry/108940) [user:adamant,2023-02-25] and [by](https://codeforces.me/blog/entry/108595) [user:tibinyte,2023-02-25]. This is not a super-comprehensive list. I set many shit problems that I don't want to share for some local contests. It can be long, and I'm not sure if I have finished half of them yet. The number of asterisks after the label indicates the recommendation levels. One asterisk means this problem is worth reading. Two asterisks mean this problem is one of my favorite problems, Three asterisks mean this problem is one of my best problems. | # | Date | Problem | Contest | Comment | | ---- | ----------- | --------------------------------------------...
://acm.hdu.edu.cn/showproblem.php?pid=4954) | Yuhao Du Contest 1| | | 11 | August 2014 | [Tree](http, ](http://acm.hdu.edu.cn/showproblem.php?pid=4954) | Yuhao Du Contest 1| | | 11 | August 2014 | [Tree

Full text and comments »

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

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

Full text and comments »

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

198.
By ace5, 17 months ago, In English
Very hard bug in a very simple code Take a look at this code: <spoiler summary="Code"> ~~~~~ #include <bits/stdc++.h> using namespace std; vector<int> k; int f() { k.push_back(3); return 3; } int main() { k.push_back(1); k[0] = f(); cout << k[0]; } ~~~~~ </spoiler> At first glance, it should output $3$ because that's what $f()$ returns, which is then assigned to $k_0$. But when executed, this code outputs $1$! This code is very short and everything seems clear, we're simply assinging $k_0$ to the return value of $f()$ which is $3$, and the push_back in $f()$ clearly doesn't affect the result... or does it? <h3>How an assingment operation really works</h3> It may seem obvious at first, we just copying one value to another, but let's see how compiler actually handles this operation. Consider this code. ([Source](https://en.cppreference.com/w/cpp/language/eval_order.html)) <spoiler summary="Code"> ~~~~~ #include <cstdio> int a() { return std::puts("a...
("a"); } int b() { return std::puts("b"); } int c() { return std::puts("c"); } void z(int, int

Full text and comments »

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

199.
By Enigma27, history, 8 years ago, In English
Invitation to ICM Technex 2019 — IIT(BHU) Varanasi I would like to invite you all to the **International Coding Marathon 2019**, under the banner of Technex'19, IIT (BHU) Varanasi. [Technex](https://www.technex.in/) is the annual techno-management fest of Indian Institute of Technology (BHU), Varanasi organized from March 8 &mdash; 10, 2019. International Coding Marathon is the flagship event of [Byte The Bits](https://www.technex.in/events/), the set of programming events organized under Technex. ICM is brought to you by [Mentor Graphics](https://www.mentor.com/india). It will take place on [Friday, 8th March 2019, 21:00 IST](https://www.timeanddate.com/worldclock/fixedtime.html?msg=ICM+Technex+2019+by+IIT+%28BHU%29&iso=20190308T1530&ah=2). The contest will be held on [Codechef](https://www.codechef.com/ICMT2019?utm_source=contest_listing&utm_medium=link&utm_campaign=ICMT2019). The problemset has been prepared by [user:hitman623,2019-03-06], [user:dhirajfx3,2019-03-06], [user:_shanky,2019-03-06], [user:drastogi21,2019-03-08...
Let’s divide the tree into blocks of size $B$ and mark $n/B$ special nodes such that any path from

Full text and comments »

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

200.
By Ahmad_Elsagheer, 9 years ago, In English
[Editorial] Codeforces Round #417 (Div. 2) Hello Codeforces, I hope you enjoyed the round! Just some notes about the problems: - In problem A, the picture and example notes should complete your understanding for the problem if the statement itself is not clear. - Solutions that check the lights of each part separately should have failed on pretests. My bad. - Problem C was assigned as B at the beginning, but moved to C lest it is harder than B difficulty. However, I think problem B is still easier than problem C (check the solution below). - I thought problem D is easier than problem E. Once, conditions are well-understood and related to each other and the problem is modeled correctly, then its implementation is easy. The points I have just described is my own opinion in the problems. Of course, you might have a different point of view. However, I would like you to keep in mind that I did my best to make statements clear and pretests strong. Thanks for your understanding! ## [problem:812A] For ped...
Let’s go through scenario requests one by one. For request $a$ $b$, if toy $b$ is free, then child

Full text and comments »

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

201.
By fatemetmhr, 4 years ago, In English
A Problem With GCC Hi! Yesterday I was solving problem [problem:1743C], when I faced a strange verdict. My code was getting WA with C++20 ([submission:176908643]), while everything was ok with C++17 ([submission:176909474], [submission:176989803]). I tried looking for anything in my code that may cause undefined behavior, nothing found. Also there were something more strange as well; Like these two: - Changing the order of two variables in line 43 caused different verdict ([submission:176965105]). - Adding a single line of `cerr << 1;`, again,caused different verdict ([submission:176965552]). and many other strange behaviours... Here's a smaller code which has different verdicts in `GNU G++20 11.2.0 (64 bit, winlibs)` and `GNU G++17 7.3.0` on Codeforces's custom test. You can check it out yourself, but as far as I know there's nothing special or causing undefined behaviour in this code: <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> /* Woman Life Freedom */ using nam...
)) #### What's really happening ? It's all about `tree -loop-distribute-patterns` flag. You can learn about

Full text and comments »

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

202.
By yeputons, 16 years ago, translation, In English
Tutorial for problems of Codeforces Beta Round #49 (Div.2). All problems now. Let's go.<br><br><div class="title" align="center">A. Autocomplete</div><br><div align="left">In this problem you should read the statement and solve in any way. One of the most simple solutions is read string and last visited pages, sort (even bubble source - 100<sup>3</sup> isn't a lot, 3rd power because we need 100 operations to compare two strings), and rundown pages. When we find good string, we should write it and exit.<br>If there are no such one, write source string. 'Goodness' of string is checking with one <i>if</i> (to check lengths and avoid <i>RTE</i>) and <i>for</i>.<br>[cut]<br><br><div class="title" align="center">C. Froggy (Little Frog)</div><br></div>IMHO it's the second difficulty problem. If you cannot see solution just after you saw the statement, you can write brute-force solution (rundown all permutation and check), run it for <i>n=10</i> and see beautiful answer.<br>Answer is <i>1 n 2 (n-1) 3 (n-2) 4 (n-3) ... </i>Let's define two pointers - <i>l</i> and <i>r</i...
changed i to b (if b had exactly two neighbors). Answer for this tree we know

Full text and comments »

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

203.
By antontrygubO_o, 4 years ago, In English
Problems that I authored so far **UPD 1 [May 17 2025]:** I added my problems from Ukrainian Olympiad in Informatics (among others). They are available here: [contest:105820] Hi everyone! I wanted to write such a blog for a long time, motivated by similar blogs [by](https://codeforces.me/blog/entry/108940) [user:adamant,2023-02-20] and [by](https://codeforces.me/blog/entry/108595) [user:tibinyte,2023-02-20]; I finally decided to do it after my Universal Cup contest. This is not a super-comprehensive list, I also set some problems for some local contests, but that's most of it. I want to encourage other setters to write such blogs. For me, it's very interesting to read about the backstories of some problems and also to see all the problems by some author gathered in one place (as most authors give problems to several platforms). One important point. As you will see from the comments, many of my problems were improved by other people, and I myself improved some problems by other people. I think that it's cruc...
://codeforces.com/contest/1189/problem/B) | Codeforces Round #572 (Div. 2) | | | 5 | July 2019 | [Candies

Full text and comments »

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

204.
By EndlessDreams, 4 years ago, In English
TheForces Rounds Editorials Here's the editorials of [TheForces Rounds](https://t.me/TheForcesOfficial): <spoiler summary="Round 1"> <spoiler summary="Problem A"> For a number $x$, as long as $2\le x$, it can be squared to any large number. For $0$ and $1$, the square of both numbers is equal to themselves. So just compare $0$ and $1$. <spoiler summary="Code"> ~~~ void elysia() { cin >> n; bool flag=true; for(int i=1;i<=n;++i) { cin >> a[i]; a[i]=min(a[i],2ll); if(i!=1&&a[i]<a[i-1]) flag=false; } if(flag) cout << "YES" << endl; else cout << "NO" << endl; } ~~~ </spoiler> </spoiler> <spoiler summary="Problem B"> Consider the number of times each $a_i$ is XOR in the answer. for $a_i$, calculated $i(n-i+1)$ times in the answer. Two same XOR will disappear, so checking is this an odd number then done. <spoiler summary="Code"> ~~~ void elysia() { int answer=0; cin >> n; for(int i=1;i<=n;++i) { cin >> a[i]; ...
Noting that dp in Problem B can be described as a multiplication of multiple matrices, it is

Full text and comments »

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

205.
By satyam343, 3 years ago, In English
Problems that I authored so far Hi everyone! I wanted to write such a blog for a long time. I finally decided to do it after Codeforces Round $934$. I would like to thank [user:Non-origination,2024-03-21], [user:GoatTamer,2024-03-21] and [user:KingRayuga,2024-03-21] for discussing the problems with me. For each problem, I tried to include the some interesting stuff if I could remember. I tried to avoid using spoilers for the problems. So you can look at the comments even if you have not tried the problem. | # | Date | Problem | Difficulty | Contest | Comment |----|-----------|---------------------------------|------------|--------------------------------------|--------------------------------------| | 1 | Aug 2021 | [Tree Distance Sum](https://www.codechef.com/problems/TREEDIST) | Div 2 E | Codechef Starters 10 | My first problem which appeared in some contest. I noticed some nice properties about the dfs traversal and de...
|----|-----------|---------------------------------|------------|--------------------------------------|--------------------------------------| | 1 | Aug 2021 | [Tree Distance Sum

Full text and comments »

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

206.
By marat.snowbear, 12 years ago, In English
Codeforces Round #269 Editorial [problem:471A] ------------------ Given six sticks and their lengths we need to decide whether we can make an elephant or a bear using those sticks. The only common requirement for both animals is that four leg-sticks should have same length. This means that the answer "Alien" should be given **only** if we can't find four sticks for the legs. Otherwise we will be able to make some animal. The type of the animal will depend on the relation of the remaining sticks' lengths. If they are equal then it will an elephant, if they are different we will have a bear. So this algorithm should solve the problem: 1. Find the number which appears at least four times in the input. 2. If no such number exist then the answer is "Alien". 3. Otherwise remove four entries of that number from the input. 4. After removing that number you will have two numbers left, compare them and decide whether it's an elephant or a bear. One shortcut for this problem might be to sort the in...
b. This line lays on some end of the interval covered by the chunk — we update that end. In

Full text and comments »

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

207.
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...
minimum spanning tree is a subset of Delaunay edges. Degenerate Cases

Full text and comments »

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

208.
By chromate00, 22 months ago, In English
Codeforces Round 1000 (Div. 2) — Editorial <spoiler summary="Rating Predictions"> | Handles | A | B | C | D | E | F1 | F2 | | ---------------- | --- | ---- | ----------- | ----------- | ----------- | ---- | ----------- | | ~Proof_by_QED,2025-01-20 | 800 | 1000 | 1500 | 2200 | 2400 | 1800 | 2600 | | ~chromate00,2025-01-20 | 800 | 1100 | 1500 | 2100 | 2300 | 1800 | 2700 | | ~redpanda,2025-01-20 | 800 | 900 | 1400 | 2000 | 2400 | | | | ~larush,2025-01-20 | 800 | 1100 | 1600 | 2100 | | | | | ~FairyWinx,2025-01-20 | 800 | 900 | 1500 | 2000 | 2400 | 1800 | 2500 | | [user:priyanshu.p,2025-01-20] | 800 | 1200 | 1500 | 2000 | 2500 | 2000 | | | ~Intellegent,2025-01-20 | 800 | 1000 | 1400 | 2000 | 2200 | 2000 | 260...
; ll p=P[x]; ll b=nil; if(p==nil)return; if(x==L[p

Full text and comments »

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

209.
By fchirica, 13 years ago, In English
Codeforces Round #191 — Tutorial [problem:327A] I’ll present here the O(N ^ 3) algorithm, which is enough to solve this task. Then, for those interested, I’ll show a method to achieve O(N) complexity. **O(N ^ 3) method:** The first thing to observe is that constrains are slow enough to allow a brute force algorithm. Using brute force, I can calculate for each possible single move the number of 1s resulting after applying it and take maximum. For consider each move, I can just generate with 2 FOR loops all indices i, j such as i <= j. So far we have O(N ^ 2) complexity. Suppose I have now 2 fixed vaIues i and j. I need to calculate variable cnt (initially 0) representing the number of ones if I do the move. For do this, I choose another indice k to go in a[] array (taking O(N) time, making the total of O(N ^ 3) complexity). We have two cases: either k is in range [i, j] (this means i <= k AND k <= j) or not (if that condition is not met). If it’s in range, then it gets flipped, so we add to count variable 1 – ...
cells that are adjacent. Since S is connected, it is possible to build a tree that spans to all

Full text and comments »

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

210.
By Grey_Matter, 7 years ago, In English
[Tutorial] "1354D — Multiset" + A Gentle Introduction to Fenwick Trees (For the tutorial, skip to the second paragraph) The recently held [Educational Codeforces Round 87](https://codeforces.me/contest/1354) was full of controversies. The delay in its start, the overlap with Google Code Jam and then the many complaints that problems B, C1, C2 and D were all google-able! In particular, problem D was heavily criticised due to its strict memory limit which didn't help non-C++ users. The authors have given their reasons for this &mdash; to discourage the use of memory heavy data structures such as policy-based data structures (gnu pbds) and treaps. I personally found the contest to be "educational" indeed and I'm sure the same authors will now deliver even better contests in the future. Here I discuss the problem [D &mdash; Multiset](https://codeforces.me/contest/1354/problem/D) and some of the ways in which it could be solved. This blog is aimed at beginners. I hope to provide you with a gentle introduction to this fast and easy-to-implement data st...
overlap with Google Code Jam and then the many complaints that problems B, C1, C2 and D were all google

Full text and comments »

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

211.
By skywalkert, history, 5 years ago, In English
2019 Summer PtzCamp, Day 8: XIX Open Cup Onsite, Editorial This editorial corresponds to [contest:103652], a.k.a "Jingzhe Tang Contest 2", held on Sept. 1st, 2019. Moreover, this problem set is a selection of "CCPC-Wannafly Winter Camp 2018, Day 2 (Div. 1 & Div. 2)" held on Jan 30th, 2019. Feel free to comment on the tutorials listed in the following (with some follow-up questions left to readers). Hope you enjoy solving these problems. --- [problem:103652A] <spoiler summary="solution"> The number of updates can be counted as the number of ordered pairs $(u, v)$ such that when $u$ is going to be removed, there exists at least one path between $u$ and $v$. If the path between $u$ and $v$ is unique in the original graph, we can conclude that pair exists if $u$ is the first removed node on the path with respect to an order, and $\frac{1}{cnt(u, v)}$ of all possible orders would meet this condition, where $cnt(u, v)$ is the number of nodes on the unique path between $u$ and $v$ (inclusive). In other cases, there exist exactly tw...
subinterval is like $[a + b k^u, a + c k^u)$, where $a$ is a multiple of $k^{u + 1}$, and $b$, $c$ are

Full text and comments »

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

212.
By chithanh_nguyen, 6 months ago, In English
Duplicate Problem in Codeforces Round 1099 Div. 2? During [Codeforces Round 1099 (Div. 2),](https://codeforces.me/contest/2231), I noticed that Problem E appears to be very similar to an old problem from the Vietnamese Olympiad in Informatics 2021 (VOI 2021). The statement of Problem E can be summarized as follows: > Given a tree with $n$ vertices, count the number of triples $(a, b, c)$ such that $a < b < c$ and the number of vertices in the Steiner tree connecting $a$, $b$, and $c$ is exactly $d$. **Note.** Here, the Steiner tree of a set of vertices in a tree simply means the smallest connected subgraph containing all chosen vertices. **Constraints.** $3 \leq d \leq n \leq 2000$. However, in VOI 2021, Problem 2 had an almost identical idea. The original Vietnamese statement can be found [here](https://oj.vnoi.info/problem/voi21_comnet). Its statement can be summarized as follows: > Given a tree with $n$ vertices, count the number of ways to choose $k$ vertices such that the number of edges in the Steiner tree conne...
tree connecting $a$, $b$, and $c$ is exactly $d$.

Full text and comments »

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

213.
By uditgupta, history, 9 years ago, In English
In depth tutorial for Adding Arithmetic progression to range using Segment Tree wrt Problem Mister b and PR Shifts PLEASE INCREASE BRIGHTNESS IF IMAGES ARE NOT CLEARLY VISIBLE. POOR PHONE CAMERA . APOLOGIES ``` If your are familier with concept of Segment Trees with Lazy Update, Please go ahead and read the solution. If not, please do these two classic simple problems of Segment Trees with Lazy Update on Codchef. Then come back to this problem. This problem is a classic implementation of Segment Trees. Purpose of this tutorial is to help you find your solution and not just giving the solutions. ``` ~~~~~ Your code here... ~~~~~ * [Flipcoin Codechef](https://www.codechef.com/problems/FLIPCOIN) <br/> You can read my commented code for this flipcoin (https://www.codechef.com/viewsolution/4341486) * [MultQ3 Codechef](https://www.codechef.com/problems/MULTQ3) <br/> You can read my commented code for this MultQ3 (https://www.codechef.com/viewsolution/4342905) ![Alt text](https://user-images.githubusercontent.com/26462566/27768658-46f17eb6-5f36-11e7-8c24-d1ff7072dcd8.jp...
In depth tutorial for Adding Arithmetic progression to range using Segment Tree wrt Problem Mister, <b> Step 3 — Adding Arithmetic Progression to Segment Tree using Segment Tree with Lazy

Full text and comments »

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

214.
By saketh, 12 years ago, In English
Good Bye 2014 Tutorial ###[500A &mdash; New Year Transportation](http://codeforces.me/contest/500/problem/A) In this problem we are given a directed graph, and asked whether a particular vertex is reachable from vertex 1. It is possible to solve this by running a depth-first search starting from vertex 1. Since every vertex has at most one outgoing edge, it is possible to write the DFS as a simple loop. Some people used this to make [very short](http://codeforces.me/contest/500/submission/9307130) submissions. ###[500B &mdash; New Year Permutation](http://codeforces.me/contest/500/problem/B) Imagine a graph with one vertex for each entry in the permutation, and edges between pairs of swappable entries. It is easy to see that no matter how many swaps we make, no entry can end up in a location that is not in its connected component. We can also show that within any connected component, we can achieve any rearrangement of the entries that we wish. Since we want to make the lexicographically sm...
To figure out $|a|$ and $|b|$ for each $j$, we can root the tree arbitrarily and compute the depth

Full text and comments »

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

215.
By cgy4ever, 12 years ago, In English
Codeforces Round #290 Editorial **Update 1** : here are the reference solutions for this contest: 1. Div2-A: [http://ideone.com/JP1Ksj](http://ideone.com/JP1Ksj) 1. DIv2-B: [http://ideone.com/udz3bN](http://ideone.com/udz3bN) 1. Div2-C / Div1-A: [http://ideone.com/KVobNb](http://ideone.com/KVobNb) 1. Div2-D / Div1-B: [http://ideone.com/7MQqOm](http://ideone.com/7MQqOm) 1. Div2-E / Div1-C: [http://ideone.com/z3FsU2](http://ideone.com/z3FsU2) 1. Div1-D: [http://ideone.com/Y7j21a](http://ideone.com/Y7j21a) 1. Div1-E: [http://ideone.com/Orbacp](http://ideone.com/Orbacp) Note that for Div2-E / Div1-C, it is for the harder version: we need to handle '1' in the cycle. [problem:510A] There are 2 different ways to solve this kind of task: First one is to simulate the movement of the snake head, and you draw '#'s on the board. The code will look like: ~~~~~ head = (1, 1) repeat: repeat m-1 times: head move to right repeat 2 times: head move down repeat 2 times: head move down repeat m-1 ti...
/JP1Ksj](http://ideone.com/JP1Ksj) 1. DIv2-B: [http://ideone.com/udz3bN](http://ideone.com/udz3bN

Full text and comments »

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

216.
By ngk_manh, history, 5 years ago, In English
A simpler way to understand Li-Chao tree _Hi codeforces!_ _I was trying to learn about Li-Chao tree by some blog which i can find on gg (codeforces included). But there still some issue i was encountered while I trying to understood Li-Chao tree._ _Fortunately! I found that there's a simpler way to understand LC tree by thinking about another approach._ _So, I decide to write this blog for two reason :_ - _Archive_ - _Sharing_ _If you feel interesting about this topic, welcome!_ Prerequisite : ============== Did you read one of two blog ? : - https://robert1003.github.io/2020/02/06/li-chao-segment-tree.html - https://cp-algorithms.com/geometry/convex_hull_trick.html ### I.Which issue that me (or maybe someone) stuck in Li-Chao tree? These question are main motivation : - Why node on $Li-Chao$ $tree$ only store one line that is $min/max$ at point $mid$ which $mid$ is the middle point in segment $[L, R]$ which current node manage? - Why in $Query$ function we get $max$ result on way from root t...
A simpler way to understand Li-Chao tree, - If a line $y = a*x + b$ reach min in range $[L, R]$ among all line we added, then any path from

Full text and comments »

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

217.
By Theo830, 5 years ago, In English
Codeforces Round #747 (Div. 2) Editorial [problem:1594A] <spoiler summary="Hint"> See how $n = 2$ case works. </spoiler> <spoiler summary="Solution"> [tutorial:1594A] </spoiler> <spoiler summary="Code (C++)"> ~~~~~ #include <bits/stdc++.h> using namespace std; typedef long long ll; int main(void){ ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while(t--){ ll n; cin>>n; cout<<-n+1<<" "<<n<<endl; } } ~~~~~ </spoiler> [problem:1594B] <spoiler summary="Hint"> Think of the numbers in base $n$. </spoiler> <spoiler summary="Solution"> [tutorial:1594B] </spoiler> <spoiler summary="Code (C++)"> ~~~~~ #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll INF = 1e9+7; const ll MOD = 998244353; typedef pair<ll,ll> ii; #define iii pair<ll,ii> #define f(i,a,b) for(ll i = a;i < b;i++) #define pb push_back #define vll vector<ll> #define F first #define S second #define all(x) (x).begin(), (x).e...
; typedef pair ii; #define iii pair #define f(i,a,b) for(ll i = a;i < b;i++) #define pb

Full text and comments »

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

218.
By Baba, history, 10 years ago, In English
CodeCraft-17 and Codeforces Round #391 (Div. 1 + Div. 2, combined) Editorial [757A &mdash; Gotta Catch Em' All!](http://www.codeforces.com/contest/757/problem/A) ------------------ **Author:** [user:tanujkhattar,2017-01-13] **Testers:** [user:r.arora,2017-01-13] [user:born2rule,2017-01-13] **Expected complexity**: $\mathcal{O}(n)$ **Main idea**: Maintain counts of required characters. Since we are allowed to permute the string in any order to find the maximum occurences of the string "Bulbasaur", we simply keep the count of the letters 'B', 'u', 'l', 'b', 'a', 's', 'r'. Now the string "Bulbasaur" contains 1 'B', 2'u', 1 'l', 2'a', 1 's', 1'r' and 1 'b', thus the answer to the problem is Min(count('B'), count('b'), count('s'), count('r'), count('l'), count('a')/2, count('u')/2). You can maintain the counts using an array. **Corner Cases:** 1. Neglecting 'B' and while calculating the answer considering count('b')/2. 2. Considering a letter more than once ( 'a' and 'u' ). <spoiler summ...
) { scc(a,b,c); tree[a].pb(mp(b,c)); tree[b].pb(mp(a,c)); } unordered_map stmp

Full text and comments »

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

219.
By onufryw, history, 14 months ago, In English
The geometric solution to ICPC World Finals problem G (Lava Moat) In a few places I mentioned that besides the "standard" approaches to G (including the actual solution at the WF), there's a more geometric approach. Let me describe it here. First, a recap of the problem. We're given a rectangular area with a triangulation, with up to 50K vertices. Each of the triangulation vertices has a distinct height, and the height within triangles is linearly interpolated. We're asked to find the length of the shortest path from the east edge of the rectangle to the west that all lies on one height. Additionally, there are no triangulation vertices (except corners) on the east and west edges. First (this is common to both solutions), let's look at the set of points at a given height H. The intersection of this set with any triangle is either empty, a single vertex (the unique vertex of height H), or an interval. So, the set of points at height H forms a set of paths (which interesect triangulation triangles at intervals), and these paths can terminate by: ...
, we can run a tree search from A and from B to begin with.

Full text and comments »

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

220.
By karan_garg_12, 19 months ago, In English
Editorial — Dream in Code 25' — by IIIT Lucknow **[Dream In Code '25](https://codeforces.me/contestInvitation/d9fe41b44ce8688f482fa17563ca389c65711a69) – Editorial** *Hosted by Competitive Programming Club, IIIT Lucknow* --- ## Introduction Thank you to everyone who participated in **Dream In Code '25**, held on Codeforces Gym as part of Equinox 2025! We hope you enjoyed the problems and learned something new. This editorial includes detailed explanations and intended solutions for all the problems from the contest. --- ## Problems ### [A. Inversion Spectrum](https://codeforces.me/gym/602694/problem/A) **Setter:** [user:kunwarArjun,2025-05-05] <spoiler summary="Solution"> We need $$ \sum_{x \in X}\bigl(L(x)+R(x)\bigr) \;=\;2\times\bigl|\{\,i<j: X_i>X_j\}\bigr| $$ so it suffices to count the number of inversions in the exit array $X$ and multiply by two mod $10^9 + 7$. There exists a standard way to count inversions in the array using Merge Sort Algorithm. You can also impl...
For a perfect $b$-ary tree of height $h$, when $b=1$, the tree degenerates into a single chain. In

Full text and comments »

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