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.

Cpp

Last visit:  6 years ago
Registered:  15 years ago
2.
By nik_exists, 3 months ago, In English
Codeforces Round 1119 (Div. 3) <pre><code class="cpp">#include "codeforces.h" #include &lt;chrono&gt; #include &lt;vector&gt; using namespace std; using namespace std::chrono_literals; using namespace cf; int main() { Blog announcement("Codeforces Round 1119 (Div. 3)"); announcement &lt;&lt; "Hello Codeforces!\n"; announcement &lt;&lt; "I am delighted to invite you to participate in " &lt;&lt; </code>[contest:2259]<code class="cpp"> &lt;&lt; "!\n"; announcement &lt;&lt; "The problems were written and prepared by " &lt;&lt; </code>[user:nik_exists,2026-09-01]<code class="cpp"> &lt;&lt; ".\n\n"; announcement &lt;&lt; ContestInfo { .start_time = </code>[contest_time:2259]<code class="cpp">, .duration = 2h + 15min, .number_of_problems = 7, .subtasks = true // possibly not adjacent }; announcement &lt;&lt; RatingRules { .rated_for_rating_below = 1600, .unrated_registration_allowed = true, .trusted_max_rating_...
class="cpp">, .russian_translation = [user:Vladosiya,2026-09-01], you to participate in " << [contest:2259] << "!\n, #include "codeforces.h" #include <chrono> #include <vector>, ="cpp">, .duration = 2h + 15min, .number_of_problems = 7, .subtasks = true

Full text and comments »

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

3.
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...
relationships: - [tempo1.cpp ](https://github.com/NXIST-backup/algorithm_trans/blob, ![NaokiLH's blue_book/sh/tempo7.cpp](https://pic4.zhimg.com/80/v2, ![NaokiLH's blue_book/sh/tempo8.cpp](https://pic4.zhimg.com/80/v2, - [tempo1.cpp](https://github.com/NXIST-backup/algorithm_trans/blob, - [tempo8.cpp](https://github.com/NXIST-backup/algorithm_trans/blob, - [tempo9.cpp](https://github.com/NXIST-backup/algorithm_trans/blob

Full text and comments »

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

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

Full text and comments »

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

5.
By PinkieRabbit_buster, 3 years ago, In English
PinkieRabbit Cheated in Div. 1 Contest on Apr 27 I am writing to report an incident of cheating by PinkieRabbit during the recent contest 1965 on Codeforces. **PinkieRabbit asked help about problem D from others during the contest,** which is definitely against the contest rules. I have attached the evidence of the cheating behavior in the appendix, please read it. This evidence clearly shows the communications PinkieRabbit had with another person during the contest. It is a contest recording video published after contest by himself. As a former fan of PinkieRabbit, after seeing this video, I was shocked by how dishonest PinkieRabbit was. I believe such actions undermine the integrity of the competition and the platform as a whole. [user:win114514,2024-05-05] cheated by grouping up in contest 1905, finally punished by skipping. Therefore, I respectfully request that Codeforces take appropriate action against PinkieRabbit to maintain the fairness of the contests on Codeforces. He only cheated in one problem this round, so I sugg...
(P opens dev-cpp)

Full text and comments »

6.
By adamant, history, 19 months ago, In English
Complex FFT is not as bad as you think ... Probably. Hi everyone! As some of you _might_ already know, I don't like NTT. Primary reasons for this are: - I don't like modular arithmetic optimizations (Montgomery, etc). - I don't like NTT mods, and prefer good, old $10^9+7$. - I do like algebra of complex numbers. But, to my regret, the overwhelming mainstream in modern competitive programming is NTT. Primary reasons are: - It's allegedly faster. - It needs less memory. - It has no precision issues. - People don't like algebra of complex numbers. There is nothing I can do about the last, but today I'll address the first 3. Optimizing complex FFT was on my mind for quite some time, but I didn't really work on it _that much_ until the [blog](https://codeforces.me/blog/entry/142063) by [user:Qwerty1232,2025-04-24] on optimizing NTT has dropped, which motivated me to actually put some serious effort into this. In this blog, we will primarily focus on optimizations that are specific to complex arithmetic...
representable increment to $1.0$, which you get e.g. by [calling](https://en.cppreference.com/w/cpp, ://en.cppreference.com/w/cpp/experimental/simd) a [to be standardized](https://en.cppreference.com/w/cpp/header, ```cpp #include #include , ```cpp dx4 abs(dx4 a) { return a < 0 ? -a : a; }, ```cpp template using simd [[gnu::vector_size(len * sizeof(T))]] = T, ```cpp u64x4 montgomery_reduce(u64x4 x, u64x4 mod, u64x4 imod) { auto x_ninv = u64x4(u32x8(x, ```cpp using v4si [[gnu::vector_size(4 * sizeof(int))]] = int;, ```cpp void dot(cvector const& t) { size_t n = this->size(); exec_on_evals<1>(n / flen

Full text and comments »

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

7.
By pajenegod, history, 3 years ago, In English
Slowdown bug affecting C++ (64 bit) on Codeforces Yesterday, investigating [Strange TLE by cin using GNU C++20 (64)](https://codeforces.me/blog/entry/126573), I found an easy and reproducable way to trigger a slowdown bug that I believe has been plaguing Codeforces for some time now. So I'm making this blog to raise awarness of it. [user:MikeMirzayanov,2024-03-02], please take a look at this! Here is how to trigger the slowness bug: 1. Take any problem with a relatively large input on Codeforces ($2 \cdot 10^5$ ints is enough). 2. Take a random AC C++ submission that uses `std::cin`. 3. Add the line `vector<vector<int>> TLE(40000, vector<int>(7));` somewhere in global space. 4. Submit using either C++20(64 bit) or C++17(64 bit). 4. ??? 5. TLE For example take [user:Tourist,2024-03-02]'s solution to problem [problem:1936-D]. With the vector of death added to the code, it gets [TLE on TC5](https://codeforces.me/contest/1936/submission/249181295) (taking $> 5$ s). While without the deadly vector, the submission takes [15...
```cpp #include using namespace std;

Full text and comments »

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

8.
By YouKn0wWho, 4 years ago, In English
[Tutorial] Common Mistakes in Competitive Programming and How to Avoid Them One thing is for sure. You do make mistakes. I also make miskates and that's what makes us human. But what we can surely do is &mdash; to try to minimize the errors that we make throughout our life. I have compiled some of the mistakes that I made in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in C++ as it is the most used language for CP. **So, if you are new to CP, stick with me as you might don't wanna repeat the mistakes that I made when I was a beginner.** #### Mistake 1 Check out the following code: <spoiler summary="Code"> ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { int a = 1000'000'000,b = 1000'000'000; long long product = a * b; cout << product << '\n'; return 0; } ~~~~~ </spoiler> The outp...
[Typecast!](https://www.programiz.com/cpp-programming/type-conversion), [smash me](https://www.geeksforgeeks.org/endl-vs-n-in-cpp/) , `ios_base::sync_with_stdio(0)`. Check [this](https://en.cppreference.com/w/cpp /io/ios_base, also returns as `int`. Check [this](https://en.cppreference.com/w/cpp /algorithm/accumulate) out for, out [this](https://www.geeksforgeeks.org/memset-in-cpp/) to learn more., Check out [this](https://en.cppreference.com/w/cpp /language/operator_precedence) to learn more

Full text and comments »

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

9.
By adamant, 12 months ago, In English
Finding all primes up to half a billion in 83 ms Hi everyone! I was itching to apply SIMD in another problem, and this time my attention picked the following problem: --- **[Library Checker &mdash; Enumerate Primes](https://judge.yosupo.jp/problem/enumerate_primes)**. You are given $N$, $A$ and $B$. Find $\pi(N)$, and print all $p_{kA + B} \leq N$. It is guaranteed that $N \leq 5 \cdot 10^8$ and that the total number of primes to print is at most $10^6$. --- After some tweaking, I managed ([#336744](https://judge.yosupo.jp/submission/336744)) to reduce my time consumption in this problem to **83 ms** and memory consumption to **25 MiB**, which makes it a top-1 submission on the Library Checker. For comparison, the top-2 solution ([#148169](https://judge.yosupo.jp/submission/148169)) takes 172 ms and 15 MiB, meaning that what I describe here is a 2x improvement in terms of the running time. We can also compare it to what appears to be the state of the art of sieving, the [primesieve](https://github.com/kimwalisch/...
```cpp constexpr auto wheel_primes = std::array{2u, 3u, 5u, 7u, ```cpp template class, ```cpp #pragma GCC optimize("O3") #pragma GCC target("avx2"), ```cpp // Convert value to ordinal (index in compressed bit array) constexpr uint32_t, ```cpp void apply(vector &sieve, vector &pattern) { size_t N

Full text and comments »

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

10.
By MikeMirzayanov, 4 years ago, In English
Testlib: tests + CI Hello, Codeforces. I have wanted for a long time and now, finally, I sat down and did it. Many of you are familiar with my [Testlib](https://github.com/MikeMirzayanov/testlib) project. This is a library that helps you develop problems if you are using C++. In the case of problems for Codeforces rounds, its use is mandatory. It seems to me that it is almost a de facto standard for preparing materials for completely different olympiads and competitions. The history of С++-Testlib is almost lost in centuries, I published the first version in 2005. Nowadays, making edits to Testlib has become tricky. The code grown to thousands of lines, also it has too long a history. This increases the likelihood of accidentally changing some aspect of behavior, which will jeopardize the holding of a Codeforces round or another important competition. In short, making a bug in this code or changing behavior anywhere is highly discouraged. So I recently took the plunge and wrote some test...
* check that all cpp files in the repository are compiled (test `test-000_compile-all-cpp

Full text and comments »

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

11.
By pajenegod, 3 years ago, In English
Shallowest Decomposition Tree Hi Codeforces! Today I want to tell you about a really cool and relatively unknown technique that is reminiscent of Centroid decomposition, but at the same time is also completely different. The most common and well known decomposition tree algorithm out there is the centroid decomposition algorithm (running in $O(n \log n)$). It is a standard algorithm that is commonly used to solve tons of different kind of divide and conquer problems on trees. However, it turns out that there exists another closely related decomposition tree algorithm, that is in a sense optimal, and can be implemented to run in $O(n)$ time in around $30$ lines of code. I have chosen to call it the _Shallowest Decomposition Tree_. This blog will be all about the shallowest decomposition tree. Something I want to remark on before we start is that I did not invent this. However, very few people know about it. So I decided to make this blog in order to teach people about this super cool and relatively unknown tec...
```cpp #define log std::__lg #define ctz __builtin_ctz, ```cpp #define remover(vec, v) vec.erase(find(vec.begin(), vec.end(), v)), ```cpp def centroid_decomposition_tree(graph): n = len(graph) graph = [c[:] for c in, ```cpp def ctz(x): # Count trailing zeroes return (x & -x).bit_length() - 1

Full text and comments »

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

12.
By Zhtluo, history, 3 years ago, In English
All You Need is Randomly Guessing — How to Improve at Codeforces I hope [my previous blog](https://codeforces.me/blog/entry/126310) has convinced you that the best way to improve at Codeforces is to be more Russian, i.e. to improve your math capability. Unfortunately, humble mortals such as you and I are not gifted with the talent that esteemed Russian grandmasters such as 74TrAkToR had: _Surely, it is beneficial to have a code reference for many algorithms and data structures, but I also think that just superficially knowing the algorithm and maybe having implemented it once or twice before is sufficient to use it without a reference?_ _&mdash; Some other Codeforces grandmaster_ Therefore, in this blog I will explore the dark side of Russian-ness &mdash; randomly guessing &mdash; that is forsaken by every Russian grandmaster of the light side I know. However, it has been very helpful to me, and I hope that it serves you well, too. ## Example 1 I will start by using an example to demonstrate my thought process. This problem [1923C](h...
```cpp #include , ```cpp if ((i - 1 >= 0 && A[i - 1] > A[i]) || (i + 1 < N && A[i + 1] > A[i, ```cpp if (s - (r - l + 1) >= c && (r - l + 1) > 1) ```

Full text and comments »

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

13.
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...
```cpp #include #include #include , ```cpp T reduce(T a, T b) { return a + b; } ```, ```cpp __attribute__((target("sse4.1"))) __m128i reduce(__m128i a, __m128i b) { return, ```cpp const T identity_element = 0; ```, ```cpp const int N = 1 << 24; ```, ```cpp for(int i = N - 1; i >= 1; i--) { a[i] = reduce(a[i * 2], a[i * 2 + 1]); } a[0, ```cpp using T = uint32_t; ```

Full text and comments »

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

14.
By bitset, 3 years ago, In English
[Bugged] Dynamic Bitsets in GCC **UPD1: The bug has been [fixed](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115399). I'll update the blog again when the fix is on Codeforces.** **UPD: Unfortunately, left / right shift is bugged and doesn't clear bits [properly](https://codeforces.me/blog/entry/129454?#comment-1157481). It should be fine for other operations, but use it at your own risk.** <spoiler summary="Original Blog"> Hello sirs, you might know that Boost has a dynamically sized bitset class, but did you know that GCC also has one? Turns out it's included in the tr2 folder. You can simply include the `<tr2/dynamic_bitset>` header, and use it as `std::tr2::dynamic_bitset`. **Yes, it works on Codeforces.** Here's a code example to count triangles in a graph ([abc258_g](https://atcoder.jp/contests/abc258/tasks/abc258_g)): <spoiler summary="Code"> ```cpp #include <bits/stdc++.h> I wonder if it's possible to get GCC to fix it... using namespace std; #include <tr2/dynamic_bitset> using namespa...
```cpp #include I wonder if it's possible to get GCC to

Full text and comments »

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

15.
By adamant, 12 months ago, In English
Caveats of using optimize("Ofast") with target("avx2") Hi everyone! As you may know, it is often recommended to put these lines in your header: ```cpp #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2") ``` And they're usually great!<sup>[1]</sup> Well, until they aren't. For last 2-3 days I was riddled with the issue that [CP-Algorithms Library](https://lib.cp-algorithms.com) would perform very well on Library Checker, but whenever I tried to also apply it on Codeforces, it will fail to speed up the code, and sometimes would even make it much slower. As I finally figured out the cause, I'd like to write a blog about it, so that other people don't waste as much time. Mitigating these issues improved my running time on [problem:1975G] from **1530 ms** in [submission:316602668] to **203 ms** in [submission:352602775]. ##### Tl'dr See the "Takeaway" section at the bottom. [cut]<br> ##### Example problem I will reproduce the issue on a simple example: <hr> **[problem:911G]**: You are given an...
: ```cpp #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2") ``` And they're, ```cpp C:/Programs/gcc14-64-msys2/mingw64/include/c++/14.2.0/bits/allocator.h:182:7: error, ```cpp #pragma GCC optimize("O3") #include #pragma GCC target("avx2, ```cpp #pragma GCC optimize("O3") ... [[gnu::target("avx2")]] void solve() { .... } ```, ```cpp #pragma GCC optimize("Ofast") #include #pragma GCC target("avx2, ```cpp #pragma GCC optimize("Ofast") #pragma GCC target("avx2") ... ```, ```cpp #pragma GCC optimize("Ofast") ... [[gnu::target("avx2")]] void solve() { ... } ... ```, ```cpp #pragma GCC optimize("Ofast") ... while(q--) { int l, r, x, y; cin >> l >> r, ```cpp #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx2") ```, ```cpp #pragma GCC push_options #pragma GCC target("avx2") ... #pragma GCC pop_options ```, ```cpp ... auto update = [&](auto &i) __attribute__((always_inline)) { a[i] = a[i, ```cpp ... auto update = [&](auto &i) { a[i] = a[i] == ux ? uy : a[i

Full text and comments »

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

16.
By bicsi, history, 4 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 ...
```cpp const int INF = 1e9; struct BottleneckTree { vector link, cost; // all inserted, ```cpp long long total = 0; int r = bt.AddEdge(x, y, c); total += (r == INF) ? c : c - r

Full text and comments »

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

17.
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...
ALL occurrences](https://en.cppreference.com/w/cpp/container/multiset/erase) of `key` from the

Full text and comments »

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

18.
By BitByBit123, 4 months ago, In English
Suspicious Master yql0991666 Update on 8/18/2026: [user:yql0991666,2026-08-18] have cheated to become a Master. How can he still not be banned? Update: Congratulations to [user:yql0991666,2026-08-18], the CHEATER is disabled! Good job, Mike! I, [user:BitByBit123,2026-08-10], suspect that [user:yql0991666,2026-08-18] is a cheater. I would like to report some suspicious behaviors and request an investigation. # Update on 8/18/2026 [user:yql0991666,2026-08-18], could you explain [387437964](/contest/2257/submission/387437964 "Submission 387437964 by yql0991666") [387437988](/contest/2257/submission/387437988 "Submission 387437988 by yql0991666") how can you write 1.6KB code in 3 seconds? Looking at the code for Problem E, what kind of person would write such a long definition on a single line (the fourth line)? If you interpret this as a way to make the code more compact (by consolidating lines), then why are the assignment statements on lines 19 through 24 separated? The only explanation is that...
```cpp if(!(cin>>n))return 0; ```, ```cpp if(cin>>T) { while(T--) { /* ... */ } } ```

Full text and comments »

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

19.
By adamant, history, 3 years ago, In English
Implementing Dinitz on bipartite graphs Hi everyone! if you read about [Dinic algorithm](https://cp-algorithms.com/graph/dinic.html) on CP-Algorithms, especially the [section](https://cp-algorithms.com/graph/dinic.html#unit-networks) about how it works on unit networks, you'll notice that its supposed runtime for bipartite matching is $O(E \sqrt V)$, where $E$ is the total number of edges, and $V$ is the total number of vertices of a bipartite graph. Let's try it out on the following problem: **[Library Checker &mdash; matching on Bipartite Graph](https://judge.yosupo.jp/problem/bipartitematching)**. Given a bipartite graph with $V, E \leq 2 \cdot 10^5$, find the maximum matching. The implementation of the Dinitz algorithm that I typically use looks as follows: <spoiler summary="code"> ```cpp struct unit_network { int n; vector<int> to, cap; vector<vector<int>> g; unit_network(int n): n(n), g(n) {} void add_edge(int a, int b, int cp) { g[a].push_back(size(to)); ...
```cpp

Full text and comments »

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

20.
By Qwerty1232, 19 months ago, In English
Making NTT convolution 10x faster with avx2 > Text is also available on [github pages](https://piskareviv.github.io/blog_aux_ntt_1/) (formatting may look a bit cleaner there) > Thanks [user:alexxela12345,2025-05-05] for reviewing this blog Hello everyone! I want to share some of my thoughts and experiments on vectorizing NTT. I prefer NTT to real-valued FFT because of the imprecision of the latter. I use `avx2` because it is the most advanced vector extension supported by the majority of modern online judges (including Codeforces), as of 2024. And I have no idea how many bugs (already found two) and how much UB my code contains, at least it passes some kind of tests. ### Benchmark info All the benchmarks are performed on my `Ubuntu 22` `Intel i5-1135g7` laptop. I execute `cpupower frequency-set -d 3.0ghz -u 3.0ghz` before benchmarks to (attempt to) fix CPU frequency for better accuracy. Code is available at [github](https://github.com/piskareviv/blog_aux_ntt_1). You can try running all the benchmarks o...
```cpp // ... ``` -->, ```cpp // iterative order, ```cpp // n_inv = -inv(mod, 2^32) % 2^32, ```cpp // recursive order, ```cpp n_inv = 1; for (int i = 0; i < 5; i++) { n_inv *= 2 + n_inv * mod; } ```, ```cpp transform_forward(lg, a); transform_forward(lg, b);, ```cpp u32 shrink(u32 val) const { return std::min(val, val - mod); } ```, ```cpp u32x8 reduce(u64x4 x0246, u64x4 x1357) const { u64x4 x0246_ninv = _mm256_mul_epu32, ```cpp void butterfly_x2(u32& a, u32& b, u32 w) { u32 a1 = a, b1 = mul(b, w); a = add(a1, ```cpp void convolve_cyclic(int lg, u32* a, u32* b) { transform(lg, a); transform(lg, b, ```cpp void transform(int lg, u32* data) { for (int i = 0; i < (1 << lg); i++) { if, ```cpp void transform_forward(int lg, u32* data) { for (int k = 0; k < lg; k, ```cpp void transform_forward(int lg, u32* data) { for (int k = lg - 1; k >= 0; k

Full text and comments »

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

21.
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...
```c++ #include using namespace std;, for i in solutions: subprocess.run("g++ {}.cpp -o bin/{} -O2 -std=c++17".format(i,i),shell=True)

Full text and comments »

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

22.
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] ...
```cpp struct trygub_num { const int base = 1 << 30;

Full text and comments »

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

23.
By adamant, history, 18 months ago, In English
Finding a billion factorials in 60 ms with SIMD Hi everyone! _This blog is not about asymptotic optimization. Refer to [this comment](https://codeforces.me/blog/entry/63491?#comment-474051) for those._ There is a problem on Library Checker that goes as follows: <hr> **[Many Factorials](https://judge.yosupo.jp/problem/many_factorials)**: You're given $n_1,\dots,n_t$, where $t \leq 10^5$. For each $i$, find $n_i! \bmod M$, where $M = 998\;244\;353$. <hr> In this blog, we will learn how to solve this task in 61 ms, without precalc and **without** FFT. That's right, we will take the dumbest solution we can imagine, and will improve its constant factor until its decent enough. How much decent? Well, let's use the following baseline: <spoiler summary="Naive solution"> ```cpp vector<int> facts(vector<int> args) { const int block = 1 << 16; vector<int> args_per_block[mod / block + 1]; vector<int> res(size(args)); for(auto [i, x]: args | views::enumerate) { args_per_block[x / block].push_b...
```cpp template unsigned pow_fixed(int n, ```cpp using u64x4 [[gnu::vector_size(32, ```cpp vector bulk_invs(auto const& args, ```cpp vector facts(vector args) { const int

Full text and comments »

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

24.
By platelet, history, 4 years ago, In English
A modulo multiplication method that is 2x faster than compiler implementation > Given $k,m$ and $n$ numbers $a_i$, compute each $a_i\times k\bmod m$ I came up with a method that is almost twice as fast as the compiler implementation (when $m$ is a constant), which can effectively speed up the NTT and some DPs. First of all $$ a_i\times k\bmod m=\{a_i\times \frac km\}\times m\tag1 $$ where $\\{x\\}=x-\lfloor x\rfloor$ is the fractional part function. The principle of equation $(1)$ is that $a_i\times k\bmod m$ is only related to the fractional part of $\frac{a_i\times k}m$. Let $\frac km\approx\frac p{2^{64}}$, $p$ is either equal to $\lfloor\frac km\times2^{64}\rfloor$ or $\lceil\frac km\times2^{64}\rceil$, which one to choose, we will decide later, then $$ \begin{aligned} a_i\times k\bmod m&\approx\{a_i\times \frac p{2^{64}}\}\times m\\ &=\frac{a_ip\bmod 2^{64}}{2^{64}}\times m\\ &=\frac{a_ip\bmod 2^{64}\times m}{2^{64}} \end{aligned} \tag2 $$ There are two place we need to choose whether round up or down: - $p=\lfloor\frac km\t...
```cpp #include , ```cpp const int P = 998244353;

Full text and comments »

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

25.
By Errichto, 7 years ago, In English
Bitwise operations 2 — popcount & bitsets Part 1 ([link](https://codeforces.me/blog/entry/73490)) introduces basic bitwise operations. This is part 2 and it's mainly about (in)famous bitsets and example problems. Also, see links to very useful advanced stuff at the bottom. EDIT: here's [video version](https://www.youtube.com/watch?v=jqJ5s077OKo&list=PLl0KD3g-oDOHpWRyyGBUJ9jmul0lUOD80) of this blog (on my Youtube channel). ### Built-in functions In C++, `__builtin_popcount(x)` returns popcount of a number &mdash; the number of ones in the binary representation of $x$. Use `__builtin_popcountll(x)` for long longs. There are also `__builtin_clz` and `__builtin_ctz` (and their long long versions) for counting the number of leading or trailing zeros in a **positive** number. Read more [here](https://www.geeksforgeeks.org/builtin-functions-gcc-compiler/). Now, try to solve these two simple tasks in $O(1)$, then open the spoiler to check the solution: <spoiler summary="Compute the biggest power of 2 that is a divisor o...
++ reference https://en.cppreference.com/w/cpp/utility/bitset.

Full text and comments »

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

26.
By yummy, 2 years ago, In English
OpenAI o1 IOI submissions Hi Codeforces! I am a member of the reasoning team at OpenAI. We are especially excited to see your interest in the OpenAI o1 model launch, many of us being Codeforces users ourselves ([user:chenmark,2024-09-17], [user:meret,2024-09-17], [user:qwerty787788,2024-09-17], among others). Given the curiosity around the IOI results, we wanted to share the submissions that scored 362.14—above the gold medal threshold—from the [research blog post](https://openai.com/index/learning-to-reason-with-llms/) with you. These were the highest scoring among 10,000 submissions, so still a ways to go until top human performance, but we aspire to be there one day. The following C++ programs (including comments!) are written entirely by the model. Special thanks to [user:PavelKunyavskiy,2024-09-17] for maintaining the IOI mirror, which we used to check our scores. We hope you enjoy taking a look! **nile (100/100)** - [Submission](https://gist.github.com/aw31/2500acc418419e022021617170cbfc9f#file-n...
- [Submission](https://gist.github.com/aw31/2500acc418419e022021617170cbfc9f#file-message- cpp, - [Submission](https://gist.github.com/aw31/2500acc418419e022021617170cbfc9f#file-nile- cpp) (100, - [Submission 1](https://gist.github.com/aw31/2500acc418419e022021617170cbfc9f#file-mosaic_1- cpp, - [Submission 1](https://gist.github.com/aw31/2500acc418419e022021617170cbfc9f#file-sphinx_1- cpp, - [Submission 1](https://gist.github.com/aw31/2500acc418419e022021617170cbfc9f#file-tree_1-cpp ) (17, -cpp) (34/100; subtasks 1, 2, and 4) - [Submission 2](https://gist.github.com/aw31, -nile-cpp) (100/100) **message (79.64/100)** - [Submission](https://gist.github.com/aw31

Full text and comments »

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

27.
By adamant, history, 2 years ago, In English
std::generator and recursive lambdas in C++23 Hi everyone! As Codeforces now [supports C++23](https://codeforces.me/blog/entry/133046), it seems to be the right time to discuss some of the particularly interesting features. Some noteworthy ones that were already mentioned elsewhere include: - `views::zip` that maps two ranges into pairs `(A[i], B[i])`. - `views::enumerate` that maps range into pairs `(i, a[i])`. - `views::adjacent<k>` that maps range into tuples `(a[i], ..., a[i+k-1])`. - `views::cartesian_product` that maps two ranges into pairs `(A[i], B[j])` with all possible `i` and `j`. - Some more [specialized views](https://en.cppreference.com/w/cpp/ranges). - `ranges::to<Container>` that creates a container out of a view, e.g. `to<vector>(views::iota(0, n))`. - `ranges::fold_left` and `ranges::fold_right`, range versions of `std::accumulate`/`std::reduce`. - `insert_range`/`append_range`/`prepend_range`/`assign_range` for containers (not in GCC yet). - `print`/`println` for formatted printing (it seems t...
](https://en.cppreference.com/w/cpp/ranges). - `ranges::to` that creates a container out, ```cpp auto fact = [&](auto &&self, int x) -> int { return x ? x * self(self, x - 1, ```cpp auto fact = [&](int x) { return x ? x * fact(x - 1) : 1; }; ```, ```cpp auto fact = [&](this auto fact, int x) -> int { return x ? x * fact(x - 1) : 1, ```cpp std::generator factorize(uint64_t m) { if(is_prime(m, ```cpp vector factors; void factorize(uint64_t m) { if(is_prime(m

Full text and comments »

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

28.
By purplesyringa, history, 3 years ago, In English
This one weird trick will speed up your I/O 5x Just do this!! ```cpp #include <iostream> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); // Your code here int n; std::cin >> n; long long sum = 0; for (int i = 0; i < n; i++) { int x; std::cin >> x; sum += x; } std::cout << sum << std::endl; } ``` This will speed up your code so much you won't have to care about spending time in I/O anymore!! Give likez plz :3 [cut] <!-- --> --- Yeah, no. That's not how it works. We're still using `<iostream>`, and that means we have to rely on virtual inheritance and all the deoptimizations that follow from that. Even if you use a random "here's-my-fast-io-library" snippet from Codeforces, you still depend on block-buffered output. (Also, none of those libraries mesh well with floats.) In many cases, more CPU time is spent encoding/decoding numbers than interacting with the file system. Can we do better? ...Yeah, stupid que...
```cpp #include

Full text and comments »

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

29.
By Igorjan94, history, 9 years ago, In English
C++17, competitive programming edition C++17 is now [available](http://codeforces.me/blog/entry/57646) on codeforces, community [wants](http://codeforces.me/blog/entry/15643?#comment-413401) new edition of [C++ tricks](http://codeforces.me/blog/entry/15643) by [user:Swift,2018-02-19], so, let's start! Disclaimer: I have done only few examples of new features, which in my opinion are related to competitive programming. Feel free to comment and provide more real-world examples or ask to elaborate some features with more examples or explanations. ### Fold expressions * I think that everybody knows, what reduce or fold means, but a c++11 example: ``` vector<int> v = {1, 3, 5, 7}; int res = accumulate(v.begin(), v.end(), 0, [](int a, int b) { return a + b; }); cout << res; // 16 ``` * In C++17 there is also folding support for a template parameters list. It has the following syntax: ``` (pack op ...) (... op pack) (pack op ... op init) (init op ... op pack) ``` * For example, implement a template...
Compexity: $O(N \log(N + M))$ [doc](http://en.cppreference.com/w/cpp /container/map/merge), Complexity: $O(\log(N))$ [doc](http://en.cppreference.com/w/cpp /container/map/emplace), Complexity: extract(key): $O(\log(N))$ [doc](http://en.cppreference.com/w/cpp /container/map, Асимптотика: $O(N \log(N + M))$ [doc](http://en.cppreference.com/w/cpp /container/map/merge), Асимптотика: $O(\log(N))$ [doc](http://en.cppreference.com/w/cpp /container/map/emplace), Асимптотика: extract(key): $O(\log(N))$ [doc](http://en.cppreference.com/w/cpp /container/map

Full text and comments »

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

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

Full text and comments »

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

31.
By huangzirui, history, 4 years ago, In English
Editorial of Codeforces Round 796 [problem:1688A] Idea: [user:huangzirui,2022-06-03]. Solution: [user:huangzirui,2022-06-03]. Preparation: [user:huangzirui,2022-06-03]. Good problem Average problem Bad problem Did not solve <spoiler summary="Hint"> Consider $x=2^k$ and $x\ne 2^k$ separately. </spoiler> <spoiler summary="Solution"> Let $p_i$ be the $i$-th bit of $x$, $q_i$ be the $i$-th bit of $y$ (both indexed from $0$). $x\ \texttt{and}\ y > 0\Leftrightarrow \exists i,\ p_i= q_i = 1$. $x\ \texttt{xor}\ y > 0\Leftrightarrow \exists i,\ p_i\ne q_i$. To satisfy the first condition, find the minimum integer $k$ satisfying $p_k=1$, and assign $1$ to $q_k$. If $x\ne 2^k$, the second condition is satisfied now. Otherwise, find the minimum integer $j$ satisfying $p_j=0$, and assign $1$ to $q_j$. The time complexity is $O(1)$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include<bits/stdC++.h> ...
```cpp #include #include , ```cpp #include "bits/stdC++.h" using namespace std; int main, ```cpp #include #define ll long long using, ```cpp //这回只花了45min就打完了。 #include "bits/stdC++.h" using

Full text and comments »

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

32.
By maomao90, 5 years ago, In English
[Tutorial] Intuition on Slope Trick # Introduction As mentioned in my previous blog, I will be writing a tutorial about slope trick. Since there are already many blogs that goes through the concept of slope trick, my blog will focus more on the intuition behind coming up with the slope trick algorithm. Hence, if you do not know slope trick yet, I suggest that you read other slope trick blogs such as https://codeforces.me/blog/entry/47821 and https://codeforces.me/blog/entry/77298 before reading my blog. In the future explanation on the example problems, I will assume that the reader already knows the big idea behind slope trick but do not know how to motivate the solution. Great thanks to [user:errorgorn,2022-06-25] for proofreading and writing the section on convex convolution and merchant otter. # When to use slope trick? Most of the time, slope trick can be used to optimise dp functions in the form of $dp_{i, j} = \min(dp_{i - 1, j - 1}, dp_{i - 1, j} + A_i)$ or dp functions containing costs with abs...
```cpp #include using namespace std;, ```cpp const int MAXN = 100005;, ```cpp const long long INF = 1000000000000000005;, ```cpp int main() { int n; cin >> n; vector a(n); for (int i = 0; i < n; i

Full text and comments »

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

33.
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...
```cpp

Full text and comments »

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

34.
By adamant, history, 4 years ago, In English
Nimbers and Sprague-Grundy theorem Hi everyone! Today I'd like to write about the so-called Grundy numbers, or nimbers. I will start by providing a formal recap on the Sprague-Grundy theorem and then will advance to the topic that is rarely covered in competitive programming resources, that is I will write about nimber product and its meaning to the game theory. _I was asked to add the following to the blog: THANK SIR MASTER [user:ADAM_GS,2022-06-12] FOR GREAT AND VALUABLE REVIEW SIR_ ## Prerequisites Familiarity with the following concepts: - Basic [set theory](https://en.wikipedia.org/wiki/Set_theory) notion: [union](https://en.wikipedia.org/wiki/Union_%28set_theory%29), [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) and [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) of sets, [set of all subsets](https://en.wikipedia.org/wiki/Power_set) denoted as $2^A$, etc; - [Groups](https://en.wikipedia.org/wiki/Group_%28mathematics%29) and [fields](https://en.wiki...
```cpp #define int uint64_t

Full text and comments »

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

35.
By adamant, history, 3 years ago, In English
Efficient linear algebra for dummies Hi everyone! Some time ago I started developing a linear algebra library for Library Checker, and it turned out to be much fun. I'd like to write this blog to outline how one can implement a linalg library with a very good Library Checker performance, while also avoiding highly technical low-level details that are common in other similar blogs. Instead, we will learn a few high level ideas that will let us write a code that the compiler will then optimize using all these fancy techniques _in our stead_. Huge thanks to ~ToxicPie9,2024-05-08 and [user:magnus.hegdahl,2024-05-08] for explaining me some of the optimizations used here! You may also look into ~sslotin,2024-05-08's [entry](https://codeforces.me/blog/entry/101655) about how it can be sped up even further with more advanced and low-level techniques. ### Tl'dr. In this blog, I present my [matrix library](https://cp-algorithms.github.io/cp-algorithms-aux/cp-algo/linalg/matrix.hpp), which maintains a simple and elegant...
```cpp auto sort_classify(size_t lim, ```cpp std::pair find_pivot, ```cpp void add_scaled(vec const& b, base scale, `. - `submatrix(x, y)` takes two [std::slice](https://en.cppreference.com/w/cpp /numeric/valarray/slice), and, ```cpp // Subtract a's contribution from b void reduce(int &b, int a) { b = min(b, b ^ a, ```cpp enum gauss_mode {normal, reverse}; template matrix& gauss, ```cpp for(int i = 0; i < n; i++) { for(int k = 0; k < t; k++) { for(int j = 0; j, ```cpp for(size_t i = 0; i < n; i++) { for(size_t j = 0; j < m; j++) { for(size_t k, ```cpp for(size_t i = 0; i < n; i++) { for(size_t k = 0; k < t; k++) { for(size_t j, ```cpp for(size_t i = 0; i < n; i++) { for(size_t k = 0; k < t; k++) { C[i] += A[i, ```cpp matrix operator *(matrix const& b) const { matrix res(n, b.m); for(size_t i = 0, ```cpp size_t rank() const { if(n() > m()) { return T().rank(); } return, ```cpp template auto echelonize(size_t lim) { return gauss

Full text and comments »

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

36.
By adamant, history, 4 years ago, In English
A bit more of general ideas Hi everyone! Here's another collection of [little tricks](https://codeforces.me/blog/entry/100910) and [general ideas](https://codeforces.me/blog/entry/48417) that might make your life better (or maybe worse). Most of them are somewhat well-known, but perhaps would still be useful to someone. [cut]<hr> 1<!---->. **Evaluating polynomial modulo small prime $p$**. Given a polynomial $q(x)$, it may be evaluated in all possible $a \in \mathbb Z_p$ in $O(p \log p)$. To do this, compute $q(0)$ separately and use [chirp Z-transform](https://codeforces.me/blog/entry/83532) to compute $q(g^0), q(g^1), \dots, q(g^{p-2})$, where $g$ is a primitive root modulo $p$. _This method can be used to solve [problem:1054H]._ 2<!---->. **Generalized Euler theorem**. Let $a$ be a number, not necessarily co-prime with $m$, and $k > \log_2 m$. Then $$ a^k \equiv a^{\phi(m) + k \mod \phi(m)} \pmod m, $$ where $\phi(m)$ is Euler's totient. This follows from the Chinese remainder theor...
```cpp #define int int64_t

Full text and comments »

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

37.
By adamant, history, 2 years ago, In English
Fenwick bitset _Okay guys, I know it sounds like [Top 10 optimizations 2017- (collectors edition)](https://codeforces.me/blog/entry/53168) but hear me out_ Hi everyone! Recently, a problem **[ordered set](https://judge.yosupo.jp/problem/ordered_set)** has been added to Library Checker. Essentially, the problem asks you to maintain a set $\\{a_1,\dots,a_n\\}$ that supports the following operations: 1. Insert an element; 2. Erase an element; 3. Find the $k$-th smallest element; 4. Find the order index of an element; 5. Find lower bound of an element; 6. Find pre-upper bound of an element. Of course, all these [can be done](https://judge.yosupo.jp/submission/248515) with GNU policy-based data structures (pbds) in $O(\log n)$ per query, which leads to the shortest code. At the same time, it has a huge constant factor in practice, so a natural question arises. What would be the fastest way to solve this? One of my [earliest blogs](https://codeforces.me/blog/entry/11275) already addre...
```cpp auto compress_coords(auto &coords) { std::vector original, ```cpp size_t kth_set_bit(uint64_t x, size_t k) { return std::countr_zero(_pdep_u64, ```cpp size_t order_of_bit(uint64_t x, size_t k) { return k ? std::popcount(x << (64, ```cpp vector> coords; for(auto &it: a) { cin >> it

Full text and comments »

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

38.
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...
```cpp #include

Full text and comments »

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

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

Full text and comments »

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

40.
By Sugar_fan, 7 months ago, In English
Hacking Incorrect XOR Hashing with mt19937_64 Let us start with [problem:2014H]. A common solution assigns each value a random integer in $[0,L)$ and XORs the values in the interval. If every value appears an even number of times, the result is $0$. Otherwise, the result is $0$ with probability at most $1/L$. Inspired by the hack used on [submission:282284449] with xorshift, I found that many other submissions can also be hacked. The pitfalls of XOR hashing with `mt19937_64` do not seem to be widely known, so I wrote this blog. If we view both the internal state and the outputs as vectors over $\mathbb{F}_2$, then the $i$-th output of [`mt19937_64`](https://en.wikipedia.org/wiki/Mersenne_Twister) with initial state $x$ can be written as $o_i = BA^i x$, where $A$ is the state transition matrix and $B$ is the output matrix over $\mathbb{F}_2$. Thus, to make the XOR zero for every seed, it is enough to find a nonzero polynomial $p(t)=\sum_i a_i t^i$ such that $p(A)=0$. Then $$ \bigoplus_i a_i o_i = \bigoplus_i a_i BA^i...
[implementation](https://usaco.guide/gold/hashing?lang=cpp#implementation-2) is unsafe on common

Full text and comments »

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

41.
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...
Consider this code. ([Source](https://en.cppreference.com/w/cpp /language/eval_order.html))

Full text and comments »

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

42.
By adamant, 10 months ago, In English
Fastest bitwise convolutions Hi everyone! There are 3 roughly similar problems on Library Checker: - **[Bitwise Xor Convolution](https://judge.yosupo.jp/problem/bitwise_xor_convolution)** - **[Bitwise And Convolution](https://judge.yosupo.jp/problem/bitwise_and_convolution)** - **[Subset Convolution](https://judge.yosupo.jp/problem/subset_convolution)** All of them ask us to find $c_0, \dots, c_{2^n-1}$, where $$ c_k = \sum\limits_{i \circ j = k} a_i b_j, $$ where $\circ$ stands for bitwise xor, bitwise and, and "disjoint or" correspondingly. As of now, my submissions are the fastest one for all 3 problems, and in this blog I'd like to explain how it is achieved. XOR / AND convolutions are fairly simple, which is why my **30 ms** submissions are closely followed by others. However, for subset convolution, my submission uses **94 ms** with just **34 MiB**, while all other submissions (except the one by ~Qwerty1232,2026-02-15 on the second place, whose approach is similar to mine) use at least 3...
```cpp, ```cpp template void with_bit_floor(size_t n, auto &&callback) { if

Full text and comments »

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

43.
By Vladithur, history, 4 years ago, In English
Codeforces Round #842 (Div. 2) Editorial Hope you liked the problems! <spoiler summary="(from thanhchauns2) Before the round starts"> This is my second contest on Codeforces, inspiring coordination has been done for the last several months, cannot wait until the third round is released! <spoiler summary="Testers' predictions"> <table> <tr style ="background-color:#D3D3D3"> <th>Tester</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> <tr> <td>[user:xiaoziya,2022-12-13]</td> <td>900</td> <td>1000</td> <td>1400</td> <td>1800</td> <td>2100</td> <td>3000</td> </tr> <tr> <td>[user:feecle6418,2022-12-13]</td> <td>900</td> <td>1200</td> <td>1400</td> <td>1700</td> <td>2200</td> <td>2900</td> </tr> <tr> <td>[user:cadmiumky,2022-12-13]</td> <td>800</td> <td>1100</td> <td>1550</td> <td>1900</td> <td>2200</td> <td>-</td> </tr> <tr> <t...
```cpp #include #include , ```cpp /// Initialize permutation p[1..n], q[1..n] vector p(n + 1, -1), q(n + 1, -1);, ```cpp /// Storing position of each a[i] vector > b(n + 1); for (int i, ```cpp for (int i = 1; i <= n; ++i) { if (max(p[i], q[i]) != a[i, ```cpp for (int x = n, vp = n, vq = n; x >= 1; --x) { for (int i : b[x

Full text and comments »

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

44.
By sum, history, 3 years ago, In English
Editorial for Codeforces Round #919 (Div. 2) ##Information about the round <spoiler summary="Rating predictions (inspired by BucketPotato's editorial)"> | Person | A | B | C | D | E | F1 | F2 | |--------------------------------------------|------|------|------|------|------|------|------| | [user:sum,2024-01-13] | 800 | 1300 | 1500 | 1900 | 2000 | 2200 | 2900 | | [user:oursaco,2024-01-13] | 800 | 1100 | 1300 | 1600 | 1800 | 2100 | 3100 | | [user:omeganot,2024-01-13] | 900 | 1000 | 1400 | 1700 | 1900 | 2200 | 2800 | | [user:sriniv,2024-01-13] | | | | 1900 | 2000 | 1900 | | | [user:apple_method,2024-01-13] | 1000 | 1200 | 1400 | 1900 | 1600 | | | | [user:awesomeguy856,2024-01-13] | 800 | 1100 | 1400 | 1800 | 1900 | 2000 | 2800 | | [user:nonrice,2024-01-13] | 900 | 1000 | 1400 | 1750 | | | | | [user:null_aw...
```cpp #include

Full text and comments »

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

45.
By pajenegod, history, 3 years ago, In English
Tutorial: A simple O(n log n) polynomial multiplication algorithm Hi Codeforces! I have something exciting to tell you guys about today! I have recently come up with a really neat and simple recursive algorithm for multiplying polynomials in $O(n \log n)$ time. It is so neat and simple that I think it might possibly revolutionize the way that fast polynomial multiplication is taught and coded. You don't need to know anything about FFT to understand and implement this algorithm. Big thanks to [user:nor,2023-07-10], [user:c1729,2023-07-10] and [user:spheniscine,2023-07-10] for discussing the contents of the blog with me and comming up with ideas for how to improve the blog =). I've split this blog up into two parts. The first part is intended for anyone to be able to read and understand. The second part is advanced and goes into a ton of interesting ideas and concepts related to this algorithm. Prerequisite: Polynomial quotient and remainder, see [Wiki article] (https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Euclidean_divi...
```cpp const ll mod = (119 << 23) + 1;// = 998244353 // For p < 2^30 there is also e.g. 5 << 25

Full text and comments »

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

46.
By rui_er, history, 4 years ago, In English
Codeforces Round 864 (Div. 2) Editorial [problem:1797A] <spoiler summary="Tutorial"> [tutorial:1797A] </spoiler> <spoiler summary="Solution (rui_er)"> ```cpp //By: OIer rui_er #include <bits/stdc++.h> #define rep(x,y,z) for(int x=(y);x<=(z);x++) #define per(x,y,z) for(int x=(y);x>=(z);x--) #define debug(format...) fprintf(stderr, format) #define fileIO(s) do{freopen(s".in","r",stdin);freopen(s".out","w",stdout);}while(false) using namespace std; typedef long long ll; #define y1 y114514 int T, n, m, x1, y1, x2, y2; template<typename T> void chkmin(T& x, T y) {if(x > y) x = y;} template<typename T> void chkmax(T& x, T y) {if(x < y) x = y;} int f(int x, int y) { if((x == 1 || x == n) && (y == 1 || y == m)) return 2; if(x == 1 || x == n || y == 1 || y == m) return 3; return 4; } int main() { for(scanf("%d", &T);T;T--) { scanf("%d%d%d%d%d%d", &n, &m, &x1, &y1, &x2, &y2); printf("%d\n", min(f(x1, y1), f(x2, y2))); } return 0; } ``` </spoiler> [problem:1797B] <spoiler...
```cpp #include using namespace std;, ```cpp //By: OIer rui_er #include #define rep(x,y,z) for(int x=(y);x<=(z);x, ```cpp //By: OIer rui_er #include #define rep(x,y,z) for(ll x=(y);x<=(z);x

Full text and comments »

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

47.
By ouuan, history, 7 years ago, In English
Codeforces Round #564 Editorial [problem:1173A] Idea: [user:ouuan,2019-06-07] <spoiler summary="Tutorial"> Consider the two edge cases: all the $z$ persons upvote / all the $z$ persons downvote. If the results are the same in these two cases, it is the answer. Otherwise, the result is uncertain. </spoiler> <spoiler summary="Solution"> ```cpp #include <iostream> using namespace std; const char result[4] = {'+', '-', '0', '?'}; int solve(int x, int y) { return x == y ? 2 : x < y; } int main() { int x, y, z; cin >> x >> y >> z; cout << result[solve(x + z, y) == solve(x, y + z) ? solve(x, y) : 3]; return 0; } ``` </spoiler> [problem:1173B] Idea: [user:Sooke,2019-06-07] <spoiler summary="Tutorial"> - $m\ge\left\lfloor\frac n 2\right\rfloor+1$ Consider the chess pieces $1$ and $n$. $\because\begin{cases}|r_1-r_n|+|c_1-c_n|\ge n-1\\\\|r_1-r_n|\le m-1\\\\|c_1-c_n|\le m-1\end{cases}$ $\therefore m-1+m-1\ge n-1$ $\therefore m\ge\frac{n+1}2$ $\because m\...
```cpp

Full text and comments »

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

48.
By Imakf, history, 3 years ago, In English
Codeforces Round 906 Editorial [problem:1890A] idea: [user:Cocoly1990,2023-10-28] <spoiler summary="Solution"> [tutorial:1890A] </spoiler> <spoiler summary="Code"> By [user:Cocoly1990,2023-10-28] ~~~~~cpp // Time complexity O(nlogn) because of map #include <bits/stdc++.h> const int MX = 100 + 5; int main() { int t; std::cin >> t; while (t--) { int n; std::cin >> n; std::map<int ,int> occ; for (int i = 1; i <= n; ++i) { int x; std::cin >> x; occ[x]++; } if (occ.size() >= 3) puts("No"); else { if (std::abs(occ.begin()->second - occ.rbegin()->second) <= 1) { puts("Yes"); } else { puts("No"); } } } return 0; } ~~~~~ </spoiler> [problem:1890B] idea: [user:Imakf,2023-10-28] <spoiler summary="Solution"> [tutorial:1890B] </spoiler> <spoiler summary="Code"> By [user:Imakf,2023-10-28] ~~~~~cpp #include <bits/stdc++.h> bool ok(std::string s) { for ...
~~~~~cpp #include , ~~~~~cpp // Time complexity O(nlogn) because of map #include

Full text and comments »

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

49.
By Xellos, history, 7 months ago, In English
C++ quirks: variable shadowing C++ is a very permissive language. It'll let you write basically anything on the assumption that you know what you're doing... or let you shoot yourself in the foot if you don't. For example: ```cpp class C { int a; public: C(int a) : a{a} {} }; ``` It's a fairly common pattern in simple class design that's perfectly fine until it's not. The class member and constructor argument (c.arg.) have the same name. This is known as shadowing and compilers will warn you about it, though you need to use a flag `-Wshadow` that isn't included among `-Wall` or `-Wextra`. Another example of shadowing is ```cpp for(int i = 0; i < t; i++) for(int i = 0; i < n; i++) ``` which is fine if the first `i` isn't used for anything except making a loop (such as over test cases) but otherwise it's a solid source of bugs, especially if you "fix" it into `for(int j = 0; j < n; i++)`. ### How does shadowing work? First off, when can one variable shadow another? The standa...
```cpp #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #include "testlib.h, ```cpp class C { int a;, ```cpp for(int i = 0; i < t; i++) for(int i = 0; i < n; i++) ```

Full text and comments »

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

50.
By Qingyu, 6 months ago, In English
assert in GCC 16 As you might have heard, in the newest version of GCC, `<cassert>` is no longer included by `<bits/stdc++.h>` (you can view the change [here](https://github.com/gcc-mirror/gcc/commit/eaf6b40f761049ba4f74fd8bf1bc011e3c59c53b)). This means that the following code will now fail to compile: ```cpp #include <bits/stdc++.h> int main() { assert(1); } ``` <spoiler summary="Compilation Result"> ```plain test.cpp: In function ‘int main()’: test.cpp:4:5: error: ‘assert’ was not declared in this scope 4 | assert(1); | ^~~~~~ test.cpp:2:1: note: ‘assert’ is defined in header ‘<cassert>’; this is probably fixable by adding ‘#include <cassert>’ 1 | #include <bits/stdc++.h> +++ |+#include <cassert> 2 | ``` </spoiler> I noticed this issue during a recent compiler update on QOJ, where it broke a large number of older submissions. Because of this, I have reverted the compiler back to GCC 15.2.0 for now. Of course, this is not the first ti...
```cpp #include

Full text and comments »

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

51.
By cry, 4 years ago, In English
Codeforces Round 887 (Div 1, Div 2) Tutorial We hope you enjoyed these problems :) This contest has been in the works for almost a year. <spoiler summary = "About the Authors"> This round was mostly made possible by problemsetters from the [CerealCodes](https://www.cerealcodes.org/) initiative! CerealCodes is an organization based in the United States dedicated to running high quality competitive programming contests. You can check out our previous contest [here](https://codeforces.me/gym/103886). </spoiler> **UPD: D1D Editorial have been updated** **UPD 2: D1D Editorial now has images by [user:EmeraldBlock,2023-08-01]. As an apology gift for being so slow, the image generator is programmatic and available [here](https://artofproblemsolving.com/texer/codeforces).** #### [problem:1853A] Problem Credits: [user:buffering,2023-06-02] Analysis: [user:buffering,2023-06-02] <spoiler summary="Hint 1"> To make $a$ not sorted, we just need to pick one index $i$ so $a_i > a_{i + 1}$. How do we do this? </spoiler...
```cpp #include

Full text and comments »

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

52.
By Chilli, history, 7 years ago, In English
How to get actual 64 bit bitsets on Codeforces [Not Recommended] [Don't do this at your job] This blog post brought to you by [user:pajenegod,2020-05-16], [user:Narut,2020-05-16], and the rest of #constant-factor on the AC discord server. If you're interested in discussions like this, feel free to join! For the longest time, CF has constrained us to the tyranny of 32 bit C++. Not only has that slowed down our `long long` operations, it has also constrained us to a measly 32 bit constant factor reduction with bitsets! Let's take 2 pieces of equivalent code. For Loop: ~~~~ int a[MAXN], b[MAXN] for (int it = 0; it < iters; it++) for (int i = 0; i < MAXN; i++) if (a[i] & b[i]) cnt++; ~~~~ Bitset: ~~~~ bitset<MAXN> a, b; int cnt = 0; for (int it = 0; it < iters; it++) cnt += (a | b).count(); ~~~~ On Custom Invocation C++17 (32 bit) for MAXN=1e4 and iters=1e5, this boring for loop code runs in 3594 ms, while the equivalent bitset version runs in 104ms. 3594/104 is approximately 32. Ok, disappointing but makes sense. However, Mike...
defined](https://docs.microsoft.com/en-us/cpp/cpp /data-type-ranges?view=vs-2019) to be 32 bits

Full text and comments »

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

53.
By adamant, history, 2 years ago, In English
Double-ended eertree Hi everyone! Quite recently, a problem named [Palindromes in Deque](https://judge.yosupo.jp/problem/palindromes_in_deque) was added to the Library Checker that asks you to execute the following: 1. Add a character $c$ to the beginning or the end of a string $s$; 2. Remove a character from the beginning or the end of $s$. In-between the queries you also need to maintain the number of distinct palindromes, and the size of the largest prefix- and suffix-palindromes of the current string. The problem on Library Checker uses the approach from [Double-Ended Palindromic Trees](arxiv.org/abs/2210.02292) article by, presumably, [user:liouzhou_101,2024-06-10]. The paper is quite long though, so after briefly looking through introduction part to familiarize myself with their main concepts, I decided to do something a bit different than they did. In this blog, I will explain my approach. [cut] <hr> ### Recap First, let's briefly recall what an **eertree** is. If we consid...
```cpp #include

Full text and comments »

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

54.
By MikeMirzayanov, 8 years ago, translation, In English
Polygon: расширенные свойства ресурсов (грейдеры) Привет, Codeforces! Сегодня мной было выпущено важное обновление Polygon – частичная поддержка расширенных свойств ресурсов. Основная задача, которая решается этим обновлением – это поддержка разработки задач с грейдерами. В большинстве соревнований участникам необходимо предоставить полный код решения, включая чтение и вывод данных. Например, в раундах Codeforces вы решаете именно такие задач. Однако в ряде соревнований принят другой подход, где участнику просто необходимо реализовать нужную функцию или интерфейс. Например, в условии задачи может быть написано, что в решении на С++ надо реализовать функцию, которая имеет вот такой прототип `int sum(int a, int b)` и отослать реализацию. В таком случае, участнику достаточно отправить исходный код, который содержит реализацию этой функции. Затем при тестировании решения по такой задаче система должна скомпилировать и слинковать в единый исполняемый файл присланный участником файл и специальный подготовленный жюри файл, которы...
properties: that resources are applicable to `cpp.*` language group, that they are compile-time, расширенные свойства: что ресурсы применимы к языкам группы cpp.*, что это ресурсы времени

Full text and comments »

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

55.
By cry, 2 years ago, In English
Codeforces Round 965 (Div. 2) Editorial #### [problem:1998A] Problem Credits: [user:sum,2024-07-03] <br> Analysis: [user:cry,2024-07-03] <spoiler summary="Solution "> We can construct a solution by fixing all $x_i$ as $x_c$ or all $y_i$ as $y_c$. For example, if we fix all $y_i$ as $y_c$, then we can output pairs $(x_c-1, y_c), (x_c+1, y_c), (x_c-2, y_c), (x_c+2, y_c), ... , (x_c- \lfloor \frac{k}{2} \rfloor, y_c), (x_c + \lfloor \frac{k}{2} \rfloor, y_c)$. If the $k$ is odd, we need one more pair, so just output $(x_c, y_c)$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <iostream> using namespace std; int main() { int t; cin >> t; while(t--){ int x, y, k; cin >> x >> y >> k; for(int i = 0; i < k - k % 2; i++){ cout << x - (i & 1 ? 1 : -1) * (i / 2 + 1) << " " << y << "\n"; } if(k & 1){ cout << x << " " << y << "\n"; } } } ``` </spoiler> #### [problem:1998B] Problem Credits: [user:satyam343,2024-08-07] <br> Analysis: [user:cry,2024-07-03] <spoiler summ...
```cpp #include using namespace std;

Full text and comments »

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

56.
By adamant, history, 4 years ago, In English
Duality in linear programming. Part 2 — in competitive programming Hi everyone! Previously, I wrote a [general introduction](https://codeforces.me/blog/entry/105049) to linear programming duality. In this blog, I would like to write about several problems that could be solved with this technique. Familiarity with the first blog, or general knowledge of dual problems and how to construct them is generally expected to navigate in this one. Thanks to [user:brunovsky,2022-08-09] and [user:Golovanov399,2022-08-09] for problem suggestions! And particularly special thanks to [user:WeakestTopology,2022-08-09] for problem suggestions and all insightful discussions on the topic! [cut]<br> ### Dual construction mnemonics To simplify the construction of dual problems, let's recall the correspondence between constraints/variables in primal and dual problems. <spoiler summary="LP duality mnemonics"> Standard definition of LP dual problem looks like this: $$\begin{gather} \max\limits_x & c^\top x & \color{red}{\text{(maximization)}} & \ove...
-inverse_mst-cpp).

Full text and comments »

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

57.
By tiger2005, history, 3 years ago, In English
Introduction to CPLib (1) — Modern C++ Library for Test Data in CP You can refer to the second introduction post [here](https://codeforces.me/blog/entry/132343). CPLib is a library written in C++ for processing test data of competitive programming problems. It helps you write clear and efficient checkers, interactors, validators, and generators. CPLib uses "variable input template" as its major feature, provides friendly feedback for humans and backends, and is working hard to reach better compatibility and efficiency. You can get CPLib from [Github Repository](https://github.com/rindag-devs/cplib). The "single-header-snapshot" branch automatically updates single-header version of CPLib which is easy to use. Also, you can visit [cplib.aberter0x3f.top](https://cplib.aberter0x3f.top/) for more information. For regex-related questions, please refer to the [FAQ page](https://cplib.aberter0x3f.top/user-guide/faq). Here is a basic example of a checker using CPLib. For more examples, visit the links above. ```cpp #include "cplib.hpp" using ...
```cpp #include "cplib.hpp"

Full text and comments »

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

58.
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...
```cpp #include using namespace std; using ll, ```cpp #pragma GCC optimize("O3,unroll-loops")

Full text and comments »

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

59.
By LMydd0225, history, 2 years ago, In English
Codeforces Round 969 (Div. 1, Div. 2) Editorial [problem:2007A] <spoiler summary="Hint 1"> How many odd integers are there in a pair $(a, b, c)$? <spoiler summary="Answer"> At least 2. </spoiler> </spoiler> <spoiler summary="Hint 2"> It's always better to put **exactly $2$** odd integers and **exactly $1$** even integer in one pair of $(a, b, c)$. Is there a way to always choose optimal $(a, b, c)$? </spoiler> <spoiler summary="Hint 3"> Try consecutive integers. </spoiler> <spoiler summary="Tutorial"> [tutorial:2007A] </spoiler> <spoiler summary="Implementation"> ```py T = int(input()) for _ in range(T) : l, r = map(int, input().split()) print(((r + 1) // 2 - l // 2) // 2) ``` </spoiler> [problem:2007B] <spoiler summary="Hint"> Consider the position of the maximum value in one array. If there's multiple maximum values, choose any. What can you observe? <spoiler summary="Answer"> The position of the maximum value never changes. That is, if one element is the maximum value...
```cpp #include

Full text and comments »

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

60.
By Justice_Hui, history, 6 years ago, In English
[Tutorial] Easy Introduction to Kitamasa Method ### Before Reading... 1. Sorry for my poor English skill. 2. The propose of this article is "EASY" introduction to Kitamasa, so strict proofs can be omitted. ### What is Kitamasa Method? Kitamasa Method can compute N-th term of linear recurrence ($A_N = c_1A_{N-1} + c_2A_{N-2} + \cdots + c_KA_{N-K} = \sum_{i=1}^{K} c_iA_{N-i}$) in $O(K^2 \log N)$ or $O(K \log K \log N)$ when you manipulate polynomial with FFT. ### Let's transform the equation The goal of Kitamasa is find $d_i$, such that $A_N = \sum_{i=1}^{K} c_iA_{N-i} = \sum_{i=0}^{K-1} d_iA_i$. In other word, we can compute N-th term using **first K elements** instead of **before K elements**. If we can get $d_i$ in $T(N, K)$, we can compute N-th term in $O(T(N, K) + K)$ time. We can find $d_i$ just using $A_i \leftarrow (c_1A_{i-1} + c_2A_{i-2} + \cdots)$ . For example, let's think about $A_N = 2A_{N-1} + A_{N-2}$. ($c_1 = 2, c_2 = 1$). * $A_5 = 2A_4 + A_3$ * $A_5 = 2(2A_3 + A_2) + A_3 = 5A_3 + 2A_2$ * $A_5 ...
```cpp int Mod(ll x){ return (x %= MOD) < 0 ? x + MOD : x; }

Full text and comments »

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

61.
By ramchandra, 6 years ago, In English
Link-cut tree tutorial #### Introduction The link-cut tree data structure represents a rooted forest (a collection of rooted trees) and can perform the following operations in $O(\log n)$ amortized time (here, a node represents a vertex of the tree): * `link(par, child)`: Attach a tree (child) as a child of another tree's node (par). * `cut(node)`: Detach node's subtree from node's parent. * `find_root(node)`: Find the root of a node. * `lca(u, v)`: Find the least-common ancestor of two nodes. #### Structure: The represented forest (which is represented by the link-cut tree) is split into disjoint, vertical preferred paths composed of preferred edges linking each node with the latest child on the access path. On each preferred path we store a splay tree, sorted by increasing depth. You'll want to know splay trees for link-cut trees so see my [splay tree tutorial](https://codeforces.me/blog/entry/79524) for a tutorial on splay trees, which are a type of balanced binary search tree. Each ...
```cpp

Full text and comments »

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

62.
By Imakf, history, 4 years ago, In English
Codeforces Global Round 24 Editorial [problem:1764A] idea: [user:Cocoly1990,2022-11-26] <spoiler summary="Solution"> [tutorial:1764A] </spoiler> <spoiler summary="Code"> By [user:Imakf,2022-11-26] ~~~~~cpp #include <iostream> void solve(){ int n; std::cin >> n; for(int i = 1 ,nouse ; i <= n ; ++i){ std::cin >> nouse; } std::cout << "1 " << n << std::endl; } int main(){ int t; std::cin >> t; while(t--) solve(); return 0; } ~~~~~ </spoiler> [problem:1764B] idea: [user:waaitg,2022-11-26] <spoiler summary="Solution"> [tutorial:1764B] </spoiler> <spoiler summary="Code"> By [user:waaitg,2022-11-26] ~~~~~cpp #include<bits/stdc++.h> using namespace std; const int maxn=100005; int a[maxn]; int gcd(int a,int b){ return b==0?a:gcd(b,a%b); } int main(){ int t;scanf("%d",&t); while(t--){ int n;scanf("%d",&n); int tmp=0; for(int i=1;i<=n;++i){ scanf("%d",&a[i]); tmp=gcd(tmp,a[i]); } printf("%d\n",a...
~~~~~cpp #include

Full text and comments »

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

63.
By nik_exists, 3 months ago, In English
Codeforces Round 1119 (Div. 3) Editorial Thank y'all so much for participating! [problem:2259A] <spoiler summary="Solution"> [tutorial:2259A] </spoiler> <spoiler summary="Code"> ```cpp #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; string s; cin >> s; int ans = 0; for (int i = 0; i < n / k; i++) { bool has_non_nhoj_farm = false; for (int j = i * k; j < (i + 1) * k; j++) { if (s[j] == '0') has_non_nhoj_farm = true; } ans += !has_non_nhoj_farm; } cout << ans << "\n"; } } ``` </spoiler> <spoiler summary="Difficulty"> Too hard A bit on the harder side Good difficulty Easy Too easy </spoiler> <spoiler summary="Quality"> Amazing [likes:A2, ...
```cpp #include using namespace std;

Full text and comments »

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

64.
By cry, 2 years ago, In English
Codeforces Round 971 (Div. 4) Editorial Thanks for participating! Despite the round being unrated, we hope you've enjoyed the problemset. We put a lot of effort into this round :prayge: I want to give huge thanks to [user:Dominater069,2024-08-28] and [user:satyam343,2024-08-28] for their heavy contributions to the subtasks of G. If you're participating out of competition, we hope you enjoyed attempting these bonus subtasks. Otherwise, we hope you will enjoy upsolving them! [problem:2009A] Problem Credits: [user:cry,2024-08-28] <br> Analysis: [user:cry,2024-08-28] <spoiler summary="Solution "> We choose $c$ between $a$ and $b$ $(a \leq c \leq b)$. The distance is $(c - a) + (b - c) = b - a$. Note that the distance does not depend on the the position $c$ at all. </spoiler> <spoiler summary="Code (Python) (ntarsis30) "> ```py for _ in range(int(input())): a,b = map(int,input().split()) print(b-a) ``` </spoiler> [problem:2009B] Problem Credits: [user:cry,2024-08-28] <br> Analysis: [user:cry...
```cpp #include "bits/stdc++.h" #define int long, ```cpp #include "bits/stdc++.h" #pragma GCC optimize

Full text and comments »

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

65.
By Zhtluo, history, 3 years ago, In English
Guessforces Bestforces — How I Guessed My Way to GM ![Screenshot](https://zhtluo.com/cp/img/guessforces-bestforces/screenshot.png) *It turns out that randomly guessing works in Div. 1 too...* I have reached GM thanks to **randomly guessing**. **Ask me anything!** Since I have already argued in theory [how randomly guessing helps CF rating](https://codeforces.me/blog/entry/12687), I figured that I might as well compile a list of problems I guessed on my way to GM, to give some empirical evidence to all esteemed grandmasters before my rating falls off. So let us get started! ## [1975D &mdash; Paint the Tree](https://codeforces.me/contest/1975/problem/D) *Just solve the problem manually and claim it is the best solution.* Surely *it is.* <spoiler summary="Spoiler"> After playing a bit with the two pieces I found that I always make them collide. Fortunately, it suffices to randomly guess that the red piece and the blue piece will first travel to meet each other and then traverse the tree. I still have no idea why ...
```cpp #include

Full text and comments »

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

66.
By waaitg, history, 4 years ago, In English
Codeforces Round #808 Editorial [problem:1708A] idea: [user:Imakf,2022-07-16] <spoiler summary="Solution"> [tutorial:1708A] </spoiler> <spoiler summary="Code"> By [user:Imakf,2022-07-16] ~~~~~cpp #include <bits/stdc++.h> #define debug(...) fprintf(stderr ,__VA_ARGS__) #define LL long long const LL MOD = 1e9 + 7; const int MX = 1e5 + 23; int read(){ char k = getchar(); LL x = 0; while(k < '0' || k > '9') k = getchar(); while(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar(); return x; } int n ,a[MX]; void solve(){ n = read(); for(int i = 1 ; i <= n ; ++i) a[i] = read(); int ok = 1; for(int i = 1 ; i <= n ; ++i){ if(a[i] % a[1]) ok = false; } puts(ok ? "YES" : "NO"); } int main(){ int T = read(); while(T--) solve(); return 0; } ~~~~~ </spoiler> [problem:1708B] idea: [user:waaitg,2022-07-16] <spoiler summary="Solution"> [tutorial:1708B] </spoiler> <spoiler summary="Code"> By [user:Imakf,2022-07-16] ~~~~~cpp #...
~~~~~cpp #include

Full text and comments »

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

67.
By cry, 3 years ago, In English
CodeTON Round 8 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-03-10] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:oursaco,2024-03-30] | 800 | 1200 | 1500 | 1800 | 2200 | 2400 | 2800 | 2700 | 3400 | | [user:priyanshu.p,2024-03-30] | 800 | 1200 | 1300 | 1600 | 2200 | | | | | | [user:thescrasse,2024-03-30] | 800 | 1200 | 1400 | 1700 | 2100 | 2300 | 2900 | 2900 | 3500 | | [user:cry,2024-03-30] | 800 | 1000 | 1300 | 1700 | 2100 | 2200 | 2800 | 2900 | 3500 | | [user:buffering,2024-03-30] | 800 | 1000 | 1500 | 1900 | 2100 | 2200 | 2700 | 2800 | 3500 | | [user:jaggubandar,2024...
```cpp #include using namespace, ```cpp #ifndef LOCAL #pragma GCC optimize("O3,unroll-loops") #pragma GCC target("avx

Full text and comments »

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

68.
By Swistakk, history, 8 years ago, In English
Ultimate guide to TopCoder plugins Hi, I wanted to present to you guide on how you should set up TopCoder Arena in order to make competing in TC much more pleasant experience. Or at least guide how to do the same thing as I did which seem very comfortable to me compared to this big pain of competing in bare default Arena. In case you want to grab easy upvotes please leave here some joke about how I am jealous about ~Radewoosh,2018-08-16 getting insane boost in his contribution by writing his blogs, but the real reason is that I screwed my setup recently and needed to go through this painful and magical setup once again and it seems this information is very nontrivial and not available publicly in a known place (which I believe is one of reasons TopCoder is losing its popularity, but I hope thanks to this post I can give slight boost to it by settling up Arena problems once and for all for many people), so I wanted to share it with others. I want to express my sincere thanks to [user:tomasz.kociumaka,2018-08-16] for guid...
compile when expected output is an empty vector (in cpp), so you need to manually adjust that. For

Full text and comments »

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

69.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] The command line: how to read input from file without #ifdef and much more #### Introduction Instead of algorithms and math, I'll be doing something completely different here. There is something that has bothered me for a long time: people not understanding the tools they use to participate in contests and thus failing to take real advantage of them. And it all goes back to not understanding the command line. Some of you might say, "well surely, the command line is something obsolete and you're only clinging to it because you [insert ridiculous amateur-psychology here]?" No! The command line is not obsolete, and unless competitive programming becomes so mainstream that software vendors start writing professional-grade tools aimed specifically at us, it won't be. [cut] $~$ What is the command line? Any of these: ![ ](/predownloaded/bd/b6/bdb6c157b9b3ce5ae046c9064e469e0081f8c0fe.png) As you can see, it comes in many background colors and fonts, but the basic idea is always the same. It's a box you can type commands in, which it will ...
, they have no idea where their .cpp file actually is.

Full text and comments »

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

70.
By qwexd, 3 months ago, In English
Codeforces Round 1121 (Div. 2) Editorial # Codeforces Round 1121 — Editorial Thanks for participating! ### [problem:2264A] Problem by [user:qwexd,2026-09-13]. <spoiler summary="Hint"> Look at the elements that are not in the right position. Which of them must be selected? Can selecting any other element help? </spoiler> <spoiler summary="Solution"> Every element that is not in the right position has to be selected; otherwise, it never moves. Selecting an element that is already in the right position cannot help. For it to stay correct after the reversal, it has to be paired with itself, because its value occurs nowhere else in the permutation. Thus it can only be the middle selected element, and removing it changes nothing. So, if the array is already sorted, choose any one element. Otherwise, select exactly the misplaced elements and reverse them. The answer is `YES` if this sorts the array, and `NO` otherwise. If the misplaced positions are listed from left to right, the reversal pairs the...
```cpp #include

Full text and comments »

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

71.
By rui_er, 3 years ago, In English
Codeforces Round 942 (Div. 1, Div. 2) Editorial [problem:1972A] <spoiler summary="Hint 1"> Only add problems when they are needed. </spoiler> <spoiler summary="Tutorial"> [tutorial:1972A] </spoiler> <spoiler summary="Solution"> ```cpp //By: OIer rui_er #include <bits/stdc++.h> #define rep(x, y, z) for(int x = (y); x <= (z); ++x) #define per(x, y, z) for(int x = (y); x >= (z); --x) #define endl '\n' using namespace std; typedef long long ll; const int N = 105; int T, n, a[N], b[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); for(cin >> T; T; --T) { cin >> n; rep(i, 1, n) cin >> a[i]; rep(i, 1, n) cin >> b[i]; int diff = 0, ans = 0; rep(i, 1, n) { if(a[i - diff] > b[i]) { ++ans; ++diff; } } cout << ans << endl; } return 0; } ``` </spoiler> [problem:1972B] <spoiler summary="Hint 1"> Is there anything that _never...
```cpp #include

Full text and comments »

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

72.
By cry, 3 years ago, In English
Codeforces Round 952 (Div. 4) Editorial This was our first time setting a Div.4 contest. We sincerely hope you enjoyed the problems! #####[problem:1985A] Problem Credits: [user:cry,2024-05-26] <br/> Analysis: [user:cry,2024-05-26] <spoiler summary="Solution"> To swap the first character of the strings, you can use the built-in method std::swap in C++, or for each string, separate the first character from the rest of the string and concatenate it with the other string. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ string a, b; cin >> a >> b; swap(a[0], b[0]); cout << a << " " << b << endl; } } ``` </spoiler> #####[problem:1985B] Problem Credits: [user:cry,2024-05-26] <br/> Analysis: [user:cry,2024-05-26] <spoiler summary="Solution"> To maximize the number of multiples of $x$ less than $n$, it optimal to choose a small $x$, in this case, $2$. The only exception is $n = 3$, where it is op...
```cpp #include using namespace std;

Full text and comments »

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

73.
By Nanako, 4 years ago, In English
Good Bye 2022 -- Editorial ## [problem:1770A] Idea by [user:m_99,2022-12-30] <spoiler summary="Hint 1"> Exactly $n$ items out of of $a_1,\ldots,a_n,b_1,\ldots,b_m$ will remain on the whiteboard at the end. </spoiler> <spoiler summary="Hint 2"> $b_m$ will always remain on the board at the end. </spoiler> <spoiler summary="Hint 3"> Consider the case where $n=2$ and $m=2$. As we mentioned in hint 2, $b_2$ will always be written, but what about $b_1$? </spoiler> </details> <spoiler summary="Solution"> This problem can be solved naturally with a greedy algorithm &mdash; for $i = 1, 2, \dots, m$, we use $b_i$ to replace the minimal value among the current $a_1, a_2, \dots, a_n$. The time complexity is $O(nm)$ for each test case. Alternatively, we can first add $b_m$ to our final sum. For the remaining $(n+m-1)$ integers, we can freely pick $(n - 1)$ out of them and add it to our final sum. This is because if we want a certain $a_i$ to remain on the board at the end, we simply do not touch i...
```Cpp #include #define MULTI int _T; cin >> _T, ```Cpp #include #include , ```Cpp #include using namespace std

Full text and comments »

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

74.
By installb, history, 15 months ago, In English
Codeforces Round 1048 (Div. 1, Div. 2) Editorial [2139A &mdash; Maple and Multiplication](https://codeforces.me/contest/2139/problem/A) Idea: [user:installb,2025-09-08] Preparation: [user:installb,2025-09-08],[user:2014CAIS01,2025-09-08] <spoiler summary="Solution"> If $a=b$ we need $0$ steps. If $a$ can be divided by $b$, we only need $1$ step, which is to multiply $b$ by $\frac{a}{b}$. Same for the case when $b$ can be divided by $a$. Otherwise, we need at most $2$ steps. As both $a$ and $b$ are positive integers, we can first multiply $a$ by $b$ and then multiply $b$ by the original value of $a$. Both number will be equal to $a\times b$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; int solve(){ int a,b; cin >> a >> b; if(a == b) return 0; if(a % b == 0 || b % a == 0) return 1; return 2; } int main(){ ios::sync_with_stdio(false); int TC; cin >> TC; while(TC --){ cout <<...
```cpp #include using namespace std; typedef double db; const db pi = acos(-1.0, ```cpp #include using namespace std; typedef long long ll;, ```cpp #include using namespace std; void solve() { int n, q; cin

Full text and comments »

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

75.
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...
://codeforces.com/contest/573/submission/12760770 6. https://usaco.guide/adv/vectorization?lang=cpp

Full text and comments »

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

76.
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...
```cpp #include

Full text and comments »

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

77.
By defnotmee, history, 5 years ago, In English
Bizarre slowdown when using cin on a 64-bit compiler Hello codeforces! I've come to ask help in a time of great mystery. I was helping to debug a [problem](https://codeforces.me/contest/796/problem/D) where the code would [pass the 2s TL when on a 64-bit compiler](https://codeforces.me/contest/796/submission/142675925) but would get [confortably under 1s on a 32-bit one](https://codeforces.me/contest/796/submission/142679215) when some really bizarre things started to happen. First, pinning down where the problematic parts were, it turns out this was the thing consuming practically the whole time limit: ```cpp set<ll> s; for (int i(0); i < k; ++i) { int pp; cin >> pp; s.insert(pp); } ``` Im not joking. Also k <= 3e5 btw. It really shouldnt be a big deal, and normally that part should take [less than 140ms](https://codeforces.me/contest/796/submission/142729216), but both on [C++20 (64)](https://codeforces.me/contest/796/submission/142729195) and [C++17 (64)](https://codeforces.me/contest/796/submis...
```cpp set s; for (int i(0); i < k; ++i) { int pp; cin >> pp; s.insert(pp); } ```

Full text and comments »

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

78.
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...
```cpp=1 #include using namespace std;

Full text and comments »

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

79.
By dendi239, history, 6 years ago, In English
Micro- and macro-management for your next cpp source: General tips'n'tricks Hello, Codeforces! In this series of articles, I would like to tell you about tips'n'tricks I use in C++ sources. Some of them require a strong C++ background, some not, but all of them are aimed to reduce the time you spend on basic things like reading input/debugging/etc, so it might be useful for your next template. This part is dedicated to some basic tips (and probably should've been the first part but it's not ¯\\_(ツ)_/¯). <spoiler summary="TL;DR"> Full code: ~~~~ #include <bits/stdc++.h> using namespace std; using i64 = int64_t; using f80 = long double; using Str = string; template <class T> using Vec = vector<T>; template <class K, class V> using UM = unordered_map<K, V>; template <class T> auto &operator>>(istream &is, vector<T> &xs) { for (auto &x : xs) is >> x; return is; } namespace io { template <class ...As> auto &read(As &...as) { return (cin >> ... >> as); } template <class ...As> auto &log(const As &...as) { return ((cerr << " " << as...
Micro- and macro-management for your next cpp source: General tips'n'tricks, machine: that happens because `bits/stdc++.h` is a feature of GCC, not the entirecpp standard, ://en.cppreference.com/w/cpp/language/lambda), let me show the use case:

Full text and comments »

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

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

Full text and comments »

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

81.
By feecIe6418, history, 20 months ago, In English
InfOJ April Fools Day Contest 2025 (On April 5th) Hello Codeforces! I am glad to invite you to [InfOJ April Fools Day Contest 2025](http://119.27.163.117/contest/28) (IAFDC for short) which will start on [April 5th 2025, 19:00 UTC+8](https://www.timeanddate.com/worldclock/fixedtime.html?day=5&month=4&year=2025&hour=19&min=00&sec=0&p1=33). The problem setters are me and [user:gyh20,2025-03-22]. This is not a joke: the contest will really be held! The contest will last for 2.5 hours with 10 tasks for you to solve. All problems are worth 100 points, and the contest will be in IOI mode with standings. You can see the past problems [here](http://119.27.163.117/contests). ## Why is April Fool's Contest not on April Fools Day? From the year 2023, the contest has always been held on April 5th, to match the Tomb Sweeping Day's break in Chinese schools. ## Language of Problem Statements We will provide English statements for all problems. However, in the past several years, only Chinese statements are available. If you wan...
```cpp #include "llm.h"

Full text and comments »

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

82.
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...
~~~~cpp #include , ~~~~~cpp #include , ~~~~cpp #include using namespace std; #define int long long

Full text and comments »

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

83.
By meooow, 8 years ago, In English
[Tutorial] Convex Hull Trick — Geometry being useful ### The problem Let us consider the problem where we need to quickly calculate the following over some set $S$ of $j$ for some value $x$. $$\max_{j \in S} \{m_j \cdot x + c_j\}$$ Additionally, insertion of new $j$ into $S$ must also be efficient. This will most likely be encountered with DP problems. For example, the recent problem [problem:1083E] from Round #526 has the following DP formulation after sorting the rectangles by $x$. $$f(i) = x_i \cdot y_i - a_i + \max_{1 \le j < i}\{-x_j \cdot y_i + f(j)\}$$ The problem requires quick calculation of the above define maximum for each index $i$. How can this be done? ### The idea Notice the special form of $m_j \cdot x + c_j$. This is identical to the equation of a straight line with slope $m_j$ and Y-intercept $c_j$. So the problem is equivalent to being given a set of lines and asked for the maximum $y$ value any of those lines can give at a particular $x$. If you draw a bunch of straight lines on a plane, you'll...
```cpp struct line { long long m, c

Full text and comments »

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

84.
By zltzlt, 20 months ago, In English
Teza Round 1 (Codeforces Round 1015, Div. 1 + Div. 2) Editorial Thanks for participation! [problem:2084A] Idea: [user: zltzlt, 2025-3-28] <spoiler summary="Hint 1"> By observing the example, we can see that there is no solution when $n$ is even. </spoiler> <spoiler summary="Solution"> [tutorial:2084A] </spoiler> <spoiler summary="Implementation"> ```cpp #include <bits/stdc++.h> using namespace std; int main() { int T, n; cin >> T; while (T--) { cin >> n; if (n & 1) { cout << n << ' '; for (int i = 1; i < n; ++i) { cout << i << " \n"[i == n - 1]; } } else { cout << "-1\n"; } } return 0; } ``` </spoiler> [problem:2084B] Idea: [user: zltzlt, 2025-3-28] <spoiler summary="Hint 1"> Consider the position of the minimum value after rearranging the sequence. </spoiler> <spoiler summary="Hint 2"> What kind of numbers should be placed on the $\min$ side, and what kind should be placed on the $\gcd$ side? </spoiler> <spoiler summary="Solution"> [tutorial:2084B] </spoile...
```cpp #include using namespace std

Full text and comments »

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

85.
By Error_Yuan, history, 2 years ago, In English
Refact.ai Match 1 (Codeforces Round 985) Editorial Thank you all for participating in the round! We apologize for the wrong checker in problem E at the beginning of the contest, as well as the weak tests in problem B. To be honest, all the hacked submissions have similar logic and codes in B, which made me suspicious. Anyway, we are sorry for the inconvenience! >_< <spoiler summary="Rating Predictions"> | |A|B|C|D|E|F|G|H|I| |:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:|:--:| |[user:Error_Yuan,2024-11-7]|800|1200|**1600**|**2100**|**2300**|2600|**3000**|3400|**3500**| |[user:sszcdjr,2024-11-7]|800|1100|1600|2000|2300|**2600**|2900|**3300**|3500| |[user:wyrqwq,2024-11-7]|800|**1000**|1400|2200|**2300**|2600|**3000**|3500|3500| |[user:Otomachi_Una,2024-11-7]|**800**|1000|1600|2200|2400|2600|3200|3500|3500| |[user:dxqwq,2024-11-7]|900|1100|1700|2200|2400|2600|3200|3500|3500| |[user:Kubic,2024-11-7]|800|1000|1600|2400|2200|2800|3000|3500|3300| |[user:wsc2008qwq,2024-11-7]|800|1100|1600|1900|2200|2700|3100| | | |[user:chroma...
```cpp #include #define all(s, ```cpp #include using namespace std

Full text and comments »

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

86.
By eren__, 19 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):...
```cpp #include

Full text and comments »

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

87.
By cry, 15 months ago, In English
Codeforces Round 1050 (Div. 4) Editorial #### [problem:2148A] <spoiler summary="Solution (written by cry)"> Notice that if we pair each odd-indexed element with an even-indexed element, it sums to $0$. Therefore, our strategy is to pair the $2i$'th element with the $(2i+1)$th element until there are no more elements to pair. Note that if $n$ is odd, then there exists an unpaired odd element at the end. In this case, the answer will just be that ending element, which will be $x$. Otherwise, when $n$ is even, we paired every element perfectly and the sum will be $0$. Time complexity: $\mathcal{O}(1)$ per test case. </spoiler> <spoiler summary="Code (C++) (MikeMirzayanov)"> ```cpp #include <bits/stdc++.h> using namespace std; #define forn(i, n) for (int i = 0; i < int(n); i++) int main() { int t; cin >> t; forn(tt, t) { int x, n; cin >> x >> n; if (n % 2 == 0) cout << 0; else cout << x; cout << endl; } } ``` </...
```cpp #include

Full text and comments »

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

88.
By StarSilk, history, 22 months ago, In English
Ethflow Round 1 (Codeforces Round 1001, Div. 1 + Div. 2) Editorial [problem:2062A] Idea: [user:StarSilk,2025-01-23]. Solution: [user:StarSilk,2025-01-23]. Preparation: [user:SSerxhs,2025-01-23], [user:StarSilk,2025-01-23]. <spoiler summary="Rate this problem"> Good problem Average problem Bad problem Did not solve </spoiler> <spoiler summary="Solution"> [tutorial:2062A] </spoiler> <spoiler summary="Code (C++)"> ```cpp #include<bits/stdc++.h> using namespace std; string s; int main(){ ios::sync_with_stdio(false),cin.tie(0); int T,n,i,ans; for(cin>>T;T>0;T--) { cin>>s;n=s.size(); ans=0; for(i=0;i<n;i++)ans+=s[i]-'0'; cout<<ans<<'\n'; } return 0; } ``` </spoiler> <spoiler summary="Code (Python)"> ```python for _ in range(int(input())): print(input().count('1')) ``` </spoiler> [problem:2062B] Idea: [user:StarSilk,2025-01-23]. Solution: [user:StarSilk,2025-01-23]. Preparation: [user:SSerxhs,2025-01-23], [user:...
```cpp #include using namespace std;

Full text and comments »

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

89.
By lnishan, 11 years ago, In English
An awesome list for competitive programming! This is a project I started from late January 2016. My motive is that: Although there's fantastic information out there, I think they're still spread all over the place. Therefore, in my opinion it would probably be cool if there's an [awesome list](https://github.com/sindresorhus/awesome) for competitive programming! ( *It's now featured on the main list!* ) I'm actively updating the list here: [https://github.com/lnishan/awesome-competitive-programming](https://github.com/lnishan/awesome-competitive-programming) # Awesome Competitive Programming [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) A curated list of awesome `Competitive Programming`, `Algorithm` and `Data Structure` resources. Created with a view to connecting people to information, this list below contains a complete collection of all the fantastic resources I've collected over the course of my 11...
/awesome-math](https://github.com/rossant/awesome-math) | | C++ | [fffaraz/awesome-cpp](https, ://hyperpolyglot.org/cpp) | A detailed side-by-side reference sheet for common syntaxes. |

Full text and comments »

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

90.
By rivalq, 5 years ago, In English
Codeforces Round #793 (Div. 2) Editorial I hope you all liked the round. Please share your feedback in the comments section. [1682A &mdash; Palindromic Indices](https://codeforces.me/contest/1682/problem/A) =============================== <spoiler summary = "Hint"> Read the statement carefully!! The given string is a **palindrome**. </spoiler> <spoiler summary = "Tutorial"> Let's remove some index $i$ from the first half of $s$ and check whether the resulting string is a palindrome or not, the other half has the same approach. The prefix of length $i-1$ already matches with the suffix of the same length because the initial string was a palindrome, so we just need to check if $t = s[i + 1 \ldots n - i + 1]$ is a palindrome. For $t$ to be a palindrome, $s_{n - i + 1}$ should be equal to $s_{i + 1}$ which was initially equal to $s_{n - i}$, again which should be equal to $s_{i + 2}$ and this goes on. Here we can see that $s_i = s_{i + 1} \ldots = s_{n - i + 1}$. So the answer is simply equal to the number ...
```cpp #include using namespace std ;

Full text and comments »

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

91.
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...
```cpp #include using namespace std; typedef long long, ```cpp // Problem: C. LuoTianyi and the Theater // Contest: Codeforces

Full text and comments »

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

92.
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...
```cpp int

Full text and comments »

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

93.
By Sersawy, history, 12 months ago, In English
[Tutorial] Monotonic Stack Optimization for "Last-Segment" DP I recently encountered several problems that looked like standard $O(N^2)$ Dynamic Programming but required a faster solution. I noticed a recurring theme: using **Monotonic Stack** to optimize transitions dependent on range statistics (like min/max/GCD). Sometimes these problems can also be solved using the convex hull trick, but the stack-based approach is often much simpler. However, not all "Monotone Stack DPs" are the same. Sometimes we use the stack to optimize the **transition loop**, and other times we use it to optimize the **input array itself**. In this post, I will explain the intuition behind these two distinct patterns. ----- ## Pattern 1: Optimizing the Transition **Target:** Problems where the cost function behaves like a "Step Function." ### The Problem We are dealing with a 1D DP recurrence of the form: $$dp[i] = \min_{0 \le j < i} \{ dp[j] + \text{cost}(j+1 \dots i) \}$$ Where $\text{cost}(j+1 \dots i)$ depends on a range statistic (e.g., ...
```cpp vector> st; // {val, dp}

Full text and comments »

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

94.
By dendi239, 6 years ago, In English
Micro- and macro-management for your next cpp source: Reading Hello, codeforces! I would like to tell you about tips'n'tricks I use in C++ sources. Some of them require a strong C++ background, some not, but all of them are aimed to reduce the time you spend on basic things like reading input/debugging/etc, so it might be useful for your next template. After a few hours of working on this post, I decided to split it into several more focused articles -- it's so hard to write about everything I planned, cover all nuances, and don't make it super-big. For simple tasks, you may need to write very little code solving the problem and the biggest part of the source will be about reading values. Thus, declaring and reading variables seem like things that need to be simplified. Is there a way to shorten the following? ~~~~~~ int n, m, k, t, q; cin >> n >> m >> k >> t >> q; ~~~~~~ There're a few ways, more or less flexible, I'll show one of them, you can find another, for example, [here](https://codeforces.me/blog/entry/74684): ~~~...
Micro- and macro-management for your next cpp source: Reading, ://en.cppreference.com/w/cpp/language/parameter_pack) and [macros](https://en.wikipedia.org/wiki/Variadic_macro, ://en.cppreference.com/w/cpp/language/parameter_pack):

Full text and comments »

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

95.
By awang11, 23 months ago, In English
Codeforces Round 996 (Div. 2) Editorial Hope you enjoyed the problems! **UPD 1:** Added implementations! **UPD 2:** It seems my wording for the solution to C is not the best, and it is causing some confusion. I've updated it to be better! **UPD 3:** Implementation links didn't work for some reason, so I've just added the code directly. [problem:2055A] <spoiler summary="Hint 1"> Look at the distance between the frogs. </spoiler> <spoiler summary="Solution"> Notice that regardless of how the players move, the difference between the numbers of the lilypads the two players are standing on always alternates even and odd, depending on the starting configuration. Then, the key observation is that exactly one player has the following winning strategy: * Walk towards the other player, and do not stop until they are forced onto lilypad $1$ or $n$. For instance, if Alice and Bob start on lilypads with the same parity, Bob cannot stop Alice from advancing towards him. This is because at the start of Alice's ...
~~~~~cpp #include

Full text and comments »

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

96.
By nifeshe, 23 months ago, In English
Codeforces Round #997 (Div. 2) Editorial <spoiler summary = "Rating predictions"> | | A | B | C | D | E | F1 | F2 | |----------------------|------|-----------|---------|------|------|------|---------------| | [user:nifeshe,2025-01-17] | 800 | 1200 | 1400 | 2000 | 2200 | 2700 | 2800 | | [user:Intellegent,2025-01-17] | 800 | 1200 | 1600 | 2000 | 2300 | | | | [user:mwen,2025-01-17] | 800 | 1200 | 1300 | 1800 | 2300 | | | | [user:Markadiusz,2025-01-17] | 800 | 1100 | 1300 | 1800 | 2300 | 2500 | 2800 | | [user:_istil,2025-01-17] | 800 | | [1600, 2000] | 2000 | | 2400 | 2700 | | [user:hazzlek,2025-01-17] | 1000 | 1200 | 1500 | 2000 | 2100 | | | | [user:iLoveIOI,2025-01-17] | 800 | 1100 | 1600 | 2000 | 2400 | | | | [user:A_G,2025-01-17] | 800 | 1100 ...
```cpp #include

Full text and comments »

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

97.
By ouuan, history, 7 years ago, In English
Maintain subtree information using link/cut trees In the tutorial of [problem:1172E], I didn't write things on how to maintain subtree information, because I thought it was a popular trick. However, through [user:tmwilliamlin168,2019-06-12]'s [comment](/blog/entry/67511?#comment-518361), I realized that this trick may be not so common in other countries, so I decided to write a blog on it. This blog will tell you how to maintain subtree information using LCT, with solutions on some problems, so you should know LCT before reading this blog. ## Main Idea The main idea is simple: record the sum of information of "virtual subtrees", where the "virtual subtrees" refers to the subtrees except the one in the Splay. ![ ](/predownloaded/c7/11/c711f172df1b88ca5fd5a33fa1ceac1b2d472236.png) In the picture, $1$, $2$, $6$, $10$ are in a Splay, while $8$ and $12$ are in another. The "virtual subtrees" of $1$ is $3$ and $4$, the "virtual subtrees" of $4$ is $7$ and $8$, the node $8$ has no "virtual subtree". You need to update the i...
```cpp #include #include

Full text and comments »

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

98.
By AkiLotus, history, 2 years ago, In English
Codeforces Round 983 (Div. 2) Editorial <spoiler summary="README: Notice about solutions"> All editorial codes contain solutions wrapped in classes. I'll only paste the important part (`namespace solution` in C++, `class Solution` in Python 3) as plaintext in the solution code section (along with the corresponding AC submission link). You might want to see the code template here. <spoiler summary="C++ template"> ```cpp #include <bits/stdc++.h> using namespace std; namespace solution { bool hasMultipleTests = true; void preprocess() { // something } void input(int testcase) { // something } void solve(int testcase) { // something } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solution::preprocess(); int t = 1; if (solution::hasMultipleTests) cin >> t; for (int testcase=1; testcase<=t; testcase++) { solution::input(testcase); solution::solve(testcase); } return 0...
```cpp #include using namespace std;, ```cpp namespace solution { bool hasMultipleTests = true;

Full text and comments »

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

99.
By tweety, history, 6 years ago, In English
O(1) runtime prime checking Hello fellow people of Codeforces I hope everyone doing well in these uncertain and unprecedented times. I wanted to share this cool C++20 trick that I learned recently. Check out this cool implementation of `is_prime(n)` to test if `n` integer is prime in O(1) runtime (without any runtime precomputation!) <spoiler summary="bool is_prime(int n);"> ~~~~~ #include <iostream> #include <cstdlib> #include <ctime> const int MAXN = 100000; template<int N> struct Sieve { bool is_prime[N]; constexpr Sieve() : is_prime() { for (int i = 2; i < N; i++) { is_prime[i] = true; } for (int i = 2; i < N; i++) if (is_prime[i]) { for (int j = 2 * i; j < N; j += i) { is_prime[j] = false; } } } }; template<Sieve<MAXN> s> struct SieveWrapper { static bool get(int n) { return s.is_prime[n]; } }; bool is_prime(int n) { return SieveWrapper<Sieve<MAXN>{}>...
://en.cppreference.com/w/cpp/named_req/LiteralType) ([note](https://en.cppreference.com/w/cpp/language

Full text and comments »

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

100.
By Zhtluo, history, 13 months ago, In English
A Few Afterthoughts of ECNA 2025 --- Cheesing, Wrong Problems, etc. I happened to be proctoring ECNA 2025, and here are a few random afterthoughts after the contest&hellip; You can find the full contest on Kattis: [https://naeast25.kattis.com/contests](https://naeast25.kattis.com/contests). ## Problem C &mdash; AROD *Link: [https://open.kattis.com/contests/naeast25open/problems/arod](https://open.kattis.com/contests/naeast25open/problems/arod)* I am slightly surprised that my $O(n^4)$ solution passes the problem with $n=300$. ```cpp #include <bits/stdc++.h> #define upd(mul) \ int s = x1 * y2 - x2 * y1; \ if (s == 0) { \ D += tot * mul; \ continue; \ } \ int c1 = x1 * x2 + y1 * y2; \ int c2 = (x2 - x1) * (-x1) + (y2 - y1) * (-y1); \ int c3 = (x1 - x2) * (-x2) + (y1 - y2) * ...
```cpp #include

Full text and comments »

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

101.
By szdytom, 4 months ago, In English
Codeforces Round 1113 (Div. 2) Editorial [problem:2248A] <spoiler summary="Hint1"> Alice deletes a `0`, Bob deletes a `1`. Which occurrence should each of them choose? </spoiler> <spoiler summary="Hint2"> Deleting a `0` makes the string lexicographically larger. Does the position of that `0` matter? </spoiler> <spoiler summary="Hint3"> After Alice's move, Bob sees one string and deletes a `1`. What is his best move? </spoiler> <spoiler summary="Solution"> Deleting a `0` at an earlier position is always better for Alice. Indeed, compare deleting the `0`s at positions $i < j$: the two results agree before position $i$, and at position $i$ the first result has `1` while the second still has `0`. So Alice deletes the **first** `0`. After that, Bob wants to minimize the string. By the symmetric argument he deletes the **first** `1` of the remaining string, which is the first `1` of the original string, since deleting a `0` never changes the order of the `1`s. Hence the answer is the original string with it...
```cpp #include using namespace std;, ```cpp #include using namespace std;, ```cpp#include using namespace std;

Full text and comments »

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

102.
By McDic, 3 years ago, In English
Some common CP code practices which I think would be better changed Hello. After getting prize on ICPC 2020 Seoul Regional and writing Round #633, I almost stopped solving CP problems and entered quant industry. Now I have no job so I am not busy until I get next job, so I often describe my thoughts on online websites. This article is one of those. In this post, I am going to write about some common CP code practices which I think would be better changed. Before enumerating practices, I want to specify that this post is mostly focused to: 1. Who wants to get dev jobs 2. Who wants to create their practices from CP to productions without switching code style too much (i.e. Not having too different mindset for coding styles in CP and real applications) If you just don't care, it's ok. I am not saying writing CP-style codes is bad, unless you believe you can use same practices on productions. Now let's dive in. ### `using namespace std;` What happens if you include big header files like `bits/stdc++.h` and do this? Bunch of functions, class...
-us/cpp/cpp/pointer-to-member-operators-dot-star-and-star?view=msvc-170) and [constexpr](https, ```cpp #include

Full text and comments »

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

103.
By PoPularPlusPlus, history, 3 years ago, In English
Codeforces Round 882 Editorial [1847:A &mdash; The Man who became a God](https://codeforces.me/contest/1847/problem/A) - Author &mdash; [user:PoPularPlusPlus,2023-07-06] <spoiler summary="tutorial"> [tutorial:1847A] </spoiler> <spoiler summary="solution"> ```cpp #include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb(e) push_back(e) #define sv(a) sort(a.begin(),a.end()) #define sa(a,n) sort(a,a+n) #define mp(a,b) make_pair(a,b) #define all(x) x.begin(),x.end() void solve(){ int n , k; cin >> n >> k; ll arr[n]; for(int i = 0; i < n; i++)cin >> arr[i]; vector<ll> v; ll sum = 0; for(int i = 1; i < n; i++){ v.pb(abs(arr[i] - arr[i-1])); sum += v.back(); } sort(all(v)); for(int groups = 1; groups < k; groups++){ sum -= v.back(); v.pop_back(); } cout << sum << '\n'; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t;cin >> t;while(t--) solve(); return 0; } ```cpp </spoiler>...
```cpp

Full text and comments »

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

104.
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...
```cpp if (a[v] == -1) return void(a[v] = x); ```, ```cpp int Bsz = max(1, (int) sqrt(n)); ```, ```cpp int m(long long x, long long y) { return int((x * y) % M); }, ```cpp int main() { int t; std::cin >> t; for (int i = 1; t--; ++i) {, ```cpp int main() { int t; std::cin >> t; while (t--) {, ```cpp struct B { static vector t, z; static int c; int n;, ```cpp struct BIT { std::vector t;, ```cpp using namespace std;

Full text and comments »

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

105.
By literalchild, history, 6 months ago, In English
Unofficial Editorial for SEATST 2026 # Introduction On 23 and 24 May, 7 countries participated in the **S**outh **E**ast **A**sia **T**eam **S**election **T**est. As the only contestant who AKed both days, I decided to write an editorial for the bugaboos. (The bugaboos are [here](https://tlx.toki.id/bugaboos/seatst-2026).) # 1A (Two Exams) <spoiler summary="Solution"> My solution was the same as [user:blackscreen1,2026-05-27]'s [solution](https://codeforces.me/blog/entry/154034), but I found it in a different way. First, I tried binary searching on the answer, so it reduces to checking if $P[i] - i \leq K$. Rather than setting $P^{-1}[0], P^{-1}[1], \cdots$, giving each index $i$ a deadline of $i + K$, I decided to use the reverse order; first set $P^{-1}[N-1]$, then $P^{-1}[N-2]$, and so on. This means that each index $i$ is only "usable" from "time" $i+K$ onwards. Then, $P^{-1}[i]$ must be the remaining student with highest $A$ or highest $B$. Now, the key observation is that the only way we can "die...
```cpp

Full text and comments »

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

106.
By Osama_Alkhodairy, 7 years ago, In English
Codeforces Round #613 (Div. 2) Editorial [tutorial:1285A] <spoiler summary="code"> ```cpp #include <bits/stdc++.h> using namespace std; #define finish(x) return cout << x << endl, 0 #define ll long long int n; string s; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> s; cout << n + 1 << endl; } ``` </spoiler> [tutorial:1285B] <spoiler summary="code"> ```cpp #include <bits/stdc++.h> using namespace std; #define finish(x) return cout << x << endl, 0 #define ll long long int n; vector <int> a; bool solve(){ cin >> n; a.resize(n); for(auto &i : a) cin >> i; ll sum = 0; for(int i = 0 ; i < n ; i++){ sum += a[i]; if(sum <= 0) return 0; } sum = 0; for(int i = n - 1 ; i >= 0 ; i--){ sum += a[i]; if(sum <= 0) return 0; } return 1; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while(T--){ if(solve()) cout << "YES\n";...
```cpp #include

Full text and comments »

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

107.
By KluydQ, history, 2 months ago, translation, In English
Codeforces Round 1123 (Div. 2) Editorial Thanks a lot for participating! [problem:2267A] - Idea: [user:KluydQ,2026-09-25] - Solution + Editorial: [user:KluydQ,2026-09-25] <spoiler summary="Solution"> [tutorial:2267A] </spoiler> <spoiler summary="Implementation"> ```cpp #include <bits/stdc++.h> using namespace std; signed main() { int T; cin >> T; while (T--) { int n; cin >> n; char c; cin >> c; string s; cin >> s; int ans = 0; for (int i = 0; i < n / 2; ++i) { if (s[i] == s[n - i - 1]) continue; if (s[i] == c || s[n - i - 1] == c) ans++; else ans+=2; } cout << ans << '\n'; } } ``` </spoiler> <spoiler summary="Did you like the problem?"> - Great problem - Good problem - Bad problem - Didn't solve </spoiler> [problem:2267B] - Idea: [user:YF_YUSUF,2026-09-25] - Solution + Editori...
```cpp #include

Full text and comments »

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

108.
By SPyofgame, history, 6 years ago, In English
Simple Linear and Effectively Duval Algorithm for Lyndon Factorization -------------------- -------------------- -------------------- ### <strong> <center style="color:red;"> Table of content </center> </strong> | Teleporter | Description | | :------------------------------------------- | :----------------------------------------------------- | | [I. Lyndon Definitions](#lyndon) | Definitions of Lyndon word, Lyndon factorization, ... | | [II. Duval Algorithm](#duval) | Talk about the duval algorithm and how it works | | [III. Real Life Applications](#rla) | Motivation to learn the algorithm | | [IV. Programming Applications](#application) | The code is short and simple to implement | | [V. My Questions](#question) | Are there any other applications ? | | ................................................................... |.............................
```cpp

Full text and comments »

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

109.
By chromate00, 21 month(s) ago, In English
Codeforces Round 1009 (Div. 3) — Editorial Well, that was a blast, certainly. I hope that you... learned a lot from the contest. I wouldn't say "enjoy the contest", I know most of you hate geometry, I get you. But please do remember that, at least I did try my best to make every problem as high quality as possible. Like, if you don't get familiar with thinking about geometry now, you might never get familiar with it in the future. Though I apologize that E was quite hard, I suggest you to upsolve or read the editorials of the tasks you could not solve. I am telling you, it will be an experience that will make you improve much more from now. <strike>Solution codes will be posted after the open hack phase.</strike> They are now added. <spoiler summary="Spoiler"> ![ ](https://i.ibb.co/MkC41FRk/image.png) </spoiler> ## [problem:2074A] <spoiler summary="Editorial"> [tutorial:2074A] </spoiler> <spoiler summary="Code">```py for i in range(int(input())): l,r,d,u=map(int,input().split()) if l==r==d==u: ...
```cpp #include using namespace std;

Full text and comments »

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

110.
By _istil, 2 years ago, In English
Good Bye 2024: 2025 is NEAR Editorial Thank you for participating in this round! Problems A and G are authored by [user: Cocoly1990,2024-11-23] and the rest by me. Currently, I'm not sure if the editorials are fine enough. Please feel free to tell me where I can improve. <spoiler summary=" Rating Predictions"> | | A | B | C | D | E | F | G | H | I | | :--------------------------------: | :--: | :---------: | :--: | :----------: | :--: | :--: | :----------: | :--: | :----------: | | [user:wyrqwq,2024-12-20] | 800 | 1200 | 1400 | 1700 | 1900 | 2500 | [2800, 3300] | 3200 | [800, 3000] | | [user:Cocoly1990,2024-12-20] | 800 | 1300 | | | | | 3000 | | | | [user:TheScrasse,2024-12-20] | 800 | 1200 | ? | 1800 | | 2500 | 3000 | 3000 | 3500 | | [user:LMydd0225,2024-12-20] | 800 | ...
```cpp #include , ```cpp #include #define int long long, ```cpp #include using namespace std; template class mod_int

Full text and comments »

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

111.
By platelet, history, 4 years ago, In English
speed test code speed test code of [this](https://codeforces.me/blog/entry/111566). ```cpp #include <bits/stdc++.h> using namespace std; const int N = 5e4, P = 998244353; int a[N]; void ThroughputTest() { int checkSum1 = 0, checkSum2 = 0, checkSum3 = 0; auto start = chrono::steady_clock::now(); for(int i = 0; i < N; i += 2) for(int j = 0; j < N; j++) { checkSum1 ^= (int64_t)a[i] * a[j] % P; checkSum1 ^= (int64_t)a[i + 1] * a[j] % P; } auto end = std::chrono::steady_clock::now(); cout << "Compiler's signed modulo: " << (end - start).count() * 1e-6 << " ms" << endl; start = chrono::steady_clock::now(); for(int i = 0; i < N; i += 2) for(int j = 0; j < N; j++) { checkSum2 ^= (uint64_t)(uint32_t)a[i] * (uint32_t)a[j] % P; checkSum2 ^= (uint64_t)(uint32_t)a[i + 1] * (uint32_t)a[j] % P; } end = std::chrono::steady_clock::now(); cout << "Compiler's unsigne...
```cpp #include

Full text and comments »

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

112.
By oversolver, 4 years ago, In English
Outstanding members of my cp library I like to build my [cp library](https://github.com/demidenko/olymp-cpp-lib). I am not aiming to fill it by each algo I have met, so content looks poor. Instead I am focusing on frequently used features or implement convenient api for powerful methods. Also I like to rate cp libraries of others and currently I noticed that my lib have enough implementations which I never seen before, so I want to share it with community. Hope it will inspire you to improve or rewrite your library and eventually rethink about some algorithms (which happens to me couple times). ## #5 Centroid decomposition [graphs/trees/centriod_decomposition.cpp](https://github.com/demidenko/olymp-cpp-lib/blob/master/graphs/trees/centriod_decomposition.cpp) This one is the perfect example of what I am calling convenient api. I've seen a lot of centroid decomposition snippets and almost all of them is template code or unfinished data structure with piece of code where you need to add your solution. I have s...
And finally my favorite... [strings/hasher.cpp](https://github.com/demidenko/olymp-cpp-lib/blob, [graphs/trees/centriod_decomposition.cpp](https://github.com/demidenko/olymp-cpp -lib/blob/master, [misc/parallel_binary_search.cpp](https://github.com/demidenko/olymp-cpp -lib/blob/master/misc, [numeric/ntt.cpp](https://github.com/demidenko/olymp-cpp -lib/blob/master/numeric/ntt.cpp), [structs/ilist.cpp](https://github.com/demidenko/olymp-cpp -lib/blob/master/structs/ilist.cpp)

Full text and comments »

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

113.
By Agnimandur, history, 5 years ago, In English
April Fools Day Contest 2022 Editorial All problems were created and prepared by me and [user:magnus.hegdahl,2022-04-01]. Thanks to [user:BucketPotato,2022-04-01], [user:Monogon,2022-04-01], and [user:Priyam2k,2022-04-01] for valuable feedback and testing. Special thanks to [user:MikeMirzayanov,2022-04-01] for coming up with the idea and preparing the unique checker for [problem:1663H]. I hope you enjoyed the contest, and found it to be an interesting series of puzzles. Example solution code written by [user:Agnimandur,2022-04-01] is provided for each problem. ### [problem:1663A] <spoiler summary="Clue 1"> The problem statement is the title of the problem. </spoiler> <spoiler summary="Clue 2"> Re-read the original announcement blog. </spoiler> <spoiler summary="Solution"> If you carefully read [the announcement blog](https://codeforces.me/blog/entry/101364), you will notice that I especially thanked [user:BucketPotato,2022-04-01] for testing. Just print "BucketPotato". </spoiler> <spoiler summary=...
~~~~~cpp #include using namespace std;, ~~~~~cpp // \ begin end. int main() {} ~~~~~

Full text and comments »

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

114.
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...
```cpp #include using namespace std; const

Full text and comments »

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

115.
By box, history, 6 years ago, In English
[Tutorial] Square root decomposition and applications A brief introduction into the applications of square root decomposition ================== Square root decomposition is the process of separating a structure of size $O(N)$ into $O(\sqrt{N})$ "blocks" of size $O(\sqrt{N})$ each, in a way that aids manipulation of the entire structure. Square root decomposition is extremely versatile. Some of its most well-known use cases are: - answering queries on a static array, with methods such as Mo's algorithm or block precomputation - "lazy" brute force modifications, where it is easy to query an entire block, but tag pushing isn't obvious - separating objects based on a threshold, when there exists both an $O(x)$ algorithm and an $O(n/x)$ algorithm In this tutorial we will walk through multiple types of square root decomposition. Answering queries on a static array, offline (Mo's algorithm) --- Consider a problem where we are asked to find the answer for certain intervals $[l,r]$. We can't quickly compute the answer for an ar...
```cpp int B = ???; struct query { int l, r, id; const bool operator<(const query& o

Full text and comments »

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

116.
By purplesyringa, history, 5 years ago, In Russian
Платформы по программированию в анекдотах ## AtCoder ### Условие Даны числа A и B. Выведите A + B. ### Разбор В задаче требуется вывести сумму двух чисел. Обратите внимание: в языках C и C++ необходимо использовать достаточно большие типы данных. Решение: ```python print(int(input()) + int(input())) ``` <!-- x --> [cut] <!-- x --> --- ## Algocode ### Условие Яна стоит на числовой прямой в координате 0. Так как у Яны день рождения, ей дарят яблоки мальчики Петя и Вася. Яна любит только зеленые яблоки, но не любит красные. У Пети есть N зеленых яблок, а у Васи M красных. Одно красное яблоко сдвигает ее из координаты i в координату i-1, одно зеленое яблоко сдвигает ее из координаты i в координату i+1. Напишите, при каких N и M координата на числовой прямой будет положительной; отрицательной; равна нулю. **Все утверждения строго доказывать!** ### Разбор --- ## Codeforces ### Условие Петя и Вася решили подарить Кате на день рождения яблоки, Петя подарил N яблок, а Вася &mdash; M. ...
```cpp #include using namespace std; int main() { int a, b; cin >> a, ```cpp #pragma GCC optimize("kek") #include using namespace std; #define ll long

Full text and comments »

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

117.
By Al.Cash, 10 years ago, In English
Geometry: 2D points and lines [Tutorial] I get an impression that a lot of coders struggle with geometric problems and prefer to avoid them. That's not much of a surprise, considering that I couldn't find a good writing explaining the basics and giving useful advice how to proceed. Moreover, some resources obfuscate this beautiful area to the point it's despised by the readers. I'll try to change that, but first I'll mention some of the better resources: [geomalgorithms.com](http://geomalgorithms.com/points_and_vectors.html) This is where you can start if you don't have a basic notion of a vector. Also there are more detailed explanations for some examples I'll list, but I dislike the implementations. [This post in Russian](http://codeforces.me/blog/entry/6642) has a link to the code that's most similar to mine, with some comments (unfortunately, also is Russian)[cut]. ### Point structure and operations Without further ado, I'll start with my code for the `Point` structure. Explanations are below, so don't rush t...
://en.cppreference.com/w/cpp/algorithm/partition) calls. Think why the first one is necessary (it

Full text and comments »

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

118.
By MathModel, history, 13 months ago, In English
Codeforces Round 1061 (Div. 2) Editorial ### Thank you for participating ! Special Thanks to [user:hxu10,2025-10-24] for giving me the chance to write the editorial and for [user:maomao90,2025-10-24] for enhancing the editorial !. Editorial of Problems E and F are written by hxu10, and the rest are written by me. I hope they're insightful and concise, please let me hear your opinion about it or any feedback in general &#128153;. #### [problem:2156A] <spoiler summary="Hints"> <spoiler summary="Hint 1"> Since $m_1 \le m_2$, the total number of slices Alice ate is always at least as much as the total number of slices Bob ate. What's optimal construction ? </spoiler> <spoiler summary="Hint 2"> We want to try to minimize the difference between the total number of slices Alice ate and the total number of slices Bob ate. </spoiler> <spoiler summary="Hint 3"> The optimal construction is to let both $m_1$ and $m_2$ to be equals to one. The sequence of operations, denoted by $(m_1, m...
```cpp #include using namespace std; #define int long long

Full text and comments »

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

119.
By 36champ, 6 months ago, In English
Codeforces Round 1101 (Div. 2) — Editorial [Problem A &mdash; Convergence](https://codeforces.me/contest/2232/problem/A) Problem Idea: [user:36champ,2026-05-30] <br> Solution Idea: [user:36champ,2026-05-30] <spoiler summary="Hint 1"> What if the meeting location is fixed? </spoiler> <spoiler summary="Solution"> If the meeting location is fixed, the answer is max(the number of people to the left of that position, the number of people to the right of that position. This can be solved in $O(n^2)$ by iterating through all position that has at least one person on it. This problem can also be solved in $O(n\log n)$ by sorting and setting the meeting position to the median of all positions. </spoiler> <spoiler summary="Code"> ```cpp #include <bits/stdc++.h> #define pb push_back using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ll> vll; typedef vector<vll> vvll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; int main() { ios_ba...
```cpp #include #define pb push_back

Full text and comments »

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

120.
By PinkRabbitAFO, history, 7 years ago, In English
Codeforces Round #635 Problem "Mahjong Set" Ununofficial Editorial Hello there, here's an unofficial editorial for [1136D. Yui and Mahjong Set](https://codeforces.me/contest/1336/problem/D) by a tester [user:PinkRabbit,2020-04-16]. Observation: Focus on the differential of triplets/straights before and after an operation. By doing an operation on $a_i$, you'll find that the differential of triplets equals $x (x - 1) / 2$, where $x$ equals $a_i$ before the operation. So if we did a single operation on $a_i$, we can get the exact value of initial $a_i$ iff initial $a_i \ge 2$, otherwise initial $a_i$ must be equal to $0$ or $1$. If we did two (or more, but unnecessary?) operation on $a_i$, we can now get the exact value of initial $a_i$ no matter whether $a_i$ is less than $2$ or not. One of the most natural ideas is to perform operation in the order of $1, 2, \ldots, n$, it works like this: - Now, assume we get the exact value of $a_1 \sim a_i$, and we want to determine $a_{i + 1}$. - If $a_{i + 1} \ge 2$, done. Just consider the ...
```cpp #include

Full text and comments »

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

121.
By physics0523, history, 3 years ago, In English
TheForces Round #26 Editorial [problem:104802A] Writer: [user:wuhudsm,2023-11-14] <spoiler summary="Editorial"> We use two pointers to solve this problem. Set $l=1$ and $r=n$ initially. - If $a_l=a_r$, <code>l++,r--;</code> - If $a_l<a_r$,split $a_r$ into $a_r-a_l$ and $a_l$, <code>r--;</code> - If $a_l>a_r$,split $a_l$ into $a_r$ and $a_l-a_r$, <code>l++;</code> When $l \geq r$,the process ends. </spoiler> <spoiler summary="Rate the problem"> Good problem! : Average problem : Bad problem... : </spoiler> [problem:104802B] Writer: [user:pavlekn,2023-11-14] <spoiler summary="Editorial"> Let $M$ be the initial mass of the bus with all passengers: $M = w + \sum_{i = 1}^{n}{m_i}$. Let $F$ be the total force of the pushers, initially, $F=0$. Imagine getting out the $i$-th passenger out of the bus, then $M$ is decreased by $m_i$, while $F$ is increased by $f_i$. Hence, $M - F$ is decreased by $m_i + f_i$. Clearly, we want to make ...
```cpp #include, ```cpp // factorize // https://judge.yosupo.jp/problem/factorize

Full text and comments »

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

122.
By UnexpectedValue, 4 years ago, In English
CSES DP Section Editorial (Part 2) While looking up an editorial for a CSES task, I recently stumbled upon [CSES DP Section editorial](https://codeforces.me/blog/entry/70018) blog by [user:icecuber,2023-02-07]. Noticing that a few new tasks had been added since the blog was posted 2 years back; I decided to take his permission and write this blog, which contains editorials to the newly added tasks and acts as a sequel to his blog. I would like to thank [user:dominique38,2023-02-10] for being the most enthusiastic co-author possible, [user:defnotmee,2023-04-29] for being the second most enthusiastic co-author (he wanted the title himself), [user:Perpetually_Purple,2023-02-10] for helping me out and giving suggestions, [user:AntennaeVY,2023-02-10] for suggestions on the understandability and formatting of the blog; and finally, [user:icecuber,2023-02-10] himself for going over the blog and giving me confidence in the form of a final thumbs-up! The editorials may at some point appear excessively lengthy, but that is...
[Link to CPP Code (iterative)](https://cses.fi/paste/ac61c8124963d957537de7/) [Link to CPP

Full text and comments »

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

123.
By Sanae, history, 16 months ago, In English
Set algorithm(rev.2) # Set algorithm Part I Sometimes we may meet with some functions $S\rightarrow V$(S is a set,V is a value),and we need to handle some transformations on it. The article is for beginners whick is much easy, and I may continously update the article. There are some features. First the problem always give small $n$,such as $n\leq 15,n\leq20$. Second,the time complexity is always $O(n2^n),O(3^n),O(n^22^n)$. Let's do some assumption: The values form a ring and they contain ring operations like addition,substraction,multification or division in constant time. ## FWT/FMT The most classical one is FWT/FMT. ### Problem Define $a(S),b(S)(S\subseteq U)$ on a set. Get all $c(S)=\sum\limits_{i \oplus j=S}a_ib_j\qquad \oplus \text{is} \ \textrm{and,or,xor}$ The general idea: Let $a, b, c$ be maps (functions) from a set $S$ to a value domain $V=(N/Q/C\cdots)$. We define a transformation $\text{FWT}$ (Fast Walsh Transform) as a map from the space of such functi...
I like cpp,so I use `|` for $\textrm{or}$,`&` for $\textrm{and}$,`^` for $\textrm{xor}$.

Full text and comments »

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

124.
By Fakewave, 6 months ago, translation, In English
Codeforces Round 1102 (Div. 2) Editorial Thank you for participating in our round! We hope you enjoyed the problems. [problem:2234A] Idea: [user:FairyWinx,2026-06-07] <spoiler summary="Hint 1"> Note that $(a_i \bmod a_{i + 1}) < a_{i + 1}$. </spoiler> <spoiler summary="Hint 2"> $a_{i + 2} = (a_i \bmod a_{i + 1}) < a_{i + 1}$ and $a_2 \le a_1$ mean that the sequence $a$ must be non-increasing. On the other hand, there is only one permutation of the sequence $b$ that can be non-increasing. </spoiler> <spoiler summary="Solution"> [tutorial:2234A] </spoiler> <spoiler summary="Code (Python)"> ```python t = int(input()) for tt in range(t): n = int(input()) a = list(map(int, input().split())) a.sort() a = a[::-1] valid = True for i in range(2, n): if a[i] != a[i - 2] % a[i - 1]: print(-1) valid = False break if valid: print(a[0], a[1]) ``` </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <iostream> ...
```cpp #include

Full text and comments »

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

125.
By EmeraldBlock, history, 3 years ago, In English
IOI 2023 Robot Contest in Z* = 5 [IOI 2023 Robot Contest](https://ioi2023.hu/tasks/#:~:text=robot%20%E2%80%93%20Robot%20Contest) is a great task that reminds me of Turing machines and cellular automata. <spoiler summary="If the task statement is too intimidating..."> Your goal is to program the robot _Pulibot_ to label a shortest path between the northwest and southeast corners of a 2D grid with obstacles, which are guaranteed to be reachable from each other. However, Pulibot is short-sighted and has no memory. Knowing only the colors of the cell it is at and the 4 adjacent cells (including special "colors" for out-of-bounds cells and obstacles), it has to decide what to recolor its current cell and which direction to move in (including not moving, as well as terminating). Pulibot cannot move out-of-bounds or into obstacles. Initially, all empty cells are colored "blank", and Pulibot starts at the northwest corner. After Pulibot terminates, the cells colored "path" must form a shortest path, while th...
```cpp #include "robot.h" #include

Full text and comments »

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

126.
By gepardo, history, 8 years ago, In English
ParmPars: a library to pass parameters to generators Hello, Codeforces! If you tried to prepare some competitive programming problems, you might parse parameters like this: ```cpp #include "testlib.h" #include <cstdlib> using namespace std; int main(int argc, char **argv) { registerGen(argc, argv, 1); int n = atoi(argv[1]); int m = atoi(argv[2]); int k = atoi(argv[3]); ... ``` Of course, such way has many disadvantages: * You need to pass the exact amount of parameters, you cannot define default values for them. * If you have many parameters, it's easy to forget the order. * If you pass too few of the them, it will be undefined behavior. So I developed a library called ParmPars to pass parameters to generators in a more convenient way. You can find it on [GitHub](https://github.com/alex65536/parmpars). I hope it will help you to generate tests better. [cut] <br> Using ParmPars, you could rewrite the code above in the following way: ```cpp #include "testlib.h" #include "parmpars.hpp" ...
```cpp #include "testlib.h" #include

Full text and comments »

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

127.
By chromate00, 10 months ago, In English
Codeforces Round 1080 (Div. 3) Editorial I hope you enjoyed any number of problems in the contest! <strike>Solution codes will be posted after the open hack phase.</strike> They have now been added. ## [problem:2195A] <spoiler summary="Rate the problem!"> - Epic - Good - Moderate - Bad - Horrendous </spoiler> <spoiler summary="Editorial"> [tutorial:2195A] </spoiler> <spoiler summary="Code"> ```py for _ in range(int(input())): n=int(input()) a=[*map(int,input().split())] if 67 in a: print("YES") else: print("NO") ``` </spoiler> ## [problem:2195B] <spoiler summary="Rate the problem!"> - Epic - Good - Moderate - Bad - Horrendous </spoiler> <spoiler summary="Editorial"> [tutorial:2195B] </spoiler> <spoiler summary="Code"> ```cpp #include<bits/stdc++.h> using namespace std; using ll...
```cpp #include using namespace std;

Full text and comments »

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

128.
By dreamoon_love_AA, history, 11 years ago, In English
Codeforces Round #320 [Bayan Thanks-Round] Editorial ## [Problm 1 : Raising Bacteria](http://codeforces.me/problemset/problem/579/A) Write down $x$ into its binary form. If the $i^{th}$ least significant bit is $1$ and $x$ contains $n$ bits, we put one bacteria into this box in the morning of $(n+1-i)^{th}$ day. Then at the noon of the $n^{th}$ day, the box will contain $x$ bacteria. So the answer is the number of ones in the binary form of $x$. [code of author's friend: this](http://codeforces.me/contest/579/submission/13053439) ## [Problem 2 : Finding Team Member](http://codeforces.me/problemset/problem/579/B) Sort all possible combinations from high strength to low strength. Then iterator all combinations. If two people in a combination still are not contained in any team. then we make these two people as a team. [author's code: this](http://codeforces.me/contest/579/submission/13053526) ## [Problem 3 : A Problem about Polyline](http://codeforces.me/problemset/problem/578/A) If point ($a$,$b$) is located on t...
``` cpp #include typedef long long LL; using namespace std; int main(){ LL

Full text and comments »

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

129.
By brunomont, history, 3 days ago, In English
[Algorithm note] You can stably split implicit BSTs by value Hello, Codeforces! A few years ago I asked [here](https://codeforces.me/blog/entry/111450) whether a stable partition by value on a treap could be better than linear amortized. For integer values in $[0,U)$, I guessed that the algorithm would cut between adjacent elements only $\mathcal O(\log U)$ times per operation on average. That would give $\mathcal O(\log U\log n)$ expected amortized time, but I couldn't prove the bound on the number of cuts. It turns out we can prove $\mathcal O(\sqrt n\log n)$ expected amortized time per operation. Here is a precise version of the problem. Maintain a collection of sequences containing $n$ elements in total, with every sequence represented by a regular implicit treap. We want to support the following operations: 1. Split by index: first $k$ elements / remaining suffix; 2. Concatenate two sequences; 3. Reverse an entire sequence; 4. Set the value at a given index; 5. Query the sum over an index range; 6. **Stable partition by value...
```cpp std::pair split_value(Node* t, long long x) { if (!t) return {nullptr

Full text and comments »

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

130.
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...
factor, one could use partial sorting methods, such as [nth_element](https://en.cppreference.com/w/cpp

Full text and comments »

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

131.
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...
```cpp #include using namespace std;

Full text and comments »

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

132.
By EnDeRBeaT, 2 years ago, In English
Tutorial: Stealing the coolest debug feature from Rust # Introduction Rust is a quite popular programming language with a lot of different takes on how to write good code. Some people use it in competitive programming with varying success, but in general, C++ is the king. That doesn't mean that we can't take great ideas from this language, and one of Rust's shining jewels is it's macro system. Describing why it is better than "find and replace" thing we have in C++ is not the topic of this blog. We are here to steal from Rust, and today we will steal one of the coolest utilities for a competitive programmer: `dbg!` macro! # dbg! The `dbg!` macro in Rust has simple functionality: it evaluates the expression, prints it's to `stderr` and **returns it**. Last part is very, **very** useful, and you will see why. Example: ~~~~~ let a = 2; let b = dbg!(a * 2) + 1; // ^-- prints: [src/main.rs:2:9] a * 2 = 4 assert_eq!(b, 5); ~~~~~ Look, we evaluated `a * 2` mid expression and `b` still became `5`. Isn't that cool? ...
([link](https://en.cppreference.com/w/cpp /preprocessor/replace#Scanning_and_Replacement)), you can create

Full text and comments »

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

133.
By oToToT, 7 years ago, In English
[Tutorial] Two ways to apply Mo's Algorithm on Trees # 1. Use the trick of Tree SQRT-Decomposition I didn't find any Codeforces post describing this method, so I'm here to share this method. Also, I hope people could help me learn more about tree sqrt-decomposition. ## Main Idea The main idea of Mo's algorithm is to decompose sequence with size $N$ into $O(K)$ contiguous blocks, and if we re-order our queries $[L_i,R_i]$ with pair $(\text{BlockID}(L_i), R_i)$ and maintain two pointer of $L$ and $R$, we could get a $O(Q \frac{N}{K} + KN)$ complexity to solve some sequence problem. It is because that every queries with the same $\text{BlockID}(L_i)$ shares the cost of moving the pointer of $R$ from leftmost to rightmost, so the pointer of $R$ will move at most $O(NK)$ elements. Also, the pointer of $L$ won't move more than $O(\frac{N}{K})$ elements when changing from one query range to another query range. So, if we have a way to preserve these two properties ( i.e. we could share the cost of moving a pointer $R$ when those ...
```cpp int BlockID[N], BlockCount = 0;

Full text and comments »

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

134.
By adnan_toky, 4 years ago, In English
Codeforces Round #848 (Div. 2) Editorial [problem:1778A] <spoiler summary="Tutorial"> [tutorial: 1778A] </spoiler> <spoiler summary="Code"> ```C++ #include <bits/stdc++.h> using namespace std; const int sz = 1e5 + 10; int ara[sz]; int main() { int t; scanf("%d", &t); while(t--) { int n; scanf("%d", &n); int sum = 0; for(int i = 1; i <= n; i++) { scanf("%d", &ara[i]); sum += ara[i]; } int ans = -1e9; for(int i = 1; i < n; i++) { if(ara[i] == ara[i+1]) { if(ara[i] == 1) ans = max(ans, sum-4); else ans = max(ans, sum+4); } else ans = max(ans, sum); } printf("%d\n", ans); } return 0; } ``` </spoiler> [problem:1778B] <spoiler summary="Tutorial"> [tutorial: 1778B] </spoiler> <spoiler summary="Code"> ```C++ #include <bits/stdc++.h> using namespace std; ...
```cpp #include using namespace std;

Full text and comments »

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

135.
By dendi239, history, 6 years ago, In English
Micro- and macro-management for your next cpp source: For Hello, codeforces! In this article, I would like to show you how to reduce time spent on working with `for` cycle. There're a few ways to do it, I'll show macro-based and expressible in pure c++. # Introduction I love `for` cycle. It looks quite simple: ~~~~ for (init statement; condition; increment) ~~~~ But you can adapt it to do many great things. To illustrate the power of `for`, let's look at the simple binary search problem: we have some values `l`, `r` and a predicate `p` which is true on segment `[l, x]` and false on `(x, r)`, and we are asked to find x. Using `for` we can implement the solution in basically just one line: ~~~~~ for (int m = (l + r) / 2; abs(r - l) > 1; (p(m) ? l : r) = m, m = (l + r) / 2); ~~~~~ Pretty neat, huh? After the cycle finishes, you'll get `l = x`. Another important note, the `(p(m) ? l : r) = m` part works because ternary operator returns reference type. It means that `(is_left ? left : right) = new_value;` assigns `ne...
Micro- and macro-management for your next cpp source: For, We already have a convenient [range-based for](https://en.cppreference.com/w/cpp /language/range-for

Full text and comments »

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

136.
By physics0523, history, 3 years ago, In English
TheForces Round #27 Editorial [problem:104855A] <spoiler summary="Editorial"> First,it's not hard to come up with query `? 1`.Assume we have got $t$,the answer is either $2t$ or $2t-1$. Then we can query `? 2t`.It can be proven the answer of `? 2t` is always different from `? 2t-1`. Another approach:query `? 2` or `? 2m-1`.Although it doesn't work in some small cases,you can do another query to avoid conflict. </spoiler> <spoiler summary="Rate the problem"> Good problem! : Average problem : Bad problem... : </spoiler> [problem:104855B] <spoiler summary="Editorial"> Every time choosing adjacent cell to blue cell is optimal because it can stop the growth of blue cell in that particular direction, so obviously if $k>=4$ we can surround the blue cell so answer will be $nm-1$. For $k=1$ we will take the portion (up side, down side, left side, right side) of cells to initial blue cell containing maximum white cells, similarly for $k=...
```cpp #include

Full text and comments »

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